src/share/vm/opto/escape.cpp

Tue, 09 Oct 2012 12:40:05 -0700

author
vlivanov
date
Tue, 09 Oct 2012 12:40:05 -0700
changeset 4160
f6badecb7ea7
parent 4159
8e47bac5643a
child 4205
a3ecd773a7b9
permissions
-rw-r--r--

7199654: Remove LoadUI2LNode
Summary: Removed LoadUI2L node from Ideal nodes, use match rule in .ad files instead.
Reviewed-by: kvn

     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 // Utility function for nodes that load an object
   286 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
   287   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   288   // ThreadLocal has RawPtr type.
   289   const Type* t = _igvn->type(n);
   290   if (t->make_ptr() != NULL) {
   291     Node* adr = n->in(MemNode::Address);
   292 #ifdef ASSERT
   293     if (!adr->is_AddP()) {
   294       assert(_igvn->type(adr)->isa_rawptr(), "sanity");
   295     } else {
   296       assert((ptnode_adr(adr->_idx) == NULL ||
   297               ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
   298     }
   299 #endif
   300     add_local_var_and_edge(n, PointsToNode::NoEscape,
   301                            adr, delayed_worklist);
   302   }
   303 }
   305 // Populate Connection Graph with PointsTo nodes and create simple
   306 // connection graph edges.
   307 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
   308   assert(!_verify, "this method sould not be called for verification");
   309   PhaseGVN* igvn = _igvn;
   310   uint n_idx = n->_idx;
   311   PointsToNode* n_ptn = ptnode_adr(n_idx);
   312   if (n_ptn != NULL)
   313     return; // No need to redefine PointsTo node during first iteration.
   315   if (n->is_Call()) {
   316     // Arguments to allocation and locking don't escape.
   317     if (n->is_AbstractLock()) {
   318       // Put Lock and Unlock nodes on IGVN worklist to process them during
   319       // first IGVN optimization when escape information is still available.
   320       record_for_optimizer(n);
   321     } else if (n->is_Allocate()) {
   322       add_call_node(n->as_Call());
   323       record_for_optimizer(n);
   324     } else {
   325       if (n->is_CallStaticJava()) {
   326         const char* name = n->as_CallStaticJava()->_name;
   327         if (name != NULL && strcmp(name, "uncommon_trap") == 0)
   328           return; // Skip uncommon traps
   329       }
   330       // Don't mark as processed since call's arguments have to be processed.
   331       delayed_worklist->push(n);
   332       // Check if a call returns an object.
   333       if (n->as_Call()->returns_pointer() &&
   334           n->as_Call()->proj_out(TypeFunc::Parms) != NULL) {
   335         add_call_node(n->as_Call());
   336       }
   337     }
   338     return;
   339   }
   340   // Put this check here to process call arguments since some call nodes
   341   // point to phantom_obj.
   342   if (n_ptn == phantom_obj || n_ptn == null_obj)
   343     return; // Skip predefined nodes.
   345   int opcode = n->Opcode();
   346   switch (opcode) {
   347     case Op_AddP: {
   348       Node* base = get_addp_base(n);
   349       PointsToNode* ptn_base = ptnode_adr(base->_idx);
   350       // Field nodes are created for all field types. They are used in
   351       // adjust_scalar_replaceable_state() and split_unique_types().
   352       // Note, non-oop fields will have only base edges in Connection
   353       // Graph because such fields are not used for oop loads and stores.
   354       int offset = address_offset(n, igvn);
   355       add_field(n, PointsToNode::NoEscape, offset);
   356       if (ptn_base == NULL) {
   357         delayed_worklist->push(n); // Process it later.
   358       } else {
   359         n_ptn = ptnode_adr(n_idx);
   360         add_base(n_ptn->as_Field(), ptn_base);
   361       }
   362       break;
   363     }
   364     case Op_CastX2P: {
   365       map_ideal_node(n, phantom_obj);
   366       break;
   367     }
   368     case Op_CastPP:
   369     case Op_CheckCastPP:
   370     case Op_EncodeP:
   371     case Op_DecodeN:
   372     case Op_EncodePKlass:
   373     case Op_DecodeNKlass: {
   374       add_local_var_and_edge(n, PointsToNode::NoEscape,
   375                              n->in(1), delayed_worklist);
   376       break;
   377     }
   378     case Op_CMoveP: {
   379       add_local_var(n, PointsToNode::NoEscape);
   380       // Do not add edges during first iteration because some could be
   381       // not defined yet.
   382       delayed_worklist->push(n);
   383       break;
   384     }
   385     case Op_ConP:
   386     case Op_ConN:
   387     case Op_ConNKlass: {
   388       // assume all oop constants globally escape except for null
   389       PointsToNode::EscapeState es;
   390       if (igvn->type(n) == TypePtr::NULL_PTR ||
   391           igvn->type(n) == TypeNarrowOop::NULL_PTR) {
   392         es = PointsToNode::NoEscape;
   393       } else {
   394         es = PointsToNode::GlobalEscape;
   395       }
   396       add_java_object(n, es);
   397       break;
   398     }
   399     case Op_CreateEx: {
   400       // assume that all exception objects globally escape
   401       add_java_object(n, PointsToNode::GlobalEscape);
   402       break;
   403     }
   404     case Op_LoadKlass:
   405     case Op_LoadNKlass: {
   406       // Unknown class is loaded
   407       map_ideal_node(n, phantom_obj);
   408       break;
   409     }
   410     case Op_LoadP:
   411     case Op_LoadN:
   412     case Op_LoadPLocked: {
   413       add_objload_to_connection_graph(n, delayed_worklist);
   414       break;
   415     }
   416     case Op_Parm: {
   417       map_ideal_node(n, phantom_obj);
   418       break;
   419     }
   420     case Op_PartialSubtypeCheck: {
   421       // Produces Null or notNull and is used in only in CmpP so
   422       // phantom_obj could be used.
   423       map_ideal_node(n, phantom_obj); // Result is unknown
   424       break;
   425     }
   426     case Op_Phi: {
   427       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   428       // ThreadLocal has RawPtr type.
   429       const Type* t = n->as_Phi()->type();
   430       if (t->make_ptr() != NULL) {
   431         add_local_var(n, PointsToNode::NoEscape);
   432         // Do not add edges during first iteration because some could be
   433         // not defined yet.
   434         delayed_worklist->push(n);
   435       }
   436       break;
   437     }
   438     case Op_Proj: {
   439       // we are only interested in the oop result projection from a call
   440       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
   441           n->in(0)->as_Call()->returns_pointer()) {
   442         add_local_var_and_edge(n, PointsToNode::NoEscape,
   443                                n->in(0), delayed_worklist);
   444       }
   445       break;
   446     }
   447     case Op_Rethrow: // Exception object escapes
   448     case Op_Return: {
   449       if (n->req() > TypeFunc::Parms &&
   450           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
   451         // Treat Return value as LocalVar with GlobalEscape escape state.
   452         add_local_var_and_edge(n, PointsToNode::GlobalEscape,
   453                                n->in(TypeFunc::Parms), delayed_worklist);
   454       }
   455       break;
   456     }
   457     case Op_GetAndSetP:
   458     case Op_GetAndSetN: {
   459       add_objload_to_connection_graph(n, delayed_worklist);
   460       // fallthrough
   461     }
   462     case Op_StoreP:
   463     case Op_StoreN:
   464     case Op_StoreNKlass:
   465     case Op_StorePConditional:
   466     case Op_CompareAndSwapP:
   467     case Op_CompareAndSwapN: {
   468       Node* adr = n->in(MemNode::Address);
   469       const Type *adr_type = igvn->type(adr);
   470       adr_type = adr_type->make_ptr();
   471       if (adr_type->isa_oopptr() ||
   472           (opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) &&
   473                         (adr_type == TypeRawPtr::NOTNULL &&
   474                          adr->in(AddPNode::Address)->is_Proj() &&
   475                          adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
   476         delayed_worklist->push(n); // Process it later.
   477 #ifdef ASSERT
   478         assert(adr->is_AddP(), "expecting an AddP");
   479         if (adr_type == TypeRawPtr::NOTNULL) {
   480           // Verify a raw address for a store captured by Initialize node.
   481           int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
   482           assert(offs != Type::OffsetBot, "offset must be a constant");
   483         }
   484 #endif
   485       } else {
   486         // Ignore copy the displaced header to the BoxNode (OSR compilation).
   487         if (adr->is_BoxLock())
   488           break;
   489         // Stored value escapes in unsafe access.
   490         if ((opcode == Op_StoreP) && (adr_type == TypeRawPtr::BOTTOM)) {
   491           // Pointer stores in G1 barriers looks like unsafe access.
   492           // Ignore such stores to be able scalar replace non-escaping
   493           // allocations.
   494           if (UseG1GC && adr->is_AddP()) {
   495             Node* base = get_addp_base(adr);
   496             if (base->Opcode() == Op_LoadP &&
   497                 base->in(MemNode::Address)->is_AddP()) {
   498               adr = base->in(MemNode::Address);
   499               Node* tls = get_addp_base(adr);
   500               if (tls->Opcode() == Op_ThreadLocal) {
   501                 int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
   502                 if (offs == in_bytes(JavaThread::satb_mark_queue_offset() +
   503                                      PtrQueue::byte_offset_of_buf())) {
   504                   break; // G1 pre barier previous oop value store.
   505                 }
   506                 if (offs == in_bytes(JavaThread::dirty_card_queue_offset() +
   507                                      PtrQueue::byte_offset_of_buf())) {
   508                   break; // G1 post barier card address store.
   509                 }
   510               }
   511             }
   512           }
   513           delayed_worklist->push(n); // Process unsafe access later.
   514           break;
   515         }
   516 #ifdef ASSERT
   517         n->dump(1);
   518         assert(false, "not unsafe or G1 barrier raw StoreP");
   519 #endif
   520       }
   521       break;
   522     }
   523     case Op_AryEq:
   524     case Op_StrComp:
   525     case Op_StrEquals:
   526     case Op_StrIndexOf: {
   527       add_local_var(n, PointsToNode::ArgEscape);
   528       delayed_worklist->push(n); // Process it later.
   529       break;
   530     }
   531     case Op_ThreadLocal: {
   532       add_java_object(n, PointsToNode::ArgEscape);
   533       break;
   534     }
   535     default:
   536       ; // Do nothing for nodes not related to EA.
   537   }
   538   return;
   539 }
   541 #ifdef ASSERT
   542 #define ELSE_FAIL(name)                               \
   543       /* Should not be called for not pointer type. */  \
   544       n->dump(1);                                       \
   545       assert(false, name);                              \
   546       break;
   547 #else
   548 #define ELSE_FAIL(name) \
   549       break;
   550 #endif
   552 // Add final simple edges to graph.
   553 void ConnectionGraph::add_final_edges(Node *n) {
   554   PointsToNode* n_ptn = ptnode_adr(n->_idx);
   555 #ifdef ASSERT
   556   if (_verify && n_ptn->is_JavaObject())
   557     return; // This method does not change graph for JavaObject.
   558 #endif
   560   if (n->is_Call()) {
   561     process_call_arguments(n->as_Call());
   562     return;
   563   }
   564   assert(n->is_Store() || n->is_LoadStore() ||
   565          (n_ptn != NULL) && (n_ptn->ideal_node() != NULL),
   566          "node should be registered already");
   567   int opcode = n->Opcode();
   568   switch (opcode) {
   569     case Op_AddP: {
   570       Node* base = get_addp_base(n);
   571       PointsToNode* ptn_base = ptnode_adr(base->_idx);
   572       assert(ptn_base != NULL, "field's base should be registered");
   573       add_base(n_ptn->as_Field(), ptn_base);
   574       break;
   575     }
   576     case Op_CastPP:
   577     case Op_CheckCastPP:
   578     case Op_EncodeP:
   579     case Op_DecodeN:
   580     case Op_EncodePKlass:
   581     case Op_DecodeNKlass: {
   582       add_local_var_and_edge(n, PointsToNode::NoEscape,
   583                              n->in(1), NULL);
   584       break;
   585     }
   586     case Op_CMoveP: {
   587       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
   588         Node* in = n->in(i);
   589         if (in == NULL)
   590           continue;  // ignore NULL
   591         Node* uncast_in = in->uncast();
   592         if (uncast_in->is_top() || uncast_in == n)
   593           continue;  // ignore top or inputs which go back this node
   594         PointsToNode* ptn = ptnode_adr(in->_idx);
   595         assert(ptn != NULL, "node should be registered");
   596         add_edge(n_ptn, ptn);
   597       }
   598       break;
   599     }
   600     case Op_LoadP:
   601     case Op_LoadN:
   602     case Op_LoadPLocked: {
   603       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   604       // ThreadLocal has RawPtr type.
   605       const Type* t = _igvn->type(n);
   606       if (t->make_ptr() != NULL) {
   607         Node* adr = n->in(MemNode::Address);
   608         add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
   609         break;
   610       }
   611       ELSE_FAIL("Op_LoadP");
   612     }
   613     case Op_Phi: {
   614       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   615       // ThreadLocal has RawPtr type.
   616       const Type* t = n->as_Phi()->type();
   617       if (t->make_ptr() != NULL) {
   618         for (uint i = 1; i < n->req(); i++) {
   619           Node* in = n->in(i);
   620           if (in == NULL)
   621             continue;  // ignore NULL
   622           Node* uncast_in = in->uncast();
   623           if (uncast_in->is_top() || uncast_in == n)
   624             continue;  // ignore top or inputs which go back this node
   625           PointsToNode* ptn = ptnode_adr(in->_idx);
   626           assert(ptn != NULL, "node should be registered");
   627           add_edge(n_ptn, ptn);
   628         }
   629         break;
   630       }
   631       ELSE_FAIL("Op_Phi");
   632     }
   633     case Op_Proj: {
   634       // we are only interested in the oop result projection from a call
   635       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
   636           n->in(0)->as_Call()->returns_pointer()) {
   637         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), NULL);
   638         break;
   639       }
   640       ELSE_FAIL("Op_Proj");
   641     }
   642     case Op_Rethrow: // Exception object escapes
   643     case Op_Return: {
   644       if (n->req() > TypeFunc::Parms &&
   645           _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
   646         // Treat Return value as LocalVar with GlobalEscape escape state.
   647         add_local_var_and_edge(n, PointsToNode::GlobalEscape,
   648                                n->in(TypeFunc::Parms), NULL);
   649         break;
   650       }
   651       ELSE_FAIL("Op_Return");
   652     }
   653     case Op_StoreP:
   654     case Op_StoreN:
   655     case Op_StoreNKlass:
   656     case Op_StorePConditional:
   657     case Op_CompareAndSwapP:
   658     case Op_CompareAndSwapN:
   659     case Op_GetAndSetP:
   660     case Op_GetAndSetN: {
   661       Node* adr = n->in(MemNode::Address);
   662       if (opcode == Op_GetAndSetP || opcode == Op_GetAndSetN) {
   663         const Type* t = _igvn->type(n);
   664         if (t->make_ptr() != NULL) {
   665           add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
   666         }
   667       }
   668       const Type *adr_type = _igvn->type(adr);
   669       adr_type = adr_type->make_ptr();
   670       if (adr_type->isa_oopptr() ||
   671           (opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) &&
   672                         (adr_type == TypeRawPtr::NOTNULL &&
   673                          adr->in(AddPNode::Address)->is_Proj() &&
   674                          adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
   675         // Point Address to Value
   676         PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
   677         assert(adr_ptn != NULL &&
   678                adr_ptn->as_Field()->is_oop(), "node should be registered");
   679         Node *val = n->in(MemNode::ValueIn);
   680         PointsToNode* ptn = ptnode_adr(val->_idx);
   681         assert(ptn != NULL, "node should be registered");
   682         add_edge(adr_ptn, ptn);
   683         break;
   684       } else if ((opcode == Op_StoreP) && (adr_type == TypeRawPtr::BOTTOM)) {
   685         // Stored value escapes in unsafe access.
   686         Node *val = n->in(MemNode::ValueIn);
   687         PointsToNode* ptn = ptnode_adr(val->_idx);
   688         assert(ptn != NULL, "node should be registered");
   689         ptn->set_escape_state(PointsToNode::GlobalEscape);
   690         // Add edge to object for unsafe access with offset.
   691         PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
   692         assert(adr_ptn != NULL, "node should be registered");
   693         if (adr_ptn->is_Field()) {
   694           assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
   695           add_edge(adr_ptn, ptn);
   696         }
   697         break;
   698       }
   699       ELSE_FAIL("Op_StoreP");
   700     }
   701     case Op_AryEq:
   702     case Op_StrComp:
   703     case Op_StrEquals:
   704     case Op_StrIndexOf: {
   705       // char[] arrays passed to string intrinsic do not escape but
   706       // they are not scalar replaceable. Adjust escape state for them.
   707       // Start from in(2) edge since in(1) is memory edge.
   708       for (uint i = 2; i < n->req(); i++) {
   709         Node* adr = n->in(i);
   710         const Type* at = _igvn->type(adr);
   711         if (!adr->is_top() && at->isa_ptr()) {
   712           assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
   713                  at->isa_ptr() != NULL, "expecting a pointer");
   714           if (adr->is_AddP()) {
   715             adr = get_addp_base(adr);
   716           }
   717           PointsToNode* ptn = ptnode_adr(adr->_idx);
   718           assert(ptn != NULL, "node should be registered");
   719           add_edge(n_ptn, ptn);
   720         }
   721       }
   722       break;
   723     }
   724     default: {
   725       // This method should be called only for EA specific nodes which may
   726       // miss some edges when they were created.
   727 #ifdef ASSERT
   728       n->dump(1);
   729 #endif
   730       guarantee(false, "unknown node");
   731     }
   732   }
   733   return;
   734 }
   736 void ConnectionGraph::add_call_node(CallNode* call) {
   737   assert(call->returns_pointer(), "only for call which returns pointer");
   738   uint call_idx = call->_idx;
   739   if (call->is_Allocate()) {
   740     Node* k = call->in(AllocateNode::KlassNode);
   741     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
   742     assert(kt != NULL, "TypeKlassPtr  required.");
   743     ciKlass* cik = kt->klass();
   744     PointsToNode::EscapeState es = PointsToNode::NoEscape;
   745     bool scalar_replaceable = true;
   746     if (call->is_AllocateArray()) {
   747       if (!cik->is_array_klass()) { // StressReflectiveCode
   748         es = PointsToNode::GlobalEscape;
   749       } else {
   750         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
   751         if (length < 0 || length > EliminateAllocationArraySizeLimit) {
   752           // Not scalar replaceable if the length is not constant or too big.
   753           scalar_replaceable = false;
   754         }
   755       }
   756     } else {  // Allocate instance
   757       if (cik->is_subclass_of(_compile->env()->Thread_klass()) ||
   758          !cik->is_instance_klass() || // StressReflectiveCode
   759           cik->as_instance_klass()->has_finalizer()) {
   760         es = PointsToNode::GlobalEscape;
   761       }
   762     }
   763     add_java_object(call, es);
   764     PointsToNode* ptn = ptnode_adr(call_idx);
   765     if (!scalar_replaceable && ptn->scalar_replaceable()) {
   766       ptn->set_scalar_replaceable(false);
   767     }
   768   } else if (call->is_CallStaticJava()) {
   769     // Call nodes could be different types:
   770     //
   771     // 1. CallDynamicJavaNode (what happened during call is unknown):
   772     //
   773     //    - mapped to GlobalEscape JavaObject node if oop is returned;
   774     //
   775     //    - all oop arguments are escaping globally;
   776     //
   777     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
   778     //
   779     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
   780     //
   781     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
   782     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
   783     //      during call is returned;
   784     //    - mapped to ArgEscape LocalVar node pointed to object arguments
   785     //      which are returned and does not escape during call;
   786     //
   787     //    - oop arguments escaping status is defined by bytecode analysis;
   788     //
   789     // For a static call, we know exactly what method is being called.
   790     // Use bytecode estimator to record whether the call's return value escapes.
   791     ciMethod* meth = call->as_CallJava()->method();
   792     if (meth == NULL) {
   793       const char* name = call->as_CallStaticJava()->_name;
   794       assert(strncmp(name, "_multianewarray", 15) == 0, "TODO: add failed case check");
   795       // Returns a newly allocated unescaped object.
   796       add_java_object(call, PointsToNode::NoEscape);
   797       ptnode_adr(call_idx)->set_scalar_replaceable(false);
   798     } else {
   799       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
   800       call_analyzer->copy_dependencies(_compile->dependencies());
   801       if (call_analyzer->is_return_allocated()) {
   802         // Returns a newly allocated unescaped object, simply
   803         // update dependency information.
   804         // Mark it as NoEscape so that objects referenced by
   805         // it's fields will be marked as NoEscape at least.
   806         add_java_object(call, PointsToNode::NoEscape);
   807         ptnode_adr(call_idx)->set_scalar_replaceable(false);
   808       } else {
   809         // Determine whether any arguments are returned.
   810         const TypeTuple* d = call->tf()->domain();
   811         bool ret_arg = false;
   812         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   813           if (d->field_at(i)->isa_ptr() != NULL &&
   814               call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
   815             ret_arg = true;
   816             break;
   817           }
   818         }
   819         if (ret_arg) {
   820           add_local_var(call, PointsToNode::ArgEscape);
   821         } else {
   822           // Returns unknown object.
   823           map_ideal_node(call, phantom_obj);
   824         }
   825       }
   826     }
   827   } else {
   828     // An other type of call, assume the worst case:
   829     // returned value is unknown and globally escapes.
   830     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
   831     map_ideal_node(call, phantom_obj);
   832   }
   833 }
   835 void ConnectionGraph::process_call_arguments(CallNode *call) {
   836     bool is_arraycopy = false;
   837     switch (call->Opcode()) {
   838 #ifdef ASSERT
   839     case Op_Allocate:
   840     case Op_AllocateArray:
   841     case Op_Lock:
   842     case Op_Unlock:
   843       assert(false, "should be done already");
   844       break;
   845 #endif
   846     case Op_CallLeafNoFP:
   847       is_arraycopy = (call->as_CallLeaf()->_name != NULL &&
   848                       strstr(call->as_CallLeaf()->_name, "arraycopy") != 0);
   849       // fall through
   850     case Op_CallLeaf: {
   851       // Stub calls, objects do not escape but they are not scale replaceable.
   852       // Adjust escape state for outgoing arguments.
   853       const TypeTuple * d = call->tf()->domain();
   854       bool src_has_oops = false;
   855       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   856         const Type* at = d->field_at(i);
   857         Node *arg = call->in(i);
   858         const Type *aat = _igvn->type(arg);
   859         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr())
   860           continue;
   861         if (arg->is_AddP()) {
   862           //
   863           // The inline_native_clone() case when the arraycopy stub is called
   864           // after the allocation before Initialize and CheckCastPP nodes.
   865           // Or normal arraycopy for object arrays case.
   866           //
   867           // Set AddP's base (Allocate) as not scalar replaceable since
   868           // pointer to the base (with offset) is passed as argument.
   869           //
   870           arg = get_addp_base(arg);
   871         }
   872         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
   873         assert(arg_ptn != NULL, "should be registered");
   874         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
   875         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
   876           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
   877                  aat->isa_ptr() != NULL, "expecting an Ptr");
   878           bool arg_has_oops = aat->isa_oopptr() &&
   879                               (aat->isa_oopptr()->klass() == NULL || aat->isa_instptr() ||
   880                                (aat->isa_aryptr() && aat->isa_aryptr()->klass()->is_obj_array_klass()));
   881           if (i == TypeFunc::Parms) {
   882             src_has_oops = arg_has_oops;
   883           }
   884           //
   885           // src or dst could be j.l.Object when other is basic type array:
   886           //
   887           //   arraycopy(char[],0,Object*,0,size);
   888           //   arraycopy(Object*,0,char[],0,size);
   889           //
   890           // Don't add edges in such cases.
   891           //
   892           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
   893                                        arg_has_oops && (i > TypeFunc::Parms);
   894 #ifdef ASSERT
   895           if (!(is_arraycopy ||
   896                 call->as_CallLeaf()->_name != NULL &&
   897                 (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre")  == 0 ||
   898                  strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 ))
   899           ) {
   900             call->dump();
   901             assert(false, "EA: unexpected CallLeaf");
   902           }
   903 #endif
   904           // Always process arraycopy's destination object since
   905           // we need to add all possible edges to references in
   906           // source object.
   907           if (arg_esc >= PointsToNode::ArgEscape &&
   908               !arg_is_arraycopy_dest) {
   909             continue;
   910           }
   911           set_escape_state(arg_ptn, PointsToNode::ArgEscape);
   912           if (arg_is_arraycopy_dest) {
   913             Node* src = call->in(TypeFunc::Parms);
   914             if (src->is_AddP()) {
   915               src = get_addp_base(src);
   916             }
   917             PointsToNode* src_ptn = ptnode_adr(src->_idx);
   918             assert(src_ptn != NULL, "should be registered");
   919             if (arg_ptn != src_ptn) {
   920               // Special arraycopy edge:
   921               // A destination object's field can't have the source object
   922               // as base since objects escape states are not related.
   923               // Only escape state of destination object's fields affects
   924               // escape state of fields in source object.
   925               add_arraycopy(call, PointsToNode::ArgEscape, src_ptn, arg_ptn);
   926             }
   927           }
   928         }
   929       }
   930       break;
   931     }
   932     case Op_CallStaticJava: {
   933       // For a static call, we know exactly what method is being called.
   934       // Use bytecode estimator to record the call's escape affects
   935 #ifdef ASSERT
   936       const char* name = call->as_CallStaticJava()->_name;
   937       assert((name == NULL || strcmp(name, "uncommon_trap") != 0), "normal calls only");
   938 #endif
   939       ciMethod* meth = call->as_CallJava()->method();
   940       BCEscapeAnalyzer* call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
   941       // fall-through if not a Java method or no analyzer information
   942       if (call_analyzer != NULL) {
   943         PointsToNode* call_ptn = ptnode_adr(call->_idx);
   944         const TypeTuple* d = call->tf()->domain();
   945         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   946           const Type* at = d->field_at(i);
   947           int k = i - TypeFunc::Parms;
   948           Node* arg = call->in(i);
   949           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
   950           if (at->isa_ptr() != NULL &&
   951               call_analyzer->is_arg_returned(k)) {
   952             // The call returns arguments.
   953             if (call_ptn != NULL) { // Is call's result used?
   954               assert(call_ptn->is_LocalVar(), "node should be registered");
   955               assert(arg_ptn != NULL, "node should be registered");
   956               add_edge(call_ptn, arg_ptn);
   957             }
   958           }
   959           if (at->isa_oopptr() != NULL &&
   960               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
   961             if (!call_analyzer->is_arg_stack(k)) {
   962               // The argument global escapes
   963               set_escape_state(arg_ptn, PointsToNode::GlobalEscape);
   964             } else {
   965               set_escape_state(arg_ptn, PointsToNode::ArgEscape);
   966               if (!call_analyzer->is_arg_local(k)) {
   967                 // The argument itself doesn't escape, but any fields might
   968                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape);
   969               }
   970             }
   971           }
   972         }
   973         if (call_ptn != NULL && call_ptn->is_LocalVar()) {
   974           // The call returns arguments.
   975           assert(call_ptn->edge_count() > 0, "sanity");
   976           if (!call_analyzer->is_return_local()) {
   977             // Returns also unknown object.
   978             add_edge(call_ptn, phantom_obj);
   979           }
   980         }
   981         break;
   982       }
   983     }
   984     default: {
   985       // Fall-through here if not a Java method or no analyzer information
   986       // or some other type of call, assume the worst case: all arguments
   987       // globally escape.
   988       const TypeTuple* d = call->tf()->domain();
   989       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   990         const Type* at = d->field_at(i);
   991         if (at->isa_oopptr() != NULL) {
   992           Node* arg = call->in(i);
   993           if (arg->is_AddP()) {
   994             arg = get_addp_base(arg);
   995           }
   996           assert(ptnode_adr(arg->_idx) != NULL, "should be defined already");
   997           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape);
   998         }
   999       }
  1005 // Finish Graph construction.
  1006 bool ConnectionGraph::complete_connection_graph(
  1007                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
  1008                          GrowableArray<JavaObjectNode*>& non_escaped_worklist,
  1009                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
  1010                          GrowableArray<FieldNode*>&      oop_fields_worklist) {
  1011   // Normally only 1-3 passes needed to build Connection Graph depending
  1012   // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
  1013   // Set limit to 20 to catch situation when something did go wrong and
  1014   // bailout Escape Analysis.
  1015   // Also limit build time to 30 sec (60 in debug VM).
  1016 #define CG_BUILD_ITER_LIMIT 20
  1017 #ifdef ASSERT
  1018 #define CG_BUILD_TIME_LIMIT 60.0
  1019 #else
  1020 #define CG_BUILD_TIME_LIMIT 30.0
  1021 #endif
  1023   // Propagate GlobalEscape and ArgEscape escape states and check that
  1024   // we still have non-escaping objects. The method pushs on _worklist
  1025   // Field nodes which reference phantom_object.
  1026   if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
  1027     return false; // Nothing to do.
  1029   // Now propagate references to all JavaObject nodes.
  1030   int java_objects_length = java_objects_worklist.length();
  1031   elapsedTimer time;
  1032   int new_edges = 1;
  1033   int iterations = 0;
  1034   do {
  1035     while ((new_edges > 0) &&
  1036           (iterations++   < CG_BUILD_ITER_LIMIT) &&
  1037           (time.seconds() < CG_BUILD_TIME_LIMIT)) {
  1038       time.start();
  1039       new_edges = 0;
  1040       // Propagate references to phantom_object for nodes pushed on _worklist
  1041       // by find_non_escaped_objects() and find_field_value().
  1042       new_edges += add_java_object_edges(phantom_obj, false);
  1043       for (int next = 0; next < java_objects_length; ++next) {
  1044         JavaObjectNode* ptn = java_objects_worklist.at(next);
  1045         new_edges += add_java_object_edges(ptn, true);
  1047       if (new_edges > 0) {
  1048         // Update escape states on each iteration if graph was updated.
  1049         if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
  1050           return false; // Nothing to do.
  1053       time.stop();
  1055     if ((iterations     < CG_BUILD_ITER_LIMIT) &&
  1056         (time.seconds() < CG_BUILD_TIME_LIMIT)) {
  1057       time.start();
  1058       // Find fields which have unknown value.
  1059       int fields_length = oop_fields_worklist.length();
  1060       for (int next = 0; next < fields_length; next++) {
  1061         FieldNode* field = oop_fields_worklist.at(next);
  1062         if (field->edge_count() == 0) {
  1063           new_edges += find_field_value(field);
  1064           // This code may added new edges to phantom_object.
  1065           // Need an other cycle to propagate references to phantom_object.
  1068       time.stop();
  1069     } else {
  1070       new_edges = 0; // Bailout
  1072   } while (new_edges > 0);
  1074   // Bailout if passed limits.
  1075   if ((iterations     >= CG_BUILD_ITER_LIMIT) ||
  1076       (time.seconds() >= CG_BUILD_TIME_LIMIT)) {
  1077     Compile* C = _compile;
  1078     if (C->log() != NULL) {
  1079       C->log()->begin_elem("connectionGraph_bailout reason='reached ");
  1080       C->log()->text("%s", (iterations >= CG_BUILD_ITER_LIMIT) ? "iterations" : "time");
  1081       C->log()->end_elem(" limit'");
  1083     assert(false, err_msg_res("infinite EA connection graph build (%f sec, %d iterations) with %d nodes and worklist size %d",
  1084            time.seconds(), iterations, nodes_size(), ptnodes_worklist.length()));
  1085     // Possible infinite build_connection_graph loop,
  1086     // bailout (no changes to ideal graph were made).
  1087     return false;
  1089 #ifdef ASSERT
  1090   if (Verbose && PrintEscapeAnalysis) {
  1091     tty->print_cr("EA: %d iterations to build connection graph with %d nodes and worklist size %d",
  1092                   iterations, nodes_size(), ptnodes_worklist.length());
  1094 #endif
  1096 #undef CG_BUILD_ITER_LIMIT
  1097 #undef CG_BUILD_TIME_LIMIT
  1099   // Find fields initialized by NULL for non-escaping Allocations.
  1100   int non_escaped_length = non_escaped_worklist.length();
  1101   for (int next = 0; next < non_escaped_length; next++) {
  1102     JavaObjectNode* ptn = non_escaped_worklist.at(next);
  1103     PointsToNode::EscapeState es = ptn->escape_state();
  1104     assert(es <= PointsToNode::ArgEscape, "sanity");
  1105     if (es == PointsToNode::NoEscape) {
  1106       if (find_init_values(ptn, null_obj, _igvn) > 0) {
  1107         // Adding references to NULL object does not change escape states
  1108         // since it does not escape. Also no fields are added to NULL object.
  1109         add_java_object_edges(null_obj, false);
  1112     Node* n = ptn->ideal_node();
  1113     if (n->is_Allocate()) {
  1114       // The object allocated by this Allocate node will never be
  1115       // seen by an other thread. Mark it so that when it is
  1116       // expanded no MemBarStoreStore is added.
  1117       InitializeNode* ini = n->as_Allocate()->initialization();
  1118       if (ini != NULL)
  1119         ini->set_does_not_escape();
  1122   return true; // Finished graph construction.
  1125 // Propagate GlobalEscape and ArgEscape escape states to all nodes
  1126 // and check that we still have non-escaping java objects.
  1127 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
  1128                                                GrowableArray<JavaObjectNode*>& non_escaped_worklist) {
  1129   GrowableArray<PointsToNode*> escape_worklist;
  1130   // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
  1131   int ptnodes_length = ptnodes_worklist.length();
  1132   for (int next = 0; next < ptnodes_length; ++next) {
  1133     PointsToNode* ptn = ptnodes_worklist.at(next);
  1134     if (ptn->escape_state() >= PointsToNode::ArgEscape ||
  1135         ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
  1136       escape_worklist.push(ptn);
  1139   // Set escape states to referenced nodes (edges list).
  1140   while (escape_worklist.length() > 0) {
  1141     PointsToNode* ptn = escape_worklist.pop();
  1142     PointsToNode::EscapeState es  = ptn->escape_state();
  1143     PointsToNode::EscapeState field_es = ptn->fields_escape_state();
  1144     if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
  1145         es >= PointsToNode::ArgEscape) {
  1146       // GlobalEscape or ArgEscape state of field means it has unknown value.
  1147       if (add_edge(ptn, phantom_obj)) {
  1148         // New edge was added
  1149         add_field_uses_to_worklist(ptn->as_Field());
  1152     for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1153       PointsToNode* e = i.get();
  1154       if (e->is_Arraycopy()) {
  1155         assert(ptn->arraycopy_dst(), "sanity");
  1156         // Propagate only fields escape state through arraycopy edge.
  1157         if (e->fields_escape_state() < field_es) {
  1158           set_fields_escape_state(e, field_es);
  1159           escape_worklist.push(e);
  1161       } else if (es >= field_es) {
  1162         // fields_escape_state is also set to 'es' if it is less than 'es'.
  1163         if (e->escape_state() < es) {
  1164           set_escape_state(e, es);
  1165           escape_worklist.push(e);
  1167       } else {
  1168         // Propagate field escape state.
  1169         bool es_changed = false;
  1170         if (e->fields_escape_state() < field_es) {
  1171           set_fields_escape_state(e, field_es);
  1172           es_changed = true;
  1174         if ((e->escape_state() < field_es) &&
  1175             e->is_Field() && ptn->is_JavaObject() &&
  1176             e->as_Field()->is_oop()) {
  1177           // Change escape state of referenced fileds.
  1178           set_escape_state(e, field_es);
  1179           es_changed = true;;
  1180         } else if (e->escape_state() < es) {
  1181           set_escape_state(e, es);
  1182           es_changed = true;;
  1184         if (es_changed) {
  1185           escape_worklist.push(e);
  1190   // Remove escaped objects from non_escaped list.
  1191   for (int next = non_escaped_worklist.length()-1; next >= 0 ; --next) {
  1192     JavaObjectNode* ptn = non_escaped_worklist.at(next);
  1193     if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
  1194       non_escaped_worklist.delete_at(next);
  1196     if (ptn->escape_state() == PointsToNode::NoEscape) {
  1197       // Find fields in non-escaped allocations which have unknown value.
  1198       find_init_values(ptn, phantom_obj, NULL);
  1201   return (non_escaped_worklist.length() > 0);
  1204 // Add all references to JavaObject node by walking over all uses.
  1205 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
  1206   int new_edges = 0;
  1207   if (populate_worklist) {
  1208     // Populate _worklist by uses of jobj's uses.
  1209     for (UseIterator i(jobj); i.has_next(); i.next()) {
  1210       PointsToNode* use = i.get();
  1211       if (use->is_Arraycopy())
  1212         continue;
  1213       add_uses_to_worklist(use);
  1214       if (use->is_Field() && use->as_Field()->is_oop()) {
  1215         // Put on worklist all field's uses (loads) and
  1216         // related field nodes (same base and offset).
  1217         add_field_uses_to_worklist(use->as_Field());
  1221   while(_worklist.length() > 0) {
  1222     PointsToNode* use = _worklist.pop();
  1223     if (PointsToNode::is_base_use(use)) {
  1224       // Add reference from jobj to field and from field to jobj (field's base).
  1225       use = PointsToNode::get_use_node(use)->as_Field();
  1226       if (add_base(use->as_Field(), jobj)) {
  1227         new_edges++;
  1229       continue;
  1231     assert(!use->is_JavaObject(), "sanity");
  1232     if (use->is_Arraycopy()) {
  1233       if (jobj == null_obj) // NULL object does not have field edges
  1234         continue;
  1235       // Added edge from Arraycopy node to arraycopy's source java object
  1236       if (add_edge(use, jobj)) {
  1237         jobj->set_arraycopy_src();
  1238         new_edges++;
  1240       // and stop here.
  1241       continue;
  1243     if (!add_edge(use, jobj))
  1244       continue; // No new edge added, there was such edge already.
  1245     new_edges++;
  1246     if (use->is_LocalVar()) {
  1247       add_uses_to_worklist(use);
  1248       if (use->arraycopy_dst()) {
  1249         for (EdgeIterator i(use); i.has_next(); i.next()) {
  1250           PointsToNode* e = i.get();
  1251           if (e->is_Arraycopy()) {
  1252             if (jobj == null_obj) // NULL object does not have field edges
  1253               continue;
  1254             // Add edge from arraycopy's destination java object to Arraycopy node.
  1255             if (add_edge(jobj, e)) {
  1256               new_edges++;
  1257               jobj->set_arraycopy_dst();
  1262     } else {
  1263       // Added new edge to stored in field values.
  1264       // Put on worklist all field's uses (loads) and
  1265       // related field nodes (same base and offset).
  1266       add_field_uses_to_worklist(use->as_Field());
  1269   return new_edges;
  1272 // Put on worklist all related field nodes.
  1273 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
  1274   assert(field->is_oop(), "sanity");
  1275   int offset = field->offset();
  1276   add_uses_to_worklist(field);
  1277   // Loop over all bases of this field and push on worklist Field nodes
  1278   // with the same offset and base (since they may reference the same field).
  1279   for (BaseIterator i(field); i.has_next(); i.next()) {
  1280     PointsToNode* base = i.get();
  1281     add_fields_to_worklist(field, base);
  1282     // Check if the base was source object of arraycopy and go over arraycopy's
  1283     // destination objects since values stored to a field of source object are
  1284     // accessable by uses (loads) of fields of destination objects.
  1285     if (base->arraycopy_src()) {
  1286       for (UseIterator j(base); j.has_next(); j.next()) {
  1287         PointsToNode* arycp = j.get();
  1288         if (arycp->is_Arraycopy()) {
  1289           for (UseIterator k(arycp); k.has_next(); k.next()) {
  1290             PointsToNode* abase = k.get();
  1291             if (abase->arraycopy_dst() && abase != base) {
  1292               // Look for the same arracopy reference.
  1293               add_fields_to_worklist(field, abase);
  1302 // Put on worklist all related field nodes.
  1303 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
  1304   int offset = field->offset();
  1305   if (base->is_LocalVar()) {
  1306     for (UseIterator j(base); j.has_next(); j.next()) {
  1307       PointsToNode* f = j.get();
  1308       if (PointsToNode::is_base_use(f)) { // Field
  1309         f = PointsToNode::get_use_node(f);
  1310         if (f == field || !f->as_Field()->is_oop())
  1311           continue;
  1312         int offs = f->as_Field()->offset();
  1313         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
  1314           add_to_worklist(f);
  1318   } else {
  1319     assert(base->is_JavaObject(), "sanity");
  1320     if (// Skip phantom_object since it is only used to indicate that
  1321         // this field's content globally escapes.
  1322         (base != phantom_obj) &&
  1323         // NULL object node does not have fields.
  1324         (base != null_obj)) {
  1325       for (EdgeIterator i(base); i.has_next(); i.next()) {
  1326         PointsToNode* f = i.get();
  1327         // Skip arraycopy edge since store to destination object field
  1328         // does not update value in source object field.
  1329         if (f->is_Arraycopy()) {
  1330           assert(base->arraycopy_dst(), "sanity");
  1331           continue;
  1333         if (f == field || !f->as_Field()->is_oop())
  1334           continue;
  1335         int offs = f->as_Field()->offset();
  1336         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
  1337           add_to_worklist(f);
  1344 // Find fields which have unknown value.
  1345 int ConnectionGraph::find_field_value(FieldNode* field) {
  1346   // Escaped fields should have init value already.
  1347   assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
  1348   int new_edges = 0;
  1349   for (BaseIterator i(field); i.has_next(); i.next()) {
  1350     PointsToNode* base = i.get();
  1351     if (base->is_JavaObject()) {
  1352       // Skip Allocate's fields which will be processed later.
  1353       if (base->ideal_node()->is_Allocate())
  1354         return 0;
  1355       assert(base == null_obj, "only NULL ptr base expected here");
  1358   if (add_edge(field, phantom_obj)) {
  1359     // New edge was added
  1360     new_edges++;
  1361     add_field_uses_to_worklist(field);
  1363   return new_edges;
  1366 // Find fields initializing values for allocations.
  1367 int ConnectionGraph::find_init_values(JavaObjectNode* pta, PointsToNode* init_val, PhaseTransform* phase) {
  1368   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
  1369   int new_edges = 0;
  1370   Node* alloc = pta->ideal_node();
  1371   if (init_val == phantom_obj) {
  1372     // Do nothing for Allocate nodes since its fields values are "known".
  1373     if (alloc->is_Allocate())
  1374       return 0;
  1375     assert(alloc->as_CallStaticJava(), "sanity");
  1376 #ifdef ASSERT
  1377     if (alloc->as_CallStaticJava()->method() == NULL) {
  1378       const char* name = alloc->as_CallStaticJava()->_name;
  1379       assert(strncmp(name, "_multianewarray", 15) == 0, "sanity");
  1381 #endif
  1382     // Non-escaped allocation returned from Java or runtime call have
  1383     // unknown values in fields.
  1384     for (EdgeIterator i(pta); i.has_next(); i.next()) {
  1385       PointsToNode* ptn = i.get();
  1386       if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
  1387         if (add_edge(ptn, phantom_obj)) {
  1388           // New edge was added
  1389           new_edges++;
  1390           add_field_uses_to_worklist(ptn->as_Field());
  1394     return new_edges;
  1396   assert(init_val == null_obj, "sanity");
  1397   // Do nothing for Call nodes since its fields values are unknown.
  1398   if (!alloc->is_Allocate())
  1399     return 0;
  1401   InitializeNode* ini = alloc->as_Allocate()->initialization();
  1402   Compile* C = _compile;
  1403   bool visited_bottom_offset = false;
  1404   GrowableArray<int> offsets_worklist;
  1406   // Check if an oop field's initializing value is recorded and add
  1407   // a corresponding NULL if field's value if it is not recorded.
  1408   // Connection Graph does not record a default initialization by NULL
  1409   // captured by Initialize node.
  1410   //
  1411   for (EdgeIterator i(pta); i.has_next(); i.next()) {
  1412     PointsToNode* ptn = i.get(); // Field (AddP)
  1413     if (!ptn->is_Field() || !ptn->as_Field()->is_oop())
  1414       continue; // Not oop field
  1415     int offset = ptn->as_Field()->offset();
  1416     if (offset == Type::OffsetBot) {
  1417       if (!visited_bottom_offset) {
  1418         // OffsetBot is used to reference array's element,
  1419         // always add reference to NULL to all Field nodes since we don't
  1420         // known which element is referenced.
  1421         if (add_edge(ptn, null_obj)) {
  1422           // New edge was added
  1423           new_edges++;
  1424           add_field_uses_to_worklist(ptn->as_Field());
  1425           visited_bottom_offset = true;
  1428     } else {
  1429       // Check only oop fields.
  1430       const Type* adr_type = ptn->ideal_node()->as_AddP()->bottom_type();
  1431       if (adr_type->isa_rawptr()) {
  1432 #ifdef ASSERT
  1433         // Raw pointers are used for initializing stores so skip it
  1434         // since it should be recorded already
  1435         Node* base = get_addp_base(ptn->ideal_node());
  1436         assert(adr_type->isa_rawptr() && base->is_Proj() &&
  1437                (base->in(0) == alloc),"unexpected pointer type");
  1438 #endif
  1439         continue;
  1441       if (!offsets_worklist.contains(offset)) {
  1442         offsets_worklist.append(offset);
  1443         Node* value = NULL;
  1444         if (ini != NULL) {
  1445           BasicType ft = UseCompressedOops ? T_NARROWOOP : T_OBJECT;
  1446           Node* store = ini->find_captured_store(offset, type2aelembytes(ft), phase);
  1447           if (store != NULL && store->is_Store()) {
  1448             value = store->in(MemNode::ValueIn);
  1449           } else {
  1450             // There could be initializing stores which follow allocation.
  1451             // For example, a volatile field store is not collected
  1452             // by Initialize node.
  1453             //
  1454             // Need to check for dependent loads to separate such stores from
  1455             // stores which follow loads. For now, add initial value NULL so
  1456             // that compare pointers optimization works correctly.
  1459         if (value == NULL) {
  1460           // A field's initializing value was not recorded. Add NULL.
  1461           if (add_edge(ptn, null_obj)) {
  1462             // New edge was added
  1463             new_edges++;
  1464             add_field_uses_to_worklist(ptn->as_Field());
  1470   return new_edges;
  1473 // Adjust scalar_replaceable state after Connection Graph is built.
  1474 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj) {
  1475   // Search for non-escaping objects which are not scalar replaceable
  1476   // and mark them to propagate the state to referenced objects.
  1478   // 1. An object is not scalar replaceable if the field into which it is
  1479   // stored has unknown offset (stored into unknown element of an array).
  1480   //
  1481   for (UseIterator i(jobj); i.has_next(); i.next()) {
  1482     PointsToNode* use = i.get();
  1483     assert(!use->is_Arraycopy(), "sanity");
  1484     if (use->is_Field()) {
  1485       FieldNode* field = use->as_Field();
  1486       assert(field->is_oop() && field->scalar_replaceable() &&
  1487              field->fields_escape_state() == PointsToNode::NoEscape, "sanity");
  1488       if (field->offset() == Type::OffsetBot) {
  1489         jobj->set_scalar_replaceable(false);
  1490         return;
  1493     assert(use->is_Field() || use->is_LocalVar(), "sanity");
  1494     // 2. An object is not scalar replaceable if it is merged with other objects.
  1495     for (EdgeIterator j(use); j.has_next(); j.next()) {
  1496       PointsToNode* ptn = j.get();
  1497       if (ptn->is_JavaObject() && ptn != jobj) {
  1498         // Mark all objects.
  1499         jobj->set_scalar_replaceable(false);
  1500          ptn->set_scalar_replaceable(false);
  1503     if (!jobj->scalar_replaceable()) {
  1504       return;
  1508   for (EdgeIterator j(jobj); j.has_next(); j.next()) {
  1509     // Non-escaping object node should point only to field nodes.
  1510     FieldNode* field = j.get()->as_Field();
  1511     int offset = field->as_Field()->offset();
  1513     // 3. An object is not scalar replaceable if it has a field with unknown
  1514     // offset (array's element is accessed in loop).
  1515     if (offset == Type::OffsetBot) {
  1516       jobj->set_scalar_replaceable(false);
  1517       return;
  1519     // 4. Currently an object is not scalar replaceable if a LoadStore node
  1520     // access its field since the field value is unknown after it.
  1521     //
  1522     Node* n = field->ideal_node();
  1523     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  1524       if (n->fast_out(i)->is_LoadStore()) {
  1525         jobj->set_scalar_replaceable(false);
  1526         return;
  1530     // 5. Or the address may point to more then one object. This may produce
  1531     // the false positive result (set not scalar replaceable)
  1532     // since the flow-insensitive escape analysis can't separate
  1533     // the case when stores overwrite the field's value from the case
  1534     // when stores happened on different control branches.
  1535     //
  1536     // Note: it will disable scalar replacement in some cases:
  1537     //
  1538     //    Point p[] = new Point[1];
  1539     //    p[0] = new Point(); // Will be not scalar replaced
  1540     //
  1541     // but it will save us from incorrect optimizations in next cases:
  1542     //
  1543     //    Point p[] = new Point[1];
  1544     //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
  1545     //
  1546     if (field->base_count() > 1) {
  1547       for (BaseIterator i(field); i.has_next(); i.next()) {
  1548         PointsToNode* base = i.get();
  1549         // Don't take into account LocalVar nodes which
  1550         // may point to only one object which should be also
  1551         // this field's base by now.
  1552         if (base->is_JavaObject() && base != jobj) {
  1553           // Mark all bases.
  1554           jobj->set_scalar_replaceable(false);
  1555           base->set_scalar_replaceable(false);
  1562 #ifdef ASSERT
  1563 void ConnectionGraph::verify_connection_graph(
  1564                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
  1565                          GrowableArray<JavaObjectNode*>& non_escaped_worklist,
  1566                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
  1567                          GrowableArray<Node*>& addp_worklist) {
  1568   // Verify that graph is complete - no new edges could be added.
  1569   int java_objects_length = java_objects_worklist.length();
  1570   int non_escaped_length  = non_escaped_worklist.length();
  1571   int new_edges = 0;
  1572   for (int next = 0; next < java_objects_length; ++next) {
  1573     JavaObjectNode* ptn = java_objects_worklist.at(next);
  1574     new_edges += add_java_object_edges(ptn, true);
  1576   assert(new_edges == 0, "graph was not complete");
  1577   // Verify that escape state is final.
  1578   int length = non_escaped_worklist.length();
  1579   find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist);
  1580   assert((non_escaped_length == non_escaped_worklist.length()) &&
  1581          (non_escaped_length == length) &&
  1582          (_worklist.length() == 0), "escape state was not final");
  1584   // Verify fields information.
  1585   int addp_length = addp_worklist.length();
  1586   for (int next = 0; next < addp_length; ++next ) {
  1587     Node* n = addp_worklist.at(next);
  1588     FieldNode* field = ptnode_adr(n->_idx)->as_Field();
  1589     if (field->is_oop()) {
  1590       // Verify that field has all bases
  1591       Node* base = get_addp_base(n);
  1592       PointsToNode* ptn = ptnode_adr(base->_idx);
  1593       if (ptn->is_JavaObject()) {
  1594         assert(field->has_base(ptn->as_JavaObject()), "sanity");
  1595       } else {
  1596         assert(ptn->is_LocalVar(), "sanity");
  1597         for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1598           PointsToNode* e = i.get();
  1599           if (e->is_JavaObject()) {
  1600             assert(field->has_base(e->as_JavaObject()), "sanity");
  1604       // Verify that all fields have initializing values.
  1605       if (field->edge_count() == 0) {
  1606         field->dump();
  1607         assert(field->edge_count() > 0, "sanity");
  1612 #endif
  1614 // Optimize ideal graph.
  1615 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
  1616                                            GrowableArray<Node*>& storestore_worklist) {
  1617   Compile* C = _compile;
  1618   PhaseIterGVN* igvn = _igvn;
  1619   if (EliminateLocks) {
  1620     // Mark locks before changing ideal graph.
  1621     int cnt = C->macro_count();
  1622     for( int i=0; i < cnt; i++ ) {
  1623       Node *n = C->macro_node(i);
  1624       if (n->is_AbstractLock()) { // Lock and Unlock nodes
  1625         AbstractLockNode* alock = n->as_AbstractLock();
  1626         if (!alock->is_non_esc_obj()) {
  1627           if (not_global_escape(alock->obj_node())) {
  1628             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
  1629             // The lock could be marked eliminated by lock coarsening
  1630             // code during first IGVN before EA. Replace coarsened flag
  1631             // to eliminate all associated locks/unlocks.
  1632             alock->set_non_esc_obj();
  1639   if (OptimizePtrCompare) {
  1640     // Add ConI(#CC_GT) and ConI(#CC_EQ).
  1641     _pcmp_neq = igvn->makecon(TypeInt::CC_GT);
  1642     _pcmp_eq = igvn->makecon(TypeInt::CC_EQ);
  1643     // Optimize objects compare.
  1644     while (ptr_cmp_worklist.length() != 0) {
  1645       Node *n = ptr_cmp_worklist.pop();
  1646       Node *res = optimize_ptr_compare(n);
  1647       if (res != NULL) {
  1648 #ifndef PRODUCT
  1649         if (PrintOptimizePtrCompare) {
  1650           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"));
  1651           if (Verbose) {
  1652             n->dump(1);
  1655 #endif
  1656         igvn->replace_node(n, res);
  1659     // cleanup
  1660     if (_pcmp_neq->outcnt() == 0)
  1661       igvn->hash_delete(_pcmp_neq);
  1662     if (_pcmp_eq->outcnt()  == 0)
  1663       igvn->hash_delete(_pcmp_eq);
  1666   // For MemBarStoreStore nodes added in library_call.cpp, check
  1667   // escape status of associated AllocateNode and optimize out
  1668   // MemBarStoreStore node if the allocated object never escapes.
  1669   while (storestore_worklist.length() != 0) {
  1670     Node *n = storestore_worklist.pop();
  1671     MemBarStoreStoreNode *storestore = n ->as_MemBarStoreStore();
  1672     Node *alloc = storestore->in(MemBarNode::Precedent)->in(0);
  1673     assert (alloc->is_Allocate(), "storestore should point to AllocateNode");
  1674     if (not_global_escape(alloc)) {
  1675       MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
  1676       mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
  1677       mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
  1678       igvn->register_new_node_with_optimizer(mb);
  1679       igvn->replace_node(storestore, mb);
  1684 // Optimize objects compare.
  1685 Node* ConnectionGraph::optimize_ptr_compare(Node* n) {
  1686   assert(OptimizePtrCompare, "sanity");
  1687   PointsToNode* ptn1 = ptnode_adr(n->in(1)->_idx);
  1688   PointsToNode* ptn2 = ptnode_adr(n->in(2)->_idx);
  1689   JavaObjectNode* jobj1 = unique_java_object(n->in(1));
  1690   JavaObjectNode* jobj2 = unique_java_object(n->in(2));
  1691   assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
  1692   assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
  1694   // Check simple cases first.
  1695   if (jobj1 != NULL) {
  1696     if (jobj1->escape_state() == PointsToNode::NoEscape) {
  1697       if (jobj1 == jobj2) {
  1698         // Comparing the same not escaping object.
  1699         return _pcmp_eq;
  1701       Node* obj = jobj1->ideal_node();
  1702       // Comparing not escaping allocation.
  1703       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
  1704           !ptn2->points_to(jobj1)) {
  1705         return _pcmp_neq; // This includes nullness check.
  1709   if (jobj2 != NULL) {
  1710     if (jobj2->escape_state() == PointsToNode::NoEscape) {
  1711       Node* obj = jobj2->ideal_node();
  1712       // Comparing not escaping allocation.
  1713       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
  1714           !ptn1->points_to(jobj2)) {
  1715         return _pcmp_neq; // This includes nullness check.
  1719   if (jobj1 != NULL && jobj1 != phantom_obj &&
  1720       jobj2 != NULL && jobj2 != phantom_obj &&
  1721       jobj1->ideal_node()->is_Con() &&
  1722       jobj2->ideal_node()->is_Con()) {
  1723     // Klass or String constants compare. Need to be careful with
  1724     // compressed pointers - compare types of ConN and ConP instead of nodes.
  1725     const Type* t1 = jobj1->ideal_node()->bottom_type()->make_ptr();
  1726     const Type* t2 = jobj2->ideal_node()->bottom_type()->make_ptr();
  1727     assert(t1 != NULL && t2 != NULL, "sanity");
  1728     if (t1->make_ptr() == t2->make_ptr()) {
  1729       return _pcmp_eq;
  1730     } else {
  1731       return _pcmp_neq;
  1734   if (ptn1->meet(ptn2)) {
  1735     return NULL; // Sets are not disjoint
  1738   // Sets are disjoint.
  1739   bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
  1740   bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
  1741   bool set1_has_null_ptr    = ptn1->points_to(null_obj);
  1742   bool set2_has_null_ptr    = ptn2->points_to(null_obj);
  1743   if (set1_has_unknown_ptr && set2_has_null_ptr ||
  1744       set2_has_unknown_ptr && set1_has_null_ptr) {
  1745     // Check nullness of unknown object.
  1746     return NULL;
  1749   // Disjointness by itself is not sufficient since
  1750   // alias analysis is not complete for escaped objects.
  1751   // Disjoint sets are definitely unrelated only when
  1752   // at least one set has only not escaping allocations.
  1753   if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
  1754     if (ptn1->non_escaping_allocation()) {
  1755       return _pcmp_neq;
  1758   if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
  1759     if (ptn2->non_escaping_allocation()) {
  1760       return _pcmp_neq;
  1763   return NULL;
  1766 // Connection Graph constuction functions.
  1768 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
  1769   PointsToNode* ptadr = _nodes.at(n->_idx);
  1770   if (ptadr != NULL) {
  1771     assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
  1772     return;
  1774   Compile* C = _compile;
  1775   ptadr = new (C->comp_arena()) LocalVarNode(C, n, es);
  1776   _nodes.at_put(n->_idx, ptadr);
  1779 void ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
  1780   PointsToNode* ptadr = _nodes.at(n->_idx);
  1781   if (ptadr != NULL) {
  1782     assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
  1783     return;
  1785   Compile* C = _compile;
  1786   ptadr = new (C->comp_arena()) JavaObjectNode(C, n, es);
  1787   _nodes.at_put(n->_idx, ptadr);
  1790 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
  1791   PointsToNode* ptadr = _nodes.at(n->_idx);
  1792   if (ptadr != NULL) {
  1793     assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
  1794     return;
  1796   bool unsafe = false;
  1797   bool is_oop = is_oop_field(n, offset, &unsafe);
  1798   if (unsafe) {
  1799     es = PointsToNode::GlobalEscape;
  1801   Compile* C = _compile;
  1802   FieldNode* field = new (C->comp_arena()) FieldNode(C, n, es, offset, is_oop);
  1803   _nodes.at_put(n->_idx, field);
  1806 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
  1807                                     PointsToNode* src, PointsToNode* dst) {
  1808   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
  1809   assert((src != null_obj) && (dst != null_obj), "not for ConP NULL");
  1810   PointsToNode* ptadr = _nodes.at(n->_idx);
  1811   if (ptadr != NULL) {
  1812     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
  1813     return;
  1815   Compile* C = _compile;
  1816   ptadr = new (C->comp_arena()) ArraycopyNode(C, n, es);
  1817   _nodes.at_put(n->_idx, ptadr);
  1818   // Add edge from arraycopy node to source object.
  1819   (void)add_edge(ptadr, src);
  1820   src->set_arraycopy_src();
  1821   // Add edge from destination object to arraycopy node.
  1822   (void)add_edge(dst, ptadr);
  1823   dst->set_arraycopy_dst();
  1826 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
  1827   const Type* adr_type = n->as_AddP()->bottom_type();
  1828   BasicType bt = T_INT;
  1829   if (offset == Type::OffsetBot) {
  1830     // Check only oop fields.
  1831     if (!adr_type->isa_aryptr() ||
  1832         (adr_type->isa_aryptr()->klass() == NULL) ||
  1833          adr_type->isa_aryptr()->klass()->is_obj_array_klass()) {
  1834       // OffsetBot is used to reference array's element. Ignore first AddP.
  1835       if (find_second_addp(n, n->in(AddPNode::Base)) == NULL) {
  1836         bt = T_OBJECT;
  1839   } else if (offset != oopDesc::klass_offset_in_bytes()) {
  1840     if (adr_type->isa_instptr()) {
  1841       ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
  1842       if (field != NULL) {
  1843         bt = field->layout_type();
  1844       } else {
  1845         // Check for unsafe oop field access
  1846         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  1847           int opcode = n->fast_out(i)->Opcode();
  1848           if (opcode == Op_StoreP || opcode == Op_LoadP ||
  1849               opcode == Op_StoreN || opcode == Op_LoadN) {
  1850             bt = T_OBJECT;
  1851             (*unsafe) = true;
  1852             break;
  1856     } else if (adr_type->isa_aryptr()) {
  1857       if (offset == arrayOopDesc::length_offset_in_bytes()) {
  1858         // Ignore array length load.
  1859       } else if (find_second_addp(n, n->in(AddPNode::Base)) != NULL) {
  1860         // Ignore first AddP.
  1861       } else {
  1862         const Type* elemtype = adr_type->isa_aryptr()->elem();
  1863         bt = elemtype->array_element_basic_type();
  1865     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
  1866       // Allocation initialization, ThreadLocal field access, unsafe access
  1867       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  1868         int opcode = n->fast_out(i)->Opcode();
  1869         if (opcode == Op_StoreP || opcode == Op_LoadP ||
  1870             opcode == Op_StoreN || opcode == Op_LoadN) {
  1871           bt = T_OBJECT;
  1872           break;
  1877   return (bt == T_OBJECT || bt == T_NARROWOOP || bt == T_ARRAY);
  1880 // Returns unique pointed java object or NULL.
  1881 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) {
  1882   assert(!_collecting, "should not call when contructed graph");
  1883   // If the node was created after the escape computation we can't answer.
  1884   uint idx = n->_idx;
  1885   if (idx >= nodes_size()) {
  1886     return NULL;
  1888   PointsToNode* ptn = ptnode_adr(idx);
  1889   if (ptn->is_JavaObject()) {
  1890     return ptn->as_JavaObject();
  1892   assert(ptn->is_LocalVar(), "sanity");
  1893   // Check all java objects it points to.
  1894   JavaObjectNode* jobj = NULL;
  1895   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1896     PointsToNode* e = i.get();
  1897     if (e->is_JavaObject()) {
  1898       if (jobj == NULL) {
  1899         jobj = e->as_JavaObject();
  1900       } else if (jobj != e) {
  1901         return NULL;
  1905   return jobj;
  1908 // Return true if this node points only to non-escaping allocations.
  1909 bool PointsToNode::non_escaping_allocation() {
  1910   if (is_JavaObject()) {
  1911     Node* n = ideal_node();
  1912     if (n->is_Allocate() || n->is_CallStaticJava()) {
  1913       return (escape_state() == PointsToNode::NoEscape);
  1914     } else {
  1915       return false;
  1918   assert(is_LocalVar(), "sanity");
  1919   // Check all java objects it points to.
  1920   for (EdgeIterator i(this); i.has_next(); i.next()) {
  1921     PointsToNode* e = i.get();
  1922     if (e->is_JavaObject()) {
  1923       Node* n = e->ideal_node();
  1924       if ((e->escape_state() != PointsToNode::NoEscape) ||
  1925           !(n->is_Allocate() || n->is_CallStaticJava())) {
  1926         return false;
  1930   return true;
  1933 // Return true if we know the node does not escape globally.
  1934 bool ConnectionGraph::not_global_escape(Node *n) {
  1935   assert(!_collecting, "should not call during graph construction");
  1936   // If the node was created after the escape computation we can't answer.
  1937   uint idx = n->_idx;
  1938   if (idx >= nodes_size()) {
  1939     return false;
  1941   PointsToNode* ptn = ptnode_adr(idx);
  1942   PointsToNode::EscapeState es = ptn->escape_state();
  1943   // If we have already computed a value, return it.
  1944   if (es >= PointsToNode::GlobalEscape)
  1945     return false;
  1946   if (ptn->is_JavaObject()) {
  1947     return true; // (es < PointsToNode::GlobalEscape);
  1949   assert(ptn->is_LocalVar(), "sanity");
  1950   // Check all java objects it points to.
  1951   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1952     if (i.get()->escape_state() >= PointsToNode::GlobalEscape)
  1953       return false;
  1955   return true;
  1959 // Helper functions
  1961 // Return true if this node points to specified node or nodes it points to.
  1962 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
  1963   if (is_JavaObject()) {
  1964     return (this == ptn);
  1966   assert(is_LocalVar(), "sanity");
  1967   for (EdgeIterator i(this); i.has_next(); i.next()) {
  1968     if (i.get() == ptn)
  1969       return true;
  1971   return false;
  1974 // Return true if one node points to an other.
  1975 bool PointsToNode::meet(PointsToNode* ptn) {
  1976   if (this == ptn) {
  1977     return true;
  1978   } else if (ptn->is_JavaObject()) {
  1979     return this->points_to(ptn->as_JavaObject());
  1980   } else if (this->is_JavaObject()) {
  1981     return ptn->points_to(this->as_JavaObject());
  1983   assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
  1984   int ptn_count =  ptn->edge_count();
  1985   for (EdgeIterator i(this); i.has_next(); i.next()) {
  1986     PointsToNode* this_e = i.get();
  1987     for (int j = 0; j < ptn_count; j++) {
  1988       if (this_e == ptn->edge(j))
  1989         return true;
  1992   return false;
  1995 #ifdef ASSERT
  1996 // Return true if bases point to this java object.
  1997 bool FieldNode::has_base(JavaObjectNode* jobj) const {
  1998   for (BaseIterator i(this); i.has_next(); i.next()) {
  1999     if (i.get() == jobj)
  2000       return true;
  2002   return false;
  2004 #endif
  2006 int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
  2007   const Type *adr_type = phase->type(adr);
  2008   if (adr->is_AddP() && adr_type->isa_oopptr() == NULL &&
  2009       adr->in(AddPNode::Address)->is_Proj() &&
  2010       adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
  2011     // We are computing a raw address for a store captured by an Initialize
  2012     // compute an appropriate address type. AddP cases #3 and #5 (see below).
  2013     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
  2014     assert(offs != Type::OffsetBot ||
  2015            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
  2016            "offset must be a constant or it is initialization of array");
  2017     return offs;
  2019   const TypePtr *t_ptr = adr_type->isa_ptr();
  2020   assert(t_ptr != NULL, "must be a pointer type");
  2021   return t_ptr->offset();
  2024 Node* ConnectionGraph::get_addp_base(Node *addp) {
  2025   assert(addp->is_AddP(), "must be AddP");
  2026   //
  2027   // AddP cases for Base and Address inputs:
  2028   // case #1. Direct object's field reference:
  2029   //     Allocate
  2030   //       |
  2031   //     Proj #5 ( oop result )
  2032   //       |
  2033   //     CheckCastPP (cast to instance type)
  2034   //      | |
  2035   //     AddP  ( base == address )
  2036   //
  2037   // case #2. Indirect object's field reference:
  2038   //      Phi
  2039   //       |
  2040   //     CastPP (cast to instance type)
  2041   //      | |
  2042   //     AddP  ( base == address )
  2043   //
  2044   // case #3. Raw object's field reference for Initialize node:
  2045   //      Allocate
  2046   //        |
  2047   //      Proj #5 ( oop result )
  2048   //  top   |
  2049   //     \  |
  2050   //     AddP  ( base == top )
  2051   //
  2052   // case #4. Array's element reference:
  2053   //   {CheckCastPP | CastPP}
  2054   //     |  | |
  2055   //     |  AddP ( array's element offset )
  2056   //     |  |
  2057   //     AddP ( array's offset )
  2058   //
  2059   // case #5. Raw object's field reference for arraycopy stub call:
  2060   //          The inline_native_clone() case when the arraycopy stub is called
  2061   //          after the allocation before Initialize and CheckCastPP nodes.
  2062   //      Allocate
  2063   //        |
  2064   //      Proj #5 ( oop result )
  2065   //       | |
  2066   //       AddP  ( base == address )
  2067   //
  2068   // case #6. Constant Pool, ThreadLocal, CastX2P or
  2069   //          Raw object's field reference:
  2070   //      {ConP, ThreadLocal, CastX2P, raw Load}
  2071   //  top   |
  2072   //     \  |
  2073   //     AddP  ( base == top )
  2074   //
  2075   // case #7. Klass's field reference.
  2076   //      LoadKlass
  2077   //       | |
  2078   //       AddP  ( base == address )
  2079   //
  2080   // case #8. narrow Klass's field reference.
  2081   //      LoadNKlass
  2082   //       |
  2083   //      DecodeN
  2084   //       | |
  2085   //       AddP  ( base == address )
  2086   //
  2087   Node *base = addp->in(AddPNode::Base);
  2088   if (base->uncast()->is_top()) { // The AddP case #3 and #6.
  2089     base = addp->in(AddPNode::Address);
  2090     while (base->is_AddP()) {
  2091       // Case #6 (unsafe access) may have several chained AddP nodes.
  2092       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
  2093       base = base->in(AddPNode::Address);
  2095     Node* uncast_base = base->uncast();
  2096     int opcode = uncast_base->Opcode();
  2097     assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
  2098            opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
  2099            (uncast_base->is_Mem() && uncast_base->bottom_type() == TypeRawPtr::NOTNULL) ||
  2100            (uncast_base->is_Proj() && uncast_base->in(0)->is_Allocate()), "sanity");
  2102   return base;
  2105 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
  2106   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
  2107   Node* addp2 = addp->raw_out(0);
  2108   if (addp->outcnt() == 1 && addp2->is_AddP() &&
  2109       addp2->in(AddPNode::Base) == n &&
  2110       addp2->in(AddPNode::Address) == addp) {
  2111     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
  2112     //
  2113     // Find array's offset to push it on worklist first and
  2114     // as result process an array's element offset first (pushed second)
  2115     // to avoid CastPP for the array's offset.
  2116     // Otherwise the inserted CastPP (LocalVar) will point to what
  2117     // the AddP (Field) points to. Which would be wrong since
  2118     // the algorithm expects the CastPP has the same point as
  2119     // as AddP's base CheckCastPP (LocalVar).
  2120     //
  2121     //    ArrayAllocation
  2122     //     |
  2123     //    CheckCastPP
  2124     //     |
  2125     //    memProj (from ArrayAllocation CheckCastPP)
  2126     //     |  ||
  2127     //     |  ||   Int (element index)
  2128     //     |  ||    |   ConI (log(element size))
  2129     //     |  ||    |   /
  2130     //     |  ||   LShift
  2131     //     |  ||  /
  2132     //     |  AddP (array's element offset)
  2133     //     |  |
  2134     //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
  2135     //     | / /
  2136     //     AddP (array's offset)
  2137     //      |
  2138     //     Load/Store (memory operation on array's element)
  2139     //
  2140     return addp2;
  2142   return NULL;
  2145 //
  2146 // Adjust the type and inputs of an AddP which computes the
  2147 // address of a field of an instance
  2148 //
  2149 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
  2150   PhaseGVN* igvn = _igvn;
  2151   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
  2152   assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
  2153   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
  2154   if (t == NULL) {
  2155     // We are computing a raw address for a store captured by an Initialize
  2156     // compute an appropriate address type (cases #3 and #5).
  2157     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
  2158     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
  2159     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
  2160     assert(offs != Type::OffsetBot, "offset must be a constant");
  2161     t = base_t->add_offset(offs)->is_oopptr();
  2163   int inst_id =  base_t->instance_id();
  2164   assert(!t->is_known_instance() || t->instance_id() == inst_id,
  2165                              "old type must be non-instance or match new type");
  2167   // The type 't' could be subclass of 'base_t'.
  2168   // As result t->offset() could be large then base_t's size and it will
  2169   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
  2170   // constructor verifies correctness of the offset.
  2171   //
  2172   // It could happened on subclass's branch (from the type profiling
  2173   // inlining) which was not eliminated during parsing since the exactness
  2174   // of the allocation type was not propagated to the subclass type check.
  2175   //
  2176   // Or the type 't' could be not related to 'base_t' at all.
  2177   // It could happened when CHA type is different from MDO type on a dead path
  2178   // (for example, from instanceof check) which is not collapsed during parsing.
  2179   //
  2180   // Do nothing for such AddP node and don't process its users since
  2181   // this code branch will go away.
  2182   //
  2183   if (!t->is_known_instance() &&
  2184       !base_t->klass()->is_subtype_of(t->klass())) {
  2185      return false; // bail out
  2187   const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
  2188   // Do NOT remove the next line: ensure a new alias index is allocated
  2189   // for the instance type. Note: C++ will not remove it since the call
  2190   // has side effect.
  2191   int alias_idx = _compile->get_alias_index(tinst);
  2192   igvn->set_type(addp, tinst);
  2193   // record the allocation in the node map
  2194   set_map(addp, get_map(base->_idx));
  2195   // Set addp's Base and Address to 'base'.
  2196   Node *abase = addp->in(AddPNode::Base);
  2197   Node *adr   = addp->in(AddPNode::Address);
  2198   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
  2199       adr->in(0)->_idx == (uint)inst_id) {
  2200     // Skip AddP cases #3 and #5.
  2201   } else {
  2202     assert(!abase->is_top(), "sanity"); // AddP case #3
  2203     if (abase != base) {
  2204       igvn->hash_delete(addp);
  2205       addp->set_req(AddPNode::Base, base);
  2206       if (abase == adr) {
  2207         addp->set_req(AddPNode::Address, base);
  2208       } else {
  2209         // AddP case #4 (adr is array's element offset AddP node)
  2210 #ifdef ASSERT
  2211         const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
  2212         assert(adr->is_AddP() && atype != NULL &&
  2213                atype->instance_id() == inst_id, "array's element offset should be processed first");
  2214 #endif
  2216       igvn->hash_insert(addp);
  2219   // Put on IGVN worklist since at least addp's type was changed above.
  2220   record_for_optimizer(addp);
  2221   return true;
  2224 //
  2225 // Create a new version of orig_phi if necessary. Returns either the newly
  2226 // created phi or an existing phi.  Sets create_new to indicate whether a new
  2227 // phi was created.  Cache the last newly created phi in the node map.
  2228 //
  2229 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, bool &new_created) {
  2230   Compile *C = _compile;
  2231   PhaseGVN* igvn = _igvn;
  2232   new_created = false;
  2233   int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
  2234   // nothing to do if orig_phi is bottom memory or matches alias_idx
  2235   if (phi_alias_idx == alias_idx) {
  2236     return orig_phi;
  2238   // Have we recently created a Phi for this alias index?
  2239   PhiNode *result = get_map_phi(orig_phi->_idx);
  2240   if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
  2241     return result;
  2243   // Previous check may fail when the same wide memory Phi was split into Phis
  2244   // for different memory slices. Search all Phis for this region.
  2245   if (result != NULL) {
  2246     Node* region = orig_phi->in(0);
  2247     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
  2248       Node* phi = region->fast_out(i);
  2249       if (phi->is_Phi() &&
  2250           C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
  2251         assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
  2252         return phi->as_Phi();
  2256   if ((int)C->unique() + 2*NodeLimitFudgeFactor > MaxNodeLimit) {
  2257     if (C->do_escape_analysis() == true && !C->failing()) {
  2258       // Retry compilation without escape analysis.
  2259       // If this is the first failure, the sentinel string will "stick"
  2260       // to the Compile object, and the C2Compiler will see it and retry.
  2261       C->record_failure(C2Compiler::retry_no_escape_analysis());
  2263     return NULL;
  2265   orig_phi_worklist.append_if_missing(orig_phi);
  2266   const TypePtr *atype = C->get_adr_type(alias_idx);
  2267   result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
  2268   C->copy_node_notes_to(result, orig_phi);
  2269   igvn->set_type(result, result->bottom_type());
  2270   record_for_optimizer(result);
  2271   set_map(orig_phi, result);
  2272   new_created = true;
  2273   return result;
  2276 //
  2277 // Return a new version of Memory Phi "orig_phi" with the inputs having the
  2278 // specified alias index.
  2279 //
  2280 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist) {
  2281   assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
  2282   Compile *C = _compile;
  2283   PhaseGVN* igvn = _igvn;
  2284   bool new_phi_created;
  2285   PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
  2286   if (!new_phi_created) {
  2287     return result;
  2289   GrowableArray<PhiNode *>  phi_list;
  2290   GrowableArray<uint>  cur_input;
  2291   PhiNode *phi = orig_phi;
  2292   uint idx = 1;
  2293   bool finished = false;
  2294   while(!finished) {
  2295     while (idx < phi->req()) {
  2296       Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist);
  2297       if (mem != NULL && mem->is_Phi()) {
  2298         PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
  2299         if (new_phi_created) {
  2300           // found an phi for which we created a new split, push current one on worklist and begin
  2301           // processing new one
  2302           phi_list.push(phi);
  2303           cur_input.push(idx);
  2304           phi = mem->as_Phi();
  2305           result = newphi;
  2306           idx = 1;
  2307           continue;
  2308         } else {
  2309           mem = newphi;
  2312       if (C->failing()) {
  2313         return NULL;
  2315       result->set_req(idx++, mem);
  2317 #ifdef ASSERT
  2318     // verify that the new Phi has an input for each input of the original
  2319     assert( phi->req() == result->req(), "must have same number of inputs.");
  2320     assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
  2321 #endif
  2322     // Check if all new phi's inputs have specified alias index.
  2323     // Otherwise use old phi.
  2324     for (uint i = 1; i < phi->req(); i++) {
  2325       Node* in = result->in(i);
  2326       assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
  2328     // we have finished processing a Phi, see if there are any more to do
  2329     finished = (phi_list.length() == 0 );
  2330     if (!finished) {
  2331       phi = phi_list.pop();
  2332       idx = cur_input.pop();
  2333       PhiNode *prev_result = get_map_phi(phi->_idx);
  2334       prev_result->set_req(idx++, result);
  2335       result = prev_result;
  2338   return result;
  2341 //
  2342 // The next methods are derived from methods in MemNode.
  2343 //
  2344 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
  2345   Node *mem = mmem;
  2346   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
  2347   // means an array I have not precisely typed yet.  Do not do any
  2348   // alias stuff with it any time soon.
  2349   if (toop->base() != Type::AnyPtr &&
  2350       !(toop->klass() != NULL &&
  2351         toop->klass()->is_java_lang_Object() &&
  2352         toop->offset() == Type::OffsetBot)) {
  2353     mem = mmem->memory_at(alias_idx);
  2354     // Update input if it is progress over what we have now
  2356   return mem;
  2359 //
  2360 // Move memory users to their memory slices.
  2361 //
  2362 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis) {
  2363   Compile* C = _compile;
  2364   PhaseGVN* igvn = _igvn;
  2365   const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
  2366   assert(tp != NULL, "ptr type");
  2367   int alias_idx = C->get_alias_index(tp);
  2368   int general_idx = C->get_general_index(alias_idx);
  2370   // Move users first
  2371   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2372     Node* use = n->fast_out(i);
  2373     if (use->is_MergeMem()) {
  2374       MergeMemNode* mmem = use->as_MergeMem();
  2375       assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
  2376       if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
  2377         continue; // Nothing to do
  2379       // Replace previous general reference to mem node.
  2380       uint orig_uniq = C->unique();
  2381       Node* m = find_inst_mem(n, general_idx, orig_phis);
  2382       assert(orig_uniq == C->unique(), "no new nodes");
  2383       mmem->set_memory_at(general_idx, m);
  2384       --imax;
  2385       --i;
  2386     } else if (use->is_MemBar()) {
  2387       assert(!use->is_Initialize(), "initializing stores should not be moved");
  2388       if (use->req() > MemBarNode::Precedent &&
  2389           use->in(MemBarNode::Precedent) == n) {
  2390         // Don't move related membars.
  2391         record_for_optimizer(use);
  2392         continue;
  2394       tp = use->as_MemBar()->adr_type()->isa_ptr();
  2395       if (tp != NULL && C->get_alias_index(tp) == alias_idx ||
  2396           alias_idx == general_idx) {
  2397         continue; // Nothing to do
  2399       // Move to general memory slice.
  2400       uint orig_uniq = C->unique();
  2401       Node* m = find_inst_mem(n, general_idx, orig_phis);
  2402       assert(orig_uniq == C->unique(), "no new nodes");
  2403       igvn->hash_delete(use);
  2404       imax -= use->replace_edge(n, m);
  2405       igvn->hash_insert(use);
  2406       record_for_optimizer(use);
  2407       --i;
  2408 #ifdef ASSERT
  2409     } else if (use->is_Mem()) {
  2410       if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
  2411         // Don't move related cardmark.
  2412         continue;
  2414       // Memory nodes should have new memory input.
  2415       tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
  2416       assert(tp != NULL, "ptr type");
  2417       int idx = C->get_alias_index(tp);
  2418       assert(get_map(use->_idx) != NULL || idx == alias_idx,
  2419              "Following memory nodes should have new memory input or be on the same memory slice");
  2420     } else if (use->is_Phi()) {
  2421       // Phi nodes should be split and moved already.
  2422       tp = use->as_Phi()->adr_type()->isa_ptr();
  2423       assert(tp != NULL, "ptr type");
  2424       int idx = C->get_alias_index(tp);
  2425       assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
  2426     } else {
  2427       use->dump();
  2428       assert(false, "should not be here");
  2429 #endif
  2434 //
  2435 // Search memory chain of "mem" to find a MemNode whose address
  2436 // is the specified alias index.
  2437 //
  2438 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis) {
  2439   if (orig_mem == NULL)
  2440     return orig_mem;
  2441   Compile* C = _compile;
  2442   PhaseGVN* igvn = _igvn;
  2443   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
  2444   bool is_instance = (toop != NULL) && toop->is_known_instance();
  2445   Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
  2446   Node *prev = NULL;
  2447   Node *result = orig_mem;
  2448   while (prev != result) {
  2449     prev = result;
  2450     if (result == start_mem)
  2451       break;  // hit one of our sentinels
  2452     if (result->is_Mem()) {
  2453       const Type *at = igvn->type(result->in(MemNode::Address));
  2454       if (at == Type::TOP)
  2455         break; // Dead
  2456       assert (at->isa_ptr() != NULL, "pointer type required.");
  2457       int idx = C->get_alias_index(at->is_ptr());
  2458       if (idx == alias_idx)
  2459         break; // Found
  2460       if (!is_instance && (at->isa_oopptr() == NULL ||
  2461                            !at->is_oopptr()->is_known_instance())) {
  2462         break; // Do not skip store to general memory slice.
  2464       result = result->in(MemNode::Memory);
  2466     if (!is_instance)
  2467       continue;  // don't search further for non-instance types
  2468     // skip over a call which does not affect this memory slice
  2469     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
  2470       Node *proj_in = result->in(0);
  2471       if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
  2472         break;  // hit one of our sentinels
  2473       } else if (proj_in->is_Call()) {
  2474         CallNode *call = proj_in->as_Call();
  2475         if (!call->may_modify(toop, igvn)) {
  2476           result = call->in(TypeFunc::Memory);
  2478       } else if (proj_in->is_Initialize()) {
  2479         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
  2480         // Stop if this is the initialization for the object instance which
  2481         // which contains this memory slice, otherwise skip over it.
  2482         if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
  2483           result = proj_in->in(TypeFunc::Memory);
  2485       } else if (proj_in->is_MemBar()) {
  2486         result = proj_in->in(TypeFunc::Memory);
  2488     } else if (result->is_MergeMem()) {
  2489       MergeMemNode *mmem = result->as_MergeMem();
  2490       result = step_through_mergemem(mmem, alias_idx, toop);
  2491       if (result == mmem->base_memory()) {
  2492         // Didn't find instance memory, search through general slice recursively.
  2493         result = mmem->memory_at(C->get_general_index(alias_idx));
  2494         result = find_inst_mem(result, alias_idx, orig_phis);
  2495         if (C->failing()) {
  2496           return NULL;
  2498         mmem->set_memory_at(alias_idx, result);
  2500     } else if (result->is_Phi() &&
  2501                C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
  2502       Node *un = result->as_Phi()->unique_input(igvn);
  2503       if (un != NULL) {
  2504         orig_phis.append_if_missing(result->as_Phi());
  2505         result = un;
  2506       } else {
  2507         break;
  2509     } else if (result->is_ClearArray()) {
  2510       if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
  2511         // Can not bypass initialization of the instance
  2512         // we are looking for.
  2513         break;
  2515       // Otherwise skip it (the call updated 'result' value).
  2516     } else if (result->Opcode() == Op_SCMemProj) {
  2517       assert(result->in(0)->is_LoadStore(), "sanity");
  2518       const Type *at = igvn->type(result->in(0)->in(MemNode::Address));
  2519       if (at != Type::TOP) {
  2520         assert (at->isa_ptr() != NULL, "pointer type required.");
  2521         int idx = C->get_alias_index(at->is_ptr());
  2522         assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
  2523         break;
  2525       result = result->in(0)->in(MemNode::Memory);
  2528   if (result->is_Phi()) {
  2529     PhiNode *mphi = result->as_Phi();
  2530     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
  2531     const TypePtr *t = mphi->adr_type();
  2532     if (!is_instance) {
  2533       // Push all non-instance Phis on the orig_phis worklist to update inputs
  2534       // during Phase 4 if needed.
  2535       orig_phis.append_if_missing(mphi);
  2536     } else if (C->get_alias_index(t) != alias_idx) {
  2537       // Create a new Phi with the specified alias index type.
  2538       result = split_memory_phi(mphi, alias_idx, orig_phis);
  2541   // the result is either MemNode, PhiNode, InitializeNode.
  2542   return result;
  2545 //
  2546 //  Convert the types of unescaped object to instance types where possible,
  2547 //  propagate the new type information through the graph, and update memory
  2548 //  edges and MergeMem inputs to reflect the new type.
  2549 //
  2550 //  We start with allocations (and calls which may be allocations)  on alloc_worklist.
  2551 //  The processing is done in 4 phases:
  2552 //
  2553 //  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
  2554 //            types for the CheckCastPP for allocations where possible.
  2555 //            Propagate the the new types through users as follows:
  2556 //               casts and Phi:  push users on alloc_worklist
  2557 //               AddP:  cast Base and Address inputs to the instance type
  2558 //                      push any AddP users on alloc_worklist and push any memnode
  2559 //                      users onto memnode_worklist.
  2560 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
  2561 //            search the Memory chain for a store with the appropriate type
  2562 //            address type.  If a Phi is found, create a new version with
  2563 //            the appropriate memory slices from each of the Phi inputs.
  2564 //            For stores, process the users as follows:
  2565 //               MemNode:  push on memnode_worklist
  2566 //               MergeMem: push on mergemem_worklist
  2567 //  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
  2568 //            moving the first node encountered of each  instance type to the
  2569 //            the input corresponding to its alias index.
  2570 //            appropriate memory slice.
  2571 //  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
  2572 //
  2573 // In the following example, the CheckCastPP nodes are the cast of allocation
  2574 // results and the allocation of node 29 is unescaped and eligible to be an
  2575 // instance type.
  2576 //
  2577 // We start with:
  2578 //
  2579 //     7 Parm #memory
  2580 //    10  ConI  "12"
  2581 //    19  CheckCastPP   "Foo"
  2582 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
  2583 //    29  CheckCastPP   "Foo"
  2584 //    30  AddP  _ 29 29 10  Foo+12  alias_index=4
  2585 //
  2586 //    40  StoreP  25   7  20   ... alias_index=4
  2587 //    50  StoreP  35  40  30   ... alias_index=4
  2588 //    60  StoreP  45  50  20   ... alias_index=4
  2589 //    70  LoadP    _  60  30   ... alias_index=4
  2590 //    80  Phi     75  50  60   Memory alias_index=4
  2591 //    90  LoadP    _  80  30   ... alias_index=4
  2592 //   100  LoadP    _  80  20   ... alias_index=4
  2593 //
  2594 //
  2595 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
  2596 // and creating a new alias index for node 30.  This gives:
  2597 //
  2598 //     7 Parm #memory
  2599 //    10  ConI  "12"
  2600 //    19  CheckCastPP   "Foo"
  2601 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
  2602 //    29  CheckCastPP   "Foo"  iid=24
  2603 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
  2604 //
  2605 //    40  StoreP  25   7  20   ... alias_index=4
  2606 //    50  StoreP  35  40  30   ... alias_index=6
  2607 //    60  StoreP  45  50  20   ... alias_index=4
  2608 //    70  LoadP    _  60  30   ... alias_index=6
  2609 //    80  Phi     75  50  60   Memory alias_index=4
  2610 //    90  LoadP    _  80  30   ... alias_index=6
  2611 //   100  LoadP    _  80  20   ... alias_index=4
  2612 //
  2613 // In phase 2, new memory inputs are computed for the loads and stores,
  2614 // And a new version of the phi is created.  In phase 4, the inputs to
  2615 // node 80 are updated and then the memory nodes are updated with the
  2616 // values computed in phase 2.  This results in:
  2617 //
  2618 //     7 Parm #memory
  2619 //    10  ConI  "12"
  2620 //    19  CheckCastPP   "Foo"
  2621 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
  2622 //    29  CheckCastPP   "Foo"  iid=24
  2623 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
  2624 //
  2625 //    40  StoreP  25  7   20   ... alias_index=4
  2626 //    50  StoreP  35  7   30   ... alias_index=6
  2627 //    60  StoreP  45  40  20   ... alias_index=4
  2628 //    70  LoadP    _  50  30   ... alias_index=6
  2629 //    80  Phi     75  40  60   Memory alias_index=4
  2630 //   120  Phi     75  50  50   Memory alias_index=6
  2631 //    90  LoadP    _ 120  30   ... alias_index=6
  2632 //   100  LoadP    _  80  20   ... alias_index=4
  2633 //
  2634 void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist) {
  2635   GrowableArray<Node *>  memnode_worklist;
  2636   GrowableArray<PhiNode *>  orig_phis;
  2637   PhaseIterGVN  *igvn = _igvn;
  2638   uint new_index_start = (uint) _compile->num_alias_types();
  2639   Arena* arena = Thread::current()->resource_area();
  2640   VectorSet visited(arena);
  2641   ideal_nodes.clear(); // Reset for use with set_map/get_map.
  2642   uint unique_old = _compile->unique();
  2644   //  Phase 1:  Process possible allocations from alloc_worklist.
  2645   //  Create instance types for the CheckCastPP for allocations where possible.
  2646   //
  2647   // (Note: don't forget to change the order of the second AddP node on
  2648   //  the alloc_worklist if the order of the worklist processing is changed,
  2649   //  see the comment in find_second_addp().)
  2650   //
  2651   while (alloc_worklist.length() != 0) {
  2652     Node *n = alloc_worklist.pop();
  2653     uint ni = n->_idx;
  2654     if (n->is_Call()) {
  2655       CallNode *alloc = n->as_Call();
  2656       // copy escape information to call node
  2657       PointsToNode* ptn = ptnode_adr(alloc->_idx);
  2658       PointsToNode::EscapeState es = ptn->escape_state();
  2659       // We have an allocation or call which returns a Java object,
  2660       // see if it is unescaped.
  2661       if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable())
  2662         continue;
  2663       // Find CheckCastPP for the allocate or for the return value of a call
  2664       n = alloc->result_cast();
  2665       if (n == NULL) {            // No uses except Initialize node
  2666         if (alloc->is_Allocate()) {
  2667           // Set the scalar_replaceable flag for allocation
  2668           // so it could be eliminated if it has no uses.
  2669           alloc->as_Allocate()->_is_scalar_replaceable = true;
  2671         continue;
  2673       if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
  2674         assert(!alloc->is_Allocate(), "allocation should have unique type");
  2675         continue;
  2678       // The inline code for Object.clone() casts the allocation result to
  2679       // java.lang.Object and then to the actual type of the allocated
  2680       // object. Detect this case and use the second cast.
  2681       // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
  2682       // the allocation result is cast to java.lang.Object and then
  2683       // to the actual Array type.
  2684       if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
  2685           && (alloc->is_AllocateArray() ||
  2686               igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) {
  2687         Node *cast2 = NULL;
  2688         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2689           Node *use = n->fast_out(i);
  2690           if (use->is_CheckCastPP()) {
  2691             cast2 = use;
  2692             break;
  2695         if (cast2 != NULL) {
  2696           n = cast2;
  2697         } else {
  2698           // Non-scalar replaceable if the allocation type is unknown statically
  2699           // (reflection allocation), the object can't be restored during
  2700           // deoptimization without precise type.
  2701           continue;
  2704       if (alloc->is_Allocate()) {
  2705         // Set the scalar_replaceable flag for allocation
  2706         // so it could be eliminated.
  2707         alloc->as_Allocate()->_is_scalar_replaceable = true;
  2709       set_escape_state(ptnode_adr(n->_idx), es); // CheckCastPP escape state
  2710       // in order for an object to be scalar-replaceable, it must be:
  2711       //   - a direct allocation (not a call returning an object)
  2712       //   - non-escaping
  2713       //   - eligible to be a unique type
  2714       //   - not determined to be ineligible by escape analysis
  2715       set_map(alloc, n);
  2716       set_map(n, alloc);
  2717       const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
  2718       if (t == NULL)
  2719         continue;  // not a TypeOopPtr
  2720       const TypeOopPtr* tinst = t->cast_to_exactness(true)->is_oopptr()->cast_to_instance_id(ni);
  2721       igvn->hash_delete(n);
  2722       igvn->set_type(n,  tinst);
  2723       n->raise_bottom_type(tinst);
  2724       igvn->hash_insert(n);
  2725       record_for_optimizer(n);
  2726       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
  2728         // First, put on the worklist all Field edges from Connection Graph
  2729         // which is more accurate then putting immediate users from Ideal Graph.
  2730         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
  2731           PointsToNode* tgt = e.get();
  2732           Node* use = tgt->ideal_node();
  2733           assert(tgt->is_Field() && use->is_AddP(),
  2734                  "only AddP nodes are Field edges in CG");
  2735           if (use->outcnt() > 0) { // Don't process dead nodes
  2736             Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
  2737             if (addp2 != NULL) {
  2738               assert(alloc->is_AllocateArray(),"array allocation was expected");
  2739               alloc_worklist.append_if_missing(addp2);
  2741             alloc_worklist.append_if_missing(use);
  2745         // An allocation may have an Initialize which has raw stores. Scan
  2746         // the users of the raw allocation result and push AddP users
  2747         // on alloc_worklist.
  2748         Node *raw_result = alloc->proj_out(TypeFunc::Parms);
  2749         assert (raw_result != NULL, "must have an allocation result");
  2750         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
  2751           Node *use = raw_result->fast_out(i);
  2752           if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
  2753             Node* addp2 = find_second_addp(use, raw_result);
  2754             if (addp2 != NULL) {
  2755               assert(alloc->is_AllocateArray(),"array allocation was expected");
  2756               alloc_worklist.append_if_missing(addp2);
  2758             alloc_worklist.append_if_missing(use);
  2759           } else if (use->is_MemBar()) {
  2760             memnode_worklist.append_if_missing(use);
  2764     } else if (n->is_AddP()) {
  2765       JavaObjectNode* jobj = unique_java_object(get_addp_base(n));
  2766       if (jobj == NULL || jobj == phantom_obj) {
  2767 #ifdef ASSERT
  2768         ptnode_adr(get_addp_base(n)->_idx)->dump();
  2769         ptnode_adr(n->_idx)->dump();
  2770         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
  2771 #endif
  2772         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
  2773         return;
  2775       Node *base = get_map(jobj->idx());  // CheckCastPP node
  2776       if (!split_AddP(n, base)) continue; // wrong type from dead path
  2777     } else if (n->is_Phi() ||
  2778                n->is_CheckCastPP() ||
  2779                n->is_EncodeP() ||
  2780                n->is_DecodeN() ||
  2781                (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
  2782       if (visited.test_set(n->_idx)) {
  2783         assert(n->is_Phi(), "loops only through Phi's");
  2784         continue;  // already processed
  2786       JavaObjectNode* jobj = unique_java_object(n);
  2787       if (jobj == NULL || jobj == phantom_obj) {
  2788 #ifdef ASSERT
  2789         ptnode_adr(n->_idx)->dump();
  2790         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
  2791 #endif
  2792         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
  2793         return;
  2794       } else {
  2795         Node *val = get_map(jobj->idx());   // CheckCastPP node
  2796         TypeNode *tn = n->as_Type();
  2797         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
  2798         assert(tinst != NULL && tinst->is_known_instance() &&
  2799                tinst->instance_id() == jobj->idx() , "instance type expected.");
  2801         const Type *tn_type = igvn->type(tn);
  2802         const TypeOopPtr *tn_t;
  2803         if (tn_type->isa_narrowoop()) {
  2804           tn_t = tn_type->make_ptr()->isa_oopptr();
  2805         } else {
  2806           tn_t = tn_type->isa_oopptr();
  2808         if (tn_t != NULL && tinst->klass()->is_subtype_of(tn_t->klass())) {
  2809           if (tn_type->isa_narrowoop()) {
  2810             tn_type = tinst->make_narrowoop();
  2811           } else {
  2812             tn_type = tinst;
  2814           igvn->hash_delete(tn);
  2815           igvn->set_type(tn, tn_type);
  2816           tn->set_type(tn_type);
  2817           igvn->hash_insert(tn);
  2818           record_for_optimizer(n);
  2819         } else {
  2820           assert(tn_type == TypePtr::NULL_PTR ||
  2821                  tn_t != NULL && !tinst->klass()->is_subtype_of(tn_t->klass()),
  2822                  "unexpected type");
  2823           continue; // Skip dead path with different type
  2826     } else {
  2827       debug_only(n->dump();)
  2828       assert(false, "EA: unexpected node");
  2829       continue;
  2831     // push allocation's users on appropriate worklist
  2832     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2833       Node *use = n->fast_out(i);
  2834       if(use->is_Mem() && use->in(MemNode::Address) == n) {
  2835         // Load/store to instance's field
  2836         memnode_worklist.append_if_missing(use);
  2837       } else if (use->is_MemBar()) {
  2838         memnode_worklist.append_if_missing(use);
  2839       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
  2840         Node* addp2 = find_second_addp(use, n);
  2841         if (addp2 != NULL) {
  2842           alloc_worklist.append_if_missing(addp2);
  2844         alloc_worklist.append_if_missing(use);
  2845       } else if (use->is_Phi() ||
  2846                  use->is_CheckCastPP() ||
  2847                  use->is_EncodeNarrowPtr() ||
  2848                  use->is_DecodeNarrowPtr() ||
  2849                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
  2850         alloc_worklist.append_if_missing(use);
  2851 #ifdef ASSERT
  2852       } else if (use->is_Mem()) {
  2853         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
  2854       } else if (use->is_MergeMem()) {
  2855         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
  2856       } else if (use->is_SafePoint()) {
  2857         // Look for MergeMem nodes for calls which reference unique allocation
  2858         // (through CheckCastPP nodes) even for debug info.
  2859         Node* m = use->in(TypeFunc::Memory);
  2860         if (m->is_MergeMem()) {
  2861           assert(_mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
  2863       } else {
  2864         uint op = use->Opcode();
  2865         if (!(op == Op_CmpP || op == Op_Conv2B ||
  2866               op == Op_CastP2X || op == Op_StoreCM ||
  2867               op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
  2868               op == Op_StrEquals || op == Op_StrIndexOf)) {
  2869           n->dump();
  2870           use->dump();
  2871           assert(false, "EA: missing allocation reference path");
  2873 #endif
  2878   // New alias types were created in split_AddP().
  2879   uint new_index_end = (uint) _compile->num_alias_types();
  2880   assert(unique_old == _compile->unique(), "there should be no new ideal nodes after Phase 1");
  2882   //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
  2883   //            compute new values for Memory inputs  (the Memory inputs are not
  2884   //            actually updated until phase 4.)
  2885   if (memnode_worklist.length() == 0)
  2886     return;  // nothing to do
  2887   while (memnode_worklist.length() != 0) {
  2888     Node *n = memnode_worklist.pop();
  2889     if (visited.test_set(n->_idx))
  2890       continue;
  2891     if (n->is_Phi() || n->is_ClearArray()) {
  2892       // we don't need to do anything, but the users must be pushed
  2893     } else if (n->is_MemBar()) { // Initialize, MemBar nodes
  2894       // we don't need to do anything, but the users must be pushed
  2895       n = n->as_MemBar()->proj_out(TypeFunc::Memory);
  2896       if (n == NULL)
  2897         continue;
  2898     } else {
  2899       assert(n->is_Mem(), "memory node required.");
  2900       Node *addr = n->in(MemNode::Address);
  2901       const Type *addr_t = igvn->type(addr);
  2902       if (addr_t == Type::TOP)
  2903         continue;
  2904       assert (addr_t->isa_ptr() != NULL, "pointer type required.");
  2905       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
  2906       assert ((uint)alias_idx < new_index_end, "wrong alias index");
  2907       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
  2908       if (_compile->failing()) {
  2909         return;
  2911       if (mem != n->in(MemNode::Memory)) {
  2912         // We delay the memory edge update since we need old one in
  2913         // MergeMem code below when instances memory slices are separated.
  2914         set_map(n, mem);
  2916       if (n->is_Load()) {
  2917         continue;  // don't push users
  2918       } else if (n->is_LoadStore()) {
  2919         // get the memory projection
  2920         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2921           Node *use = n->fast_out(i);
  2922           if (use->Opcode() == Op_SCMemProj) {
  2923             n = use;
  2924             break;
  2927         assert(n->Opcode() == Op_SCMemProj, "memory projection required");
  2930     // push user on appropriate worklist
  2931     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2932       Node *use = n->fast_out(i);
  2933       if (use->is_Phi() || use->is_ClearArray()) {
  2934         memnode_worklist.append_if_missing(use);
  2935       } else if(use->is_Mem() && use->in(MemNode::Memory) == n) {
  2936         if (use->Opcode() == Op_StoreCM) // Ignore cardmark stores
  2937           continue;
  2938         memnode_worklist.append_if_missing(use);
  2939       } else if (use->is_MemBar()) {
  2940         memnode_worklist.append_if_missing(use);
  2941 #ifdef ASSERT
  2942       } else if(use->is_Mem()) {
  2943         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
  2944       } else if (use->is_MergeMem()) {
  2945         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
  2946       } else {
  2947         uint op = use->Opcode();
  2948         if (!(op == Op_StoreCM ||
  2949               (op == Op_CallLeaf && use->as_CallLeaf()->_name != NULL &&
  2950                strcmp(use->as_CallLeaf()->_name, "g1_wb_pre") == 0) ||
  2951               op == Op_AryEq || op == Op_StrComp ||
  2952               op == Op_StrEquals || op == Op_StrIndexOf)) {
  2953           n->dump();
  2954           use->dump();
  2955           assert(false, "EA: missing memory path");
  2957 #endif
  2962   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
  2963   //            Walk each memory slice moving the first node encountered of each
  2964   //            instance type to the the input corresponding to its alias index.
  2965   uint length = _mergemem_worklist.length();
  2966   for( uint next = 0; next < length; ++next ) {
  2967     MergeMemNode* nmm = _mergemem_worklist.at(next);
  2968     assert(!visited.test_set(nmm->_idx), "should not be visited before");
  2969     // Note: we don't want to use MergeMemStream here because we only want to
  2970     // scan inputs which exist at the start, not ones we add during processing.
  2971     // Note 2: MergeMem may already contains instance memory slices added
  2972     // during find_inst_mem() call when memory nodes were processed above.
  2973     igvn->hash_delete(nmm);
  2974     uint nslices = nmm->req();
  2975     for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
  2976       Node* mem = nmm->in(i);
  2977       Node* cur = NULL;
  2978       if (mem == NULL || mem->is_top())
  2979         continue;
  2980       // First, update mergemem by moving memory nodes to corresponding slices
  2981       // if their type became more precise since this mergemem was created.
  2982       while (mem->is_Mem()) {
  2983         const Type *at = igvn->type(mem->in(MemNode::Address));
  2984         if (at != Type::TOP) {
  2985           assert (at->isa_ptr() != NULL, "pointer type required.");
  2986           uint idx = (uint)_compile->get_alias_index(at->is_ptr());
  2987           if (idx == i) {
  2988             if (cur == NULL)
  2989               cur = mem;
  2990           } else {
  2991             if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
  2992               nmm->set_memory_at(idx, mem);
  2996         mem = mem->in(MemNode::Memory);
  2998       nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
  2999       // Find any instance of the current type if we haven't encountered
  3000       // already a memory slice of the instance along the memory chain.
  3001       for (uint ni = new_index_start; ni < new_index_end; ni++) {
  3002         if((uint)_compile->get_general_index(ni) == i) {
  3003           Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
  3004           if (nmm->is_empty_memory(m)) {
  3005             Node* result = find_inst_mem(mem, ni, orig_phis);
  3006             if (_compile->failing()) {
  3007               return;
  3009             nmm->set_memory_at(ni, result);
  3014     // Find the rest of instances values
  3015     for (uint ni = new_index_start; ni < new_index_end; ni++) {
  3016       const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
  3017       Node* result = step_through_mergemem(nmm, ni, tinst);
  3018       if (result == nmm->base_memory()) {
  3019         // Didn't find instance memory, search through general slice recursively.
  3020         result = nmm->memory_at(_compile->get_general_index(ni));
  3021         result = find_inst_mem(result, ni, orig_phis);
  3022         if (_compile->failing()) {
  3023           return;
  3025         nmm->set_memory_at(ni, result);
  3028     igvn->hash_insert(nmm);
  3029     record_for_optimizer(nmm);
  3032   //  Phase 4:  Update the inputs of non-instance memory Phis and
  3033   //            the Memory input of memnodes
  3034   // First update the inputs of any non-instance Phi's from
  3035   // which we split out an instance Phi.  Note we don't have
  3036   // to recursively process Phi's encounted on the input memory
  3037   // chains as is done in split_memory_phi() since they  will
  3038   // also be processed here.
  3039   for (int j = 0; j < orig_phis.length(); j++) {
  3040     PhiNode *phi = orig_phis.at(j);
  3041     int alias_idx = _compile->get_alias_index(phi->adr_type());
  3042     igvn->hash_delete(phi);
  3043     for (uint i = 1; i < phi->req(); i++) {
  3044       Node *mem = phi->in(i);
  3045       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
  3046       if (_compile->failing()) {
  3047         return;
  3049       if (mem != new_mem) {
  3050         phi->set_req(i, new_mem);
  3053     igvn->hash_insert(phi);
  3054     record_for_optimizer(phi);
  3057   // Update the memory inputs of MemNodes with the value we computed
  3058   // in Phase 2 and move stores memory users to corresponding memory slices.
  3059   // Disable memory split verification code until the fix for 6984348.
  3060   // Currently it produces false negative results since it does not cover all cases.
  3061 #if 0 // ifdef ASSERT
  3062   visited.Reset();
  3063   Node_Stack old_mems(arena, _compile->unique() >> 2);
  3064 #endif
  3065   for (uint i = 0; i < ideal_nodes.size(); i++) {
  3066     Node*    n = ideal_nodes.at(i);
  3067     Node* nmem = get_map(n->_idx);
  3068     assert(nmem != NULL, "sanity");
  3069     if (n->is_Mem()) {
  3070 #if 0 // ifdef ASSERT
  3071       Node* old_mem = n->in(MemNode::Memory);
  3072       if (!visited.test_set(old_mem->_idx)) {
  3073         old_mems.push(old_mem, old_mem->outcnt());
  3075 #endif
  3076       assert(n->in(MemNode::Memory) != nmem, "sanity");
  3077       if (!n->is_Load()) {
  3078         // Move memory users of a store first.
  3079         move_inst_mem(n, orig_phis);
  3081       // Now update memory input
  3082       igvn->hash_delete(n);
  3083       n->set_req(MemNode::Memory, nmem);
  3084       igvn->hash_insert(n);
  3085       record_for_optimizer(n);
  3086     } else {
  3087       assert(n->is_Allocate() || n->is_CheckCastPP() ||
  3088              n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
  3091 #if 0 // ifdef ASSERT
  3092   // Verify that memory was split correctly
  3093   while (old_mems.is_nonempty()) {
  3094     Node* old_mem = old_mems.node();
  3095     uint  old_cnt = old_mems.index();
  3096     old_mems.pop();
  3097     assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
  3099 #endif
  3102 #ifndef PRODUCT
  3103 static const char *node_type_names[] = {
  3104   "UnknownType",
  3105   "JavaObject",
  3106   "LocalVar",
  3107   "Field",
  3108   "Arraycopy"
  3109 };
  3111 static const char *esc_names[] = {
  3112   "UnknownEscape",
  3113   "NoEscape",
  3114   "ArgEscape",
  3115   "GlobalEscape"
  3116 };
  3118 void PointsToNode::dump(bool print_state) const {
  3119   NodeType nt = node_type();
  3120   tty->print("%s ", node_type_names[(int) nt]);
  3121   if (print_state) {
  3122     EscapeState es = escape_state();
  3123     EscapeState fields_es = fields_escape_state();
  3124     tty->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
  3125     if (nt == PointsToNode::JavaObject && !this->scalar_replaceable())
  3126       tty->print("NSR");
  3128   if (is_Field()) {
  3129     FieldNode* f = (FieldNode*)this;
  3130     tty->print("(");
  3131     for (BaseIterator i(f); i.has_next(); i.next()) {
  3132       PointsToNode* b = i.get();
  3133       tty->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
  3135     tty->print(" )");
  3137   tty->print("[");
  3138   for (EdgeIterator i(this); i.has_next(); i.next()) {
  3139     PointsToNode* e = i.get();
  3140     tty->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
  3142   tty->print(" [");
  3143   for (UseIterator i(this); i.has_next(); i.next()) {
  3144     PointsToNode* u = i.get();
  3145     bool is_base = false;
  3146     if (PointsToNode::is_base_use(u)) {
  3147       is_base = true;
  3148       u = PointsToNode::get_use_node(u)->as_Field();
  3150     tty->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
  3152   tty->print(" ]]  ");
  3153   if (_node == NULL)
  3154     tty->print_cr("<null>");
  3155   else
  3156     _node->dump();
  3159 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
  3160   bool first = true;
  3161   int ptnodes_length = ptnodes_worklist.length();
  3162   for (int i = 0; i < ptnodes_length; i++) {
  3163     PointsToNode *ptn = ptnodes_worklist.at(i);
  3164     if (ptn == NULL || !ptn->is_JavaObject())
  3165       continue;
  3166     PointsToNode::EscapeState es = ptn->escape_state();
  3167     if (ptn->ideal_node()->is_Allocate() && (es == PointsToNode::NoEscape || Verbose)) {
  3168       if (first) {
  3169         tty->cr();
  3170         tty->print("======== Connection graph for ");
  3171         _compile->method()->print_short_name();
  3172         tty->cr();
  3173         first = false;
  3175       ptn->dump();
  3176       // Print all locals and fields which reference this allocation
  3177       for (UseIterator j(ptn); j.has_next(); j.next()) {
  3178         PointsToNode* use = j.get();
  3179         if (use->is_LocalVar()) {
  3180           use->dump(Verbose);
  3181         } else if (Verbose) {
  3182           use->dump();
  3185       tty->cr();
  3189 #endif

mercurial