1 /*
2 * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "gc/shared/barrierSet.hpp"
27 #include "gc/shared/c2/barrierSetC2.hpp"
28 #include "memory/allocation.inline.hpp"
29 #include "memory/resourceArea.hpp"
30 #include "opto/block.hpp"
31 #include "opto/callnode.hpp"
32 #include "opto/castnode.hpp"
33 #include "opto/cfgnode.hpp"
34 #include "opto/idealGraphPrinter.hpp"
35 #include "opto/loopnode.hpp"
36 #include "opto/machnode.hpp"
37 #include "opto/opcodes.hpp"
38 #include "opto/phaseX.hpp"
39 #include "opto/regalloc.hpp"
40 #include "opto/rootnode.hpp"
41 #include "utilities/macros.hpp"
42 #include "utilities/powerOfTwo.hpp"
43
44 //=============================================================================
45 #define NODE_HASH_MINIMUM_SIZE 255
46 //------------------------------NodeHash---------------------------------------
NodeHash(uint est_max_size)47 NodeHash::NodeHash(uint est_max_size) :
48 _a(Thread::current()->resource_area()),
49 _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
50 _inserts(0), _insert_limit( insert_limit() ),
51 _table( NEW_ARENA_ARRAY( _a , Node* , _max ) ) // (Node**)_a->Amalloc(_max * sizeof(Node*)) ),
52 #ifndef PRODUCT
53 , _grows(0),_look_probes(0), _lookup_hits(0), _lookup_misses(0),
54 _insert_probes(0), _delete_probes(0), _delete_hits(0), _delete_misses(0),
55 _total_inserts(0), _total_insert_probes(0)
56 #endif
57 {
58 // _sentinel must be in the current node space
59 _sentinel = new ProjNode(NULL, TypeFunc::Control);
60 memset(_table,0,sizeof(Node*)*_max);
61 }
62
63 //------------------------------NodeHash---------------------------------------
NodeHash(Arena * arena,uint est_max_size)64 NodeHash::NodeHash(Arena *arena, uint est_max_size) :
65 _a(arena),
66 _max( round_up(est_max_size < NODE_HASH_MINIMUM_SIZE ? NODE_HASH_MINIMUM_SIZE : est_max_size) ),
67 _inserts(0), _insert_limit( insert_limit() ),
68 _table( NEW_ARENA_ARRAY( _a , Node* , _max ) )
69 #ifndef PRODUCT
70 , _grows(0),_look_probes(0), _lookup_hits(0), _lookup_misses(0),
71 _insert_probes(0), _delete_probes(0), _delete_hits(0), _delete_misses(0),
72 _total_inserts(0), _total_insert_probes(0)
73 #endif
74 {
75 // _sentinel must be in the current node space
76 _sentinel = new ProjNode(NULL, TypeFunc::Control);
77 memset(_table,0,sizeof(Node*)*_max);
78 }
79
80 //------------------------------NodeHash---------------------------------------
NodeHash(NodeHash * nh)81 NodeHash::NodeHash(NodeHash *nh) {
82 debug_only(_table = (Node**)badAddress); // interact correctly w/ operator=
83 // just copy in all the fields
84 *this = *nh;
85 // nh->_sentinel must be in the current node space
86 }
87
replace_with(NodeHash * nh)88 void NodeHash::replace_with(NodeHash *nh) {
89 debug_only(_table = (Node**)badAddress); // interact correctly w/ operator=
90 // just copy in all the fields
91 *this = *nh;
92 // nh->_sentinel must be in the current node space
93 }
94
95 //------------------------------hash_find--------------------------------------
96 // Find in hash table
hash_find(const Node * n)97 Node *NodeHash::hash_find( const Node *n ) {
98 // ((Node*)n)->set_hash( n->hash() );
99 uint hash = n->hash();
100 if (hash == Node::NO_HASH) {
101 NOT_PRODUCT( _lookup_misses++ );
102 return NULL;
103 }
104 uint key = hash & (_max-1);
105 uint stride = key | 0x01;
106 NOT_PRODUCT( _look_probes++ );
107 Node *k = _table[key]; // Get hashed value
108 if( !k ) { // ?Miss?
109 NOT_PRODUCT( _lookup_misses++ );
110 return NULL; // Miss!
111 }
112
113 int op = n->Opcode();
114 uint req = n->req();
115 while( 1 ) { // While probing hash table
116 if( k->req() == req && // Same count of inputs
117 k->Opcode() == op ) { // Same Opcode
118 for( uint i=0; i<req; i++ )
119 if( n->in(i)!=k->in(i)) // Different inputs?
120 goto collision; // "goto" is a speed hack...
121 if( n->cmp(*k) ) { // Check for any special bits
122 NOT_PRODUCT( _lookup_hits++ );
123 return k; // Hit!
124 }
125 }
126 collision:
127 NOT_PRODUCT( _look_probes++ );
128 key = (key + stride/*7*/) & (_max-1); // Stride through table with relative prime
129 k = _table[key]; // Get hashed value
130 if( !k ) { // ?Miss?
131 NOT_PRODUCT( _lookup_misses++ );
132 return NULL; // Miss!
133 }
134 }
135 ShouldNotReachHere();
136 return NULL;
137 }
138
139 //------------------------------hash_find_insert-------------------------------
140 // Find in hash table, insert if not already present
141 // Used to preserve unique entries in hash table
hash_find_insert(Node * n)142 Node *NodeHash::hash_find_insert( Node *n ) {
143 // n->set_hash( );
144 uint hash = n->hash();
145 if (hash == Node::NO_HASH) {
146 NOT_PRODUCT( _lookup_misses++ );
147 return NULL;
148 }
149 uint key = hash & (_max-1);
150 uint stride = key | 0x01; // stride must be relatively prime to table siz
151 uint first_sentinel = 0; // replace a sentinel if seen.
152 NOT_PRODUCT( _look_probes++ );
153 Node *k = _table[key]; // Get hashed value
154 if( !k ) { // ?Miss?
155 NOT_PRODUCT( _lookup_misses++ );
156 _table[key] = n; // Insert into table!
157 debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
158 check_grow(); // Grow table if insert hit limit
159 return NULL; // Miss!
160 }
161 else if( k == _sentinel ) {
162 first_sentinel = key; // Can insert here
163 }
164
165 int op = n->Opcode();
166 uint req = n->req();
167 while( 1 ) { // While probing hash table
168 if( k->req() == req && // Same count of inputs
169 k->Opcode() == op ) { // Same Opcode
170 for( uint i=0; i<req; i++ )
171 if( n->in(i)!=k->in(i)) // Different inputs?
172 goto collision; // "goto" is a speed hack...
173 if( n->cmp(*k) ) { // Check for any special bits
174 NOT_PRODUCT( _lookup_hits++ );
175 return k; // Hit!
176 }
177 }
178 collision:
179 NOT_PRODUCT( _look_probes++ );
180 key = (key + stride) & (_max-1); // Stride through table w/ relative prime
181 k = _table[key]; // Get hashed value
182 if( !k ) { // ?Miss?
183 NOT_PRODUCT( _lookup_misses++ );
184 key = (first_sentinel == 0) ? key : first_sentinel; // ?saw sentinel?
185 _table[key] = n; // Insert into table!
186 debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
187 check_grow(); // Grow table if insert hit limit
188 return NULL; // Miss!
189 }
190 else if( first_sentinel == 0 && k == _sentinel ) {
191 first_sentinel = key; // Can insert here
192 }
193
194 }
195 ShouldNotReachHere();
196 return NULL;
197 }
198
199 //------------------------------hash_insert------------------------------------
200 // Insert into hash table
hash_insert(Node * n)201 void NodeHash::hash_insert( Node *n ) {
202 // // "conflict" comments -- print nodes that conflict
203 // bool conflict = false;
204 // n->set_hash();
205 uint hash = n->hash();
206 if (hash == Node::NO_HASH) {
207 return;
208 }
209 check_grow();
210 uint key = hash & (_max-1);
211 uint stride = key | 0x01;
212
213 while( 1 ) { // While probing hash table
214 NOT_PRODUCT( _insert_probes++ );
215 Node *k = _table[key]; // Get hashed value
216 if( !k || (k == _sentinel) ) break; // Found a slot
217 assert( k != n, "already inserted" );
218 // if( PrintCompilation && PrintOptoStatistics && Verbose ) { tty->print(" conflict: "); k->dump(); conflict = true; }
219 key = (key + stride) & (_max-1); // Stride through table w/ relative prime
220 }
221 _table[key] = n; // Insert into table!
222 debug_only(n->enter_hash_lock()); // Lock down the node while in the table.
223 // if( conflict ) { n->dump(); }
224 }
225
226 //------------------------------hash_delete------------------------------------
227 // Replace in hash table with sentinel
hash_delete(const Node * n)228 bool NodeHash::hash_delete( const Node *n ) {
229 Node *k;
230 uint hash = n->hash();
231 if (hash == Node::NO_HASH) {
232 NOT_PRODUCT( _delete_misses++ );
233 return false;
234 }
235 uint key = hash & (_max-1);
236 uint stride = key | 0x01;
237 debug_only( uint counter = 0; );
238 for( ; /* (k != NULL) && (k != _sentinel) */; ) {
239 debug_only( counter++ );
240 NOT_PRODUCT( _delete_probes++ );
241 k = _table[key]; // Get hashed value
242 if( !k ) { // Miss?
243 NOT_PRODUCT( _delete_misses++ );
244 return false; // Miss! Not in chain
245 }
246 else if( n == k ) {
247 NOT_PRODUCT( _delete_hits++ );
248 _table[key] = _sentinel; // Hit! Label as deleted entry
249 debug_only(((Node*)n)->exit_hash_lock()); // Unlock the node upon removal from table.
250 return true;
251 }
252 else {
253 // collision: move through table with prime offset
254 key = (key + stride/*7*/) & (_max-1);
255 assert( counter <= _insert_limit, "Cycle in hash-table");
256 }
257 }
258 ShouldNotReachHere();
259 return false;
260 }
261
262 //------------------------------round_up---------------------------------------
263 // Round up to nearest power of 2
round_up(uint x)264 uint NodeHash::round_up(uint x) {
265 x += (x >> 2); // Add 25% slop
266 return MAX2(16U, round_up_power_of_2(x));
267 }
268
269 //------------------------------grow-------------------------------------------
270 // Grow _table to next power of 2 and insert old entries
grow()271 void NodeHash::grow() {
272 // Record old state
273 uint old_max = _max;
274 Node **old_table = _table;
275 // Construct new table with twice the space
276 #ifndef PRODUCT
277 _grows++;
278 _total_inserts += _inserts;
279 _total_insert_probes += _insert_probes;
280 _insert_probes = 0;
281 #endif
282 _inserts = 0;
283 _max = _max << 1;
284 _table = NEW_ARENA_ARRAY( _a , Node* , _max ); // (Node**)_a->Amalloc( _max * sizeof(Node*) );
285 memset(_table,0,sizeof(Node*)*_max);
286 _insert_limit = insert_limit();
287 // Insert old entries into the new table
288 for( uint i = 0; i < old_max; i++ ) {
289 Node *m = *old_table++;
290 if( !m || m == _sentinel ) continue;
291 debug_only(m->exit_hash_lock()); // Unlock the node upon removal from old table.
292 hash_insert(m);
293 }
294 }
295
296 //------------------------------clear------------------------------------------
297 // Clear all entries in _table to NULL but keep storage
clear()298 void NodeHash::clear() {
299 #ifdef ASSERT
300 // Unlock all nodes upon removal from table.
301 for (uint i = 0; i < _max; i++) {
302 Node* n = _table[i];
303 if (!n || n == _sentinel) continue;
304 n->exit_hash_lock();
305 }
306 #endif
307
308 memset( _table, 0, _max * sizeof(Node*) );
309 }
310
311 //-----------------------remove_useless_nodes----------------------------------
312 // Remove useless nodes from value table,
313 // implementation does not depend on hash function
remove_useless_nodes(VectorSet & useful)314 void NodeHash::remove_useless_nodes(VectorSet &useful) {
315
316 // Dead nodes in the hash table inherited from GVN should not replace
317 // existing nodes, remove dead nodes.
318 uint max = size();
319 Node *sentinel_node = sentinel();
320 for( uint i = 0; i < max; ++i ) {
321 Node *n = at(i);
322 if(n != NULL && n != sentinel_node && !useful.test(n->_idx)) {
323 debug_only(n->exit_hash_lock()); // Unlock the node when removed
324 _table[i] = sentinel_node; // Replace with placeholder
325 }
326 }
327 }
328
329
check_no_speculative_types()330 void NodeHash::check_no_speculative_types() {
331 #ifdef ASSERT
332 uint max = size();
333 Unique_Node_List live_nodes;
334 Compile::current()->identify_useful_nodes(live_nodes);
335 Node *sentinel_node = sentinel();
336 for (uint i = 0; i < max; ++i) {
337 Node *n = at(i);
338 if (n != NULL &&
339 n != sentinel_node &&
340 n->is_Type() &&
341 live_nodes.member(n)) {
342 TypeNode* tn = n->as_Type();
343 const Type* t = tn->type();
344 const Type* t_no_spec = t->remove_speculative();
345 assert(t == t_no_spec, "dead node in hash table or missed node during speculative cleanup");
346 }
347 }
348 #endif
349 }
350
351 #ifndef PRODUCT
352 //------------------------------dump-------------------------------------------
353 // Dump statistics for the hash table
dump()354 void NodeHash::dump() {
355 _total_inserts += _inserts;
356 _total_insert_probes += _insert_probes;
357 if (PrintCompilation && PrintOptoStatistics && Verbose && (_inserts > 0)) {
358 if (WizardMode) {
359 for (uint i=0; i<_max; i++) {
360 if (_table[i])
361 tty->print("%d/%d/%d ",i,_table[i]->hash()&(_max-1),_table[i]->_idx);
362 }
363 }
364 tty->print("\nGVN Hash stats: %d grows to %d max_size\n", _grows, _max);
365 tty->print(" %d/%d (%8.1f%% full)\n", _inserts, _max, (double)_inserts/_max*100.0);
366 tty->print(" %dp/(%dh+%dm) (%8.2f probes/lookup)\n", _look_probes, _lookup_hits, _lookup_misses, (double)_look_probes/(_lookup_hits+_lookup_misses));
367 tty->print(" %dp/%di (%8.2f probes/insert)\n", _total_insert_probes, _total_inserts, (double)_total_insert_probes/_total_inserts);
368 // sentinels increase lookup cost, but not insert cost
369 assert((_lookup_misses+_lookup_hits)*4+100 >= _look_probes, "bad hash function");
370 assert( _inserts+(_inserts>>3) < _max, "table too full" );
371 assert( _inserts*3+100 >= _insert_probes, "bad hash function" );
372 }
373 }
374
find_index(uint idx)375 Node *NodeHash::find_index(uint idx) { // For debugging
376 // Find an entry by its index value
377 for( uint i = 0; i < _max; i++ ) {
378 Node *m = _table[i];
379 if( !m || m == _sentinel ) continue;
380 if( m->_idx == (uint)idx ) return m;
381 }
382 return NULL;
383 }
384 #endif
385
386 #ifdef ASSERT
~NodeHash()387 NodeHash::~NodeHash() {
388 // Unlock all nodes upon destruction of table.
389 if (_table != (Node**)badAddress) clear();
390 }
391
operator =(const NodeHash & nh)392 void NodeHash::operator=(const NodeHash& nh) {
393 // Unlock all nodes upon replacement of table.
394 if (&nh == this) return;
395 if (_table != (Node**)badAddress) clear();
396 memcpy((void*)this, (void*)&nh, sizeof(*this));
397 // Do not increment hash_lock counts again.
398 // Instead, be sure we never again use the source table.
399 ((NodeHash*)&nh)->_table = (Node**)badAddress;
400 }
401
402
403 #endif
404
405
406 //=============================================================================
407 //------------------------------PhaseRemoveUseless-----------------------------
408 // 1) Use a breadthfirst walk to collect useful nodes reachable from root.
PhaseRemoveUseless(PhaseGVN * gvn,Unique_Node_List * worklist,PhaseNumber phase_num)409 PhaseRemoveUseless::PhaseRemoveUseless(PhaseGVN* gvn, Unique_Node_List* worklist, PhaseNumber phase_num) : Phase(phase_num) {
410 // Implementation requires an edge from root to each SafePointNode
411 // at a backward branch. Inserted in add_safepoint().
412
413 // Identify nodes that are reachable from below, useful.
414 C->identify_useful_nodes(_useful);
415 // Update dead node list
416 C->update_dead_node_list(_useful);
417
418 // Remove all useless nodes from PhaseValues' recorded types
419 // Must be done before disconnecting nodes to preserve hash-table-invariant
420 gvn->remove_useless_nodes(_useful.member_set());
421
422 // Remove all useless nodes from future worklist
423 worklist->remove_useless_nodes(_useful.member_set());
424
425 // Disconnect 'useless' nodes that are adjacent to useful nodes
426 C->remove_useless_nodes(_useful);
427 }
428
429 //=============================================================================
430 //------------------------------PhaseRenumberLive------------------------------
431 // First, remove useless nodes (equivalent to identifying live nodes).
432 // Then, renumber live nodes.
433 //
434 // The set of live nodes is returned by PhaseRemoveUseless in the _useful structure.
435 // If the number of live nodes is 'x' (where 'x' == _useful.size()), then the
436 // PhaseRenumberLive updates the node ID of each node (the _idx field) with a unique
437 // value in the range [0, x).
438 //
439 // At the end of the PhaseRenumberLive phase, the compiler's count of unique nodes is
440 // updated to 'x' and the list of dead nodes is reset (as there are no dead nodes).
441 //
442 // The PhaseRenumberLive phase updates two data structures with the new node IDs.
443 // (1) The worklist is used by the PhaseIterGVN phase to identify nodes that must be
444 // processed. A new worklist (with the updated node IDs) is returned in 'new_worklist'.
445 // 'worklist' is cleared upon returning.
446 // (2) Type information (the field PhaseGVN::_types) maps type information to each
447 // node ID. The mapping is updated to use the new node IDs as well. Updated type
448 // information is returned in PhaseGVN::_types.
449 //
450 // The PhaseRenumberLive phase does not preserve the order of elements in the worklist.
451 //
452 // Other data structures used by the compiler are not updated. The hash table for value
453 // numbering (the field PhaseGVN::_table) is not updated because computing the hash
454 // values is not based on node IDs. The field PhaseGVN::_nodes is not updated either
455 // because it is empty wherever PhaseRenumberLive is used.
PhaseRenumberLive(PhaseGVN * gvn,Unique_Node_List * worklist,Unique_Node_List * new_worklist,PhaseNumber phase_num)456 PhaseRenumberLive::PhaseRenumberLive(PhaseGVN* gvn,
457 Unique_Node_List* worklist, Unique_Node_List* new_worklist,
458 PhaseNumber phase_num) :
459 PhaseRemoveUseless(gvn, worklist, Remove_Useless_And_Renumber_Live),
460 _new_type_array(C->comp_arena()),
461 _old2new_map(C->unique(), C->unique(), -1),
462 _is_pass_finished(false),
463 _live_node_count(C->live_nodes())
464 {
465 assert(RenumberLiveNodes, "RenumberLiveNodes must be set to true for node renumbering to take place");
466 assert(C->live_nodes() == _useful.size(), "the number of live nodes must match the number of useful nodes");
467 assert(gvn->nodes_size() == 0, "GVN must not contain any nodes at this point");
468 assert(_delayed.size() == 0, "should be empty");
469
470 uint worklist_size = worklist->size();
471
472 // Iterate over the set of live nodes.
473 for (uint current_idx = 0; current_idx < _useful.size(); current_idx++) {
474 Node* n = _useful.at(current_idx);
475
476 bool in_worklist = false;
477 if (worklist->member(n)) {
478 in_worklist = true;
479 }
480
481 const Type* type = gvn->type_or_null(n);
482 _new_type_array.map(current_idx, type);
483
484 assert(_old2new_map.at(n->_idx) == -1, "already seen");
485 _old2new_map.at_put(n->_idx, current_idx);
486
487 n->set_idx(current_idx); // Update node ID.
488
489 if (in_worklist) {
490 new_worklist->push(n);
491 }
492
493 if (update_embedded_ids(n) < 0) {
494 _delayed.push(n); // has embedded IDs; handle later
495 }
496 }
497
498 assert(worklist_size == new_worklist->size(), "the new worklist must have the same size as the original worklist");
499 assert(_live_node_count == _useful.size(), "all live nodes must be processed");
500
501 _is_pass_finished = true; // pass finished; safe to process delayed updates
502
503 while (_delayed.size() > 0) {
504 Node* n = _delayed.pop();
505 int no_of_updates = update_embedded_ids(n);
506 assert(no_of_updates > 0, "should be updated");
507 }
508
509 // Replace the compiler's type information with the updated type information.
510 gvn->replace_types(_new_type_array);
511
512 // Update the unique node count of the compilation to the number of currently live nodes.
513 C->set_unique(_live_node_count);
514
515 // Set the dead node count to 0 and reset dead node list.
516 C->reset_dead_node_list();
517
518 // Clear the original worklist
519 worklist->clear();
520 }
521
new_index(int old_idx)522 int PhaseRenumberLive::new_index(int old_idx) {
523 assert(_is_pass_finished, "not finished");
524 if (_old2new_map.at(old_idx) == -1) { // absent
525 // Allocate a placeholder to preserve uniqueness
526 _old2new_map.at_put(old_idx, _live_node_count);
527 _live_node_count++;
528 }
529 return _old2new_map.at(old_idx);
530 }
531
update_embedded_ids(Node * n)532 int PhaseRenumberLive::update_embedded_ids(Node* n) {
533 int no_of_updates = 0;
534 if (n->is_Phi()) {
535 PhiNode* phi = n->as_Phi();
536 if (phi->_inst_id != -1) {
537 if (!_is_pass_finished) {
538 return -1; // delay
539 }
540 int new_idx = new_index(phi->_inst_id);
541 assert(new_idx != -1, "");
542 phi->_inst_id = new_idx;
543 no_of_updates++;
544 }
545 if (phi->_inst_mem_id != -1) {
546 if (!_is_pass_finished) {
547 return -1; // delay
548 }
549 int new_idx = new_index(phi->_inst_mem_id);
550 assert(new_idx != -1, "");
551 phi->_inst_mem_id = new_idx;
552 no_of_updates++;
553 }
554 }
555
556 const Type* type = _new_type_array.fast_lookup(n->_idx);
557 if (type != NULL && type->isa_oopptr() && type->is_oopptr()->is_known_instance()) {
558 if (!_is_pass_finished) {
559 return -1; // delay
560 }
561 int old_idx = type->is_oopptr()->instance_id();
562 int new_idx = new_index(old_idx);
563 const Type* new_type = type->is_oopptr()->with_instance_id(new_idx);
564 _new_type_array.map(n->_idx, new_type);
565 no_of_updates++;
566 }
567
568 return no_of_updates;
569 }
570
571 //=============================================================================
572 //------------------------------PhaseTransform---------------------------------
PhaseTransform(PhaseNumber pnum)573 PhaseTransform::PhaseTransform( PhaseNumber pnum ) : Phase(pnum),
574 _arena(Thread::current()->resource_area()),
575 _nodes(_arena),
576 _types(_arena)
577 {
578 init_con_caches();
579 #ifndef PRODUCT
580 clear_progress();
581 clear_transforms();
582 set_allow_progress(true);
583 #endif
584 // Force allocation for currently existing nodes
585 _types.map(C->unique(), NULL);
586 }
587
588 //------------------------------PhaseTransform---------------------------------
PhaseTransform(Arena * arena,PhaseNumber pnum)589 PhaseTransform::PhaseTransform( Arena *arena, PhaseNumber pnum ) : Phase(pnum),
590 _arena(arena),
591 _nodes(arena),
592 _types(arena)
593 {
594 init_con_caches();
595 #ifndef PRODUCT
596 clear_progress();
597 clear_transforms();
598 set_allow_progress(true);
599 #endif
600 // Force allocation for currently existing nodes
601 _types.map(C->unique(), NULL);
602 }
603
604 //------------------------------PhaseTransform---------------------------------
605 // Initialize with previously generated type information
PhaseTransform(PhaseTransform * pt,PhaseNumber pnum)606 PhaseTransform::PhaseTransform( PhaseTransform *pt, PhaseNumber pnum ) : Phase(pnum),
607 _arena(pt->_arena),
608 _nodes(pt->_nodes),
609 _types(pt->_types)
610 {
611 init_con_caches();
612 #ifndef PRODUCT
613 clear_progress();
614 clear_transforms();
615 set_allow_progress(true);
616 #endif
617 }
618
init_con_caches()619 void PhaseTransform::init_con_caches() {
620 memset(_icons,0,sizeof(_icons));
621 memset(_lcons,0,sizeof(_lcons));
622 memset(_zcons,0,sizeof(_zcons));
623 }
624
625
626 //--------------------------------find_int_type--------------------------------
find_int_type(Node * n)627 const TypeInt* PhaseTransform::find_int_type(Node* n) {
628 if (n == NULL) return NULL;
629 // Call type_or_null(n) to determine node's type since we might be in
630 // parse phase and call n->Value() may return wrong type.
631 // (For example, a phi node at the beginning of loop parsing is not ready.)
632 const Type* t = type_or_null(n);
633 if (t == NULL) return NULL;
634 return t->isa_int();
635 }
636
637
638 //-------------------------------find_long_type--------------------------------
find_long_type(Node * n)639 const TypeLong* PhaseTransform::find_long_type(Node* n) {
640 if (n == NULL) return NULL;
641 // (See comment above on type_or_null.)
642 const Type* t = type_or_null(n);
643 if (t == NULL) return NULL;
644 return t->isa_long();
645 }
646
647
648 #ifndef PRODUCT
dump_old2new_map() const649 void PhaseTransform::dump_old2new_map() const {
650 _nodes.dump();
651 }
652
dump_new(uint nidx) const653 void PhaseTransform::dump_new( uint nidx ) const {
654 for( uint i=0; i<_nodes.Size(); i++ )
655 if( _nodes[i] && _nodes[i]->_idx == nidx ) {
656 _nodes[i]->dump();
657 tty->cr();
658 tty->print_cr("Old index= %d",i);
659 return;
660 }
661 tty->print_cr("Node %d not found in the new indices", nidx);
662 }
663
664 //------------------------------dump_types-------------------------------------
dump_types() const665 void PhaseTransform::dump_types( ) const {
666 _types.dump();
667 }
668
669 //------------------------------dump_nodes_and_types---------------------------
dump_nodes_and_types(const Node * root,uint depth,bool only_ctrl)670 void PhaseTransform::dump_nodes_and_types(const Node* root, uint depth, bool only_ctrl) {
671 VectorSet visited;
672 dump_nodes_and_types_recur(root, depth, only_ctrl, visited);
673 }
674
675 //------------------------------dump_nodes_and_types_recur---------------------
dump_nodes_and_types_recur(const Node * n,uint depth,bool only_ctrl,VectorSet & visited)676 void PhaseTransform::dump_nodes_and_types_recur( const Node *n, uint depth, bool only_ctrl, VectorSet &visited) {
677 if( !n ) return;
678 if( depth == 0 ) return;
679 if( visited.test_set(n->_idx) ) return;
680 for( uint i=0; i<n->len(); i++ ) {
681 if( only_ctrl && !(n->is_Region()) && i != TypeFunc::Control ) continue;
682 dump_nodes_and_types_recur( n->in(i), depth-1, only_ctrl, visited );
683 }
684 n->dump();
685 if (type_or_null(n) != NULL) {
686 tty->print(" "); type(n)->dump(); tty->cr();
687 }
688 }
689
690 #endif
691
692
693 //=============================================================================
694 //------------------------------PhaseValues------------------------------------
695 // Set minimum table size to "255"
PhaseValues(Arena * arena,uint est_max_size)696 PhaseValues::PhaseValues( Arena *arena, uint est_max_size )
697 : PhaseTransform(arena, GVN), _table(arena, est_max_size), _iterGVN(false) {
698 NOT_PRODUCT( clear_new_values(); )
699 }
700
701 //------------------------------PhaseValues------------------------------------
702 // Set minimum table size to "255"
PhaseValues(PhaseValues * ptv)703 PhaseValues::PhaseValues(PhaseValues* ptv)
704 : PhaseTransform(ptv, GVN), _table(&ptv->_table), _iterGVN(false) {
705 NOT_PRODUCT( clear_new_values(); )
706 }
707
708 //------------------------------~PhaseValues-----------------------------------
709 #ifndef PRODUCT
~PhaseValues()710 PhaseValues::~PhaseValues() {
711 _table.dump();
712
713 // Statistics for value progress and efficiency
714 if( PrintCompilation && Verbose && WizardMode ) {
715 tty->print("\n%sValues: %d nodes ---> %d/%d (%d)",
716 is_IterGVN() ? "Iter" : " ", C->unique(), made_progress(), made_transforms(), made_new_values());
717 if( made_transforms() != 0 ) {
718 tty->print_cr(" ratio %f", made_progress()/(float)made_transforms() );
719 } else {
720 tty->cr();
721 }
722 }
723 }
724 #endif
725
726 //------------------------------makecon----------------------------------------
makecon(const Type * t)727 ConNode* PhaseTransform::makecon(const Type *t) {
728 assert(t->singleton(), "must be a constant");
729 assert(!t->empty() || t == Type::TOP, "must not be vacuous range");
730 switch (t->base()) { // fast paths
731 case Type::Half:
732 case Type::Top: return (ConNode*) C->top();
733 case Type::Int: return intcon( t->is_int()->get_con() );
734 case Type::Long: return longcon( t->is_long()->get_con() );
735 default: break;
736 }
737 if (t->is_zero_type())
738 return zerocon(t->basic_type());
739 return uncached_makecon(t);
740 }
741
742 //--------------------------uncached_makecon-----------------------------------
743 // Make an idealized constant - one of ConINode, ConPNode, etc.
uncached_makecon(const Type * t)744 ConNode* PhaseValues::uncached_makecon(const Type *t) {
745 assert(t->singleton(), "must be a constant");
746 ConNode* x = ConNode::make(t);
747 ConNode* k = (ConNode*)hash_find_insert(x); // Value numbering
748 if (k == NULL) {
749 set_type(x, t); // Missed, provide type mapping
750 GrowableArray<Node_Notes*>* nna = C->node_note_array();
751 if (nna != NULL) {
752 Node_Notes* loc = C->locate_node_notes(nna, x->_idx, true);
753 loc->clear(); // do not put debug info on constants
754 }
755 } else {
756 x->destruct(this); // Hit, destroy duplicate constant
757 x = k; // use existing constant
758 }
759 return x;
760 }
761
762 //------------------------------intcon-----------------------------------------
763 // Fast integer constant. Same as "transform(new ConINode(TypeInt::make(i)))"
intcon(jint i)764 ConINode* PhaseTransform::intcon(jint i) {
765 // Small integer? Check cache! Check that cached node is not dead
766 if (i >= _icon_min && i <= _icon_max) {
767 ConINode* icon = _icons[i-_icon_min];
768 if (icon != NULL && icon->in(TypeFunc::Control) != NULL)
769 return icon;
770 }
771 ConINode* icon = (ConINode*) uncached_makecon(TypeInt::make(i));
772 assert(icon->is_Con(), "");
773 if (i >= _icon_min && i <= _icon_max)
774 _icons[i-_icon_min] = icon; // Cache small integers
775 return icon;
776 }
777
778 //------------------------------longcon----------------------------------------
779 // Fast long constant.
longcon(jlong l)780 ConLNode* PhaseTransform::longcon(jlong l) {
781 // Small integer? Check cache! Check that cached node is not dead
782 if (l >= _lcon_min && l <= _lcon_max) {
783 ConLNode* lcon = _lcons[l-_lcon_min];
784 if (lcon != NULL && lcon->in(TypeFunc::Control) != NULL)
785 return lcon;
786 }
787 ConLNode* lcon = (ConLNode*) uncached_makecon(TypeLong::make(l));
788 assert(lcon->is_Con(), "");
789 if (l >= _lcon_min && l <= _lcon_max)
790 _lcons[l-_lcon_min] = lcon; // Cache small integers
791 return lcon;
792 }
integercon(jlong l,BasicType bt)793 ConNode* PhaseTransform::integercon(jlong l, BasicType bt) {
794 if (bt == T_INT) {
795 jint int_con = (jint)l;
796 assert(((long)int_con) == l, "not an int");
797 return intcon(int_con);
798 }
799 assert(bt == T_LONG, "not an integer");
800 return longcon(l);
801 }
802
803
804 //------------------------------zerocon-----------------------------------------
805 // Fast zero or null constant. Same as "transform(ConNode::make(Type::get_zero_type(bt)))"
zerocon(BasicType bt)806 ConNode* PhaseTransform::zerocon(BasicType bt) {
807 assert((uint)bt <= _zcon_max, "domain check");
808 ConNode* zcon = _zcons[bt];
809 if (zcon != NULL && zcon->in(TypeFunc::Control) != NULL)
810 return zcon;
811 zcon = (ConNode*) uncached_makecon(Type::get_zero_type(bt));
812 _zcons[bt] = zcon;
813 return zcon;
814 }
815
816
817
818 //=============================================================================
apply_ideal(Node * k,bool can_reshape)819 Node* PhaseGVN::apply_ideal(Node* k, bool can_reshape) {
820 Node* i = BarrierSet::barrier_set()->barrier_set_c2()->ideal_node(this, k, can_reshape);
821 if (i == NULL) {
822 i = k->Ideal(this, can_reshape);
823 }
824 return i;
825 }
826
827 //------------------------------transform--------------------------------------
828 // Return a node which computes the same function as this node, but in a
829 // faster or cheaper fashion.
transform(Node * n)830 Node *PhaseGVN::transform( Node *n ) {
831 return transform_no_reclaim(n);
832 }
833
834 //------------------------------transform--------------------------------------
835 // Return a node which computes the same function as this node, but
836 // in a faster or cheaper fashion.
transform_no_reclaim(Node * n)837 Node *PhaseGVN::transform_no_reclaim(Node *n) {
838 NOT_PRODUCT( set_transforms(); )
839
840 // Apply the Ideal call in a loop until it no longer applies
841 Node* k = n;
842 Node* i = apply_ideal(k, /*can_reshape=*/false);
843 NOT_PRODUCT(uint loop_count = 1;)
844 while (i != NULL) {
845 assert(i->_idx >= k->_idx, "Idealize should return new nodes, use Identity to return old nodes" );
846 k = i;
847 #ifdef ASSERT
848 if (loop_count >= K + C->live_nodes()) {
849 dump_infinite_loop_info(i, "PhaseGVN::transform_no_reclaim");
850 }
851 #endif
852 i = apply_ideal(k, /*can_reshape=*/false);
853 NOT_PRODUCT(loop_count++;)
854 }
855 NOT_PRODUCT(if (loop_count != 0) { set_progress(); })
856
857 // If brand new node, make space in type array.
858 ensure_type_or_null(k);
859
860 // Since I just called 'Value' to compute the set of run-time values
861 // for this Node, and 'Value' is non-local (and therefore expensive) I'll
862 // cache Value. Later requests for the local phase->type of this Node can
863 // use the cached Value instead of suffering with 'bottom_type'.
864 const Type* t = k->Value(this); // Get runtime Value set
865 assert(t != NULL, "value sanity");
866 if (type_or_null(k) != t) {
867 #ifndef PRODUCT
868 // Do not count initial visit to node as a transformation
869 if (type_or_null(k) == NULL) {
870 inc_new_values();
871 set_progress();
872 }
873 #endif
874 set_type(k, t);
875 // If k is a TypeNode, capture any more-precise type permanently into Node
876 k->raise_bottom_type(t);
877 }
878
879 if (t->singleton() && !k->is_Con()) {
880 NOT_PRODUCT(set_progress();)
881 return makecon(t); // Turn into a constant
882 }
883
884 // Now check for Identities
885 i = k->Identity(this); // Look for a nearby replacement
886 if (i != k) { // Found? Return replacement!
887 NOT_PRODUCT(set_progress();)
888 return i;
889 }
890
891 // Global Value Numbering
892 i = hash_find_insert(k); // Insert if new
893 if (i && (i != k)) {
894 // Return the pre-existing node
895 NOT_PRODUCT(set_progress();)
896 return i;
897 }
898
899 // Return Idealized original
900 return k;
901 }
902
is_dominator_helper(Node * d,Node * n,bool linear_only)903 bool PhaseGVN::is_dominator_helper(Node *d, Node *n, bool linear_only) {
904 if (d->is_top() || (d->is_Proj() && d->in(0)->is_top())) {
905 return false;
906 }
907 if (n->is_top() || (n->is_Proj() && n->in(0)->is_top())) {
908 return false;
909 }
910 assert(d->is_CFG() && n->is_CFG(), "must have CFG nodes");
911 int i = 0;
912 while (d != n) {
913 n = IfNode::up_one_dom(n, linear_only);
914 i++;
915 if (n == NULL || i >= 100) {
916 return false;
917 }
918 }
919 return true;
920 }
921
922 #ifdef ASSERT
923 //------------------------------dead_loop_check--------------------------------
924 // Check for a simple dead loop when a data node references itself directly
925 // or through an other data node excluding cons and phis.
dead_loop_check(Node * n)926 void PhaseGVN::dead_loop_check( Node *n ) {
927 // Phi may reference itself in a loop
928 if (n != NULL && !n->is_dead_loop_safe() && !n->is_CFG()) {
929 // Do 2 levels check and only data inputs.
930 bool no_dead_loop = true;
931 uint cnt = n->req();
932 for (uint i = 1; i < cnt && no_dead_loop; i++) {
933 Node *in = n->in(i);
934 if (in == n) {
935 no_dead_loop = false;
936 } else if (in != NULL && !in->is_dead_loop_safe()) {
937 uint icnt = in->req();
938 for (uint j = 1; j < icnt && no_dead_loop; j++) {
939 if (in->in(j) == n || in->in(j) == in)
940 no_dead_loop = false;
941 }
942 }
943 }
944 if (!no_dead_loop) n->dump(3);
945 assert(no_dead_loop, "dead loop detected");
946 }
947 }
948
949
950 /**
951 * Dumps information that can help to debug the problem. A debug
952 * build fails with an assert.
953 */
dump_infinite_loop_info(Node * n,const char * where)954 void PhaseGVN::dump_infinite_loop_info(Node* n, const char* where) {
955 n->dump(4);
956 assert(false, "infinite loop in %s", where);
957 }
958 #endif
959
960 //=============================================================================
961 //------------------------------PhaseIterGVN-----------------------------------
962 // Initialize with previous PhaseIterGVN info; used by PhaseCCP
PhaseIterGVN(PhaseIterGVN * igvn)963 PhaseIterGVN::PhaseIterGVN(PhaseIterGVN* igvn) : PhaseGVN(igvn),
964 _delay_transform(igvn->_delay_transform),
965 _stack(igvn->_stack ),
966 _worklist(igvn->_worklist)
967 {
968 _iterGVN = true;
969 }
970
971 //------------------------------PhaseIterGVN-----------------------------------
972 // Initialize with previous PhaseGVN info from Parser
PhaseIterGVN(PhaseGVN * gvn)973 PhaseIterGVN::PhaseIterGVN(PhaseGVN* gvn) : PhaseGVN(gvn),
974 _delay_transform(false),
975 // TODO: Before incremental inlining it was allocated only once and it was fine. Now that
976 // the constructor is used in incremental inlining, this consumes too much memory:
977 // _stack(C->live_nodes() >> 1),
978 // So, as a band-aid, we replace this by:
979 _stack(C->comp_arena(), 32),
980 _worklist(*C->for_igvn())
981 {
982 _iterGVN = true;
983 uint max;
984
985 // Dead nodes in the hash table inherited from GVN were not treated as
986 // roots during def-use info creation; hence they represent an invisible
987 // use. Clear them out.
988 max = _table.size();
989 for( uint i = 0; i < max; ++i ) {
990 Node *n = _table.at(i);
991 if(n != NULL && n != _table.sentinel() && n->outcnt() == 0) {
992 if( n->is_top() ) continue;
993 // If remove_useless_nodes() has run, we expect no such nodes left.
994 assert(false, "remove_useless_nodes missed this node");
995 hash_delete(n);
996 }
997 }
998
999 // Any Phis or Regions on the worklist probably had uses that could not
1000 // make more progress because the uses were made while the Phis and Regions
1001 // were in half-built states. Put all uses of Phis and Regions on worklist.
1002 max = _worklist.size();
1003 for( uint j = 0; j < max; j++ ) {
1004 Node *n = _worklist.at(j);
1005 uint uop = n->Opcode();
1006 if( uop == Op_Phi || uop == Op_Region ||
1007 n->is_Type() ||
1008 n->is_Mem() )
1009 add_users_to_worklist(n);
1010 }
1011 }
1012
shuffle_worklist()1013 void PhaseIterGVN::shuffle_worklist() {
1014 if (_worklist.size() < 2) return;
1015 for (uint i = _worklist.size() - 1; i >= 1; i--) {
1016 uint j = C->random() % (i + 1);
1017 swap(_worklist.adr()[i], _worklist.adr()[j]);
1018 }
1019 }
1020
1021 #ifndef PRODUCT
verify_step(Node * n)1022 void PhaseIterGVN::verify_step(Node* n) {
1023 if (VerifyIterativeGVN) {
1024 ResourceMark rm;
1025 VectorSet visited;
1026 Node_List worklist;
1027
1028 _verify_window[_verify_counter % _verify_window_size] = n;
1029 ++_verify_counter;
1030 if (C->unique() < 1000 || 0 == _verify_counter % (C->unique() < 10000 ? 10 : 100)) {
1031 ++_verify_full_passes;
1032 worklist.push(C->root());
1033 Node::verify(-1, visited, worklist);
1034 return;
1035 }
1036 for (int i = 0; i < _verify_window_size; i++) {
1037 Node* n = _verify_window[i];
1038 if (n == NULL) {
1039 continue;
1040 }
1041 if (n->in(0) == NodeSentinel) { // xform_idom
1042 _verify_window[i] = n->in(1);
1043 --i;
1044 continue;
1045 }
1046 // Typical fanout is 1-2, so this call visits about 6 nodes.
1047 if (!visited.test_set(n->_idx)) {
1048 worklist.push(n);
1049 }
1050 }
1051 Node::verify(4, visited, worklist);
1052 }
1053 }
1054
trace_PhaseIterGVN(Node * n,Node * nn,const Type * oldtype)1055 void PhaseIterGVN::trace_PhaseIterGVN(Node* n, Node* nn, const Type* oldtype) {
1056 if (TraceIterativeGVN) {
1057 uint wlsize = _worklist.size();
1058 const Type* newtype = type_or_null(n);
1059 if (nn != n) {
1060 // print old node
1061 tty->print("< ");
1062 if (oldtype != newtype && oldtype != NULL) {
1063 oldtype->dump();
1064 }
1065 do { tty->print("\t"); } while (tty->position() < 16);
1066 tty->print("<");
1067 n->dump();
1068 }
1069 if (oldtype != newtype || nn != n) {
1070 // print new node and/or new type
1071 if (oldtype == NULL) {
1072 tty->print("* ");
1073 } else if (nn != n) {
1074 tty->print("> ");
1075 } else {
1076 tty->print("= ");
1077 }
1078 if (newtype == NULL) {
1079 tty->print("null");
1080 } else {
1081 newtype->dump();
1082 }
1083 do { tty->print("\t"); } while (tty->position() < 16);
1084 nn->dump();
1085 }
1086 if (Verbose && wlsize < _worklist.size()) {
1087 tty->print(" Push {");
1088 while (wlsize != _worklist.size()) {
1089 Node* pushed = _worklist.at(wlsize++);
1090 tty->print(" %d", pushed->_idx);
1091 }
1092 tty->print_cr(" }");
1093 }
1094 if (nn != n) {
1095 // ignore n, it might be subsumed
1096 verify_step((Node*) NULL);
1097 }
1098 }
1099 }
1100
init_verifyPhaseIterGVN()1101 void PhaseIterGVN::init_verifyPhaseIterGVN() {
1102 _verify_counter = 0;
1103 _verify_full_passes = 0;
1104 for (int i = 0; i < _verify_window_size; i++) {
1105 _verify_window[i] = NULL;
1106 }
1107 #ifdef ASSERT
1108 // Verify that all modified nodes are on _worklist
1109 Unique_Node_List* modified_list = C->modified_nodes();
1110 while (modified_list != NULL && modified_list->size()) {
1111 Node* n = modified_list->pop();
1112 if (!n->is_Con() && !_worklist.member(n)) {
1113 n->dump();
1114 fatal("modified node is not on IGVN._worklist");
1115 }
1116 }
1117 #endif
1118 }
1119
verify_PhaseIterGVN()1120 void PhaseIterGVN::verify_PhaseIterGVN() {
1121 #ifdef ASSERT
1122 // Verify nodes with changed inputs.
1123 Unique_Node_List* modified_list = C->modified_nodes();
1124 while (modified_list != NULL && modified_list->size()) {
1125 Node* n = modified_list->pop();
1126 if (!n->is_Con()) { // skip Con nodes
1127 n->dump();
1128 fatal("modified node was not processed by IGVN.transform_old()");
1129 }
1130 }
1131 #endif
1132
1133 C->verify_graph_edges();
1134 if (VerifyIterativeGVN && PrintOpto) {
1135 if (_verify_counter == _verify_full_passes) {
1136 tty->print_cr("VerifyIterativeGVN: %d transforms and verify passes",
1137 (int) _verify_full_passes);
1138 } else {
1139 tty->print_cr("VerifyIterativeGVN: %d transforms, %d full verify passes",
1140 (int) _verify_counter, (int) _verify_full_passes);
1141 }
1142 }
1143
1144 #ifdef ASSERT
1145 if (modified_list != NULL) {
1146 while (modified_list->size() > 0) {
1147 Node* n = modified_list->pop();
1148 n->dump();
1149 assert(false, "VerifyIterativeGVN: new modified node was added");
1150 }
1151 }
1152 #endif
1153 }
1154 #endif /* PRODUCT */
1155
1156 #ifdef ASSERT
1157 /**
1158 * Dumps information that can help to debug the problem. A debug
1159 * build fails with an assert.
1160 */
dump_infinite_loop_info(Node * n,const char * where)1161 void PhaseIterGVN::dump_infinite_loop_info(Node* n, const char* where) {
1162 n->dump(4);
1163 _worklist.dump();
1164 assert(false, "infinite loop in %s", where);
1165 }
1166
1167 /**
1168 * Prints out information about IGVN if the 'verbose' option is used.
1169 */
trace_PhaseIterGVN_verbose(Node * n,int num_processed)1170 void PhaseIterGVN::trace_PhaseIterGVN_verbose(Node* n, int num_processed) {
1171 if (TraceIterativeGVN && Verbose) {
1172 tty->print(" Pop ");
1173 n->dump();
1174 if ((num_processed % 100) == 0) {
1175 _worklist.print_set();
1176 }
1177 }
1178 }
1179 #endif /* ASSERT */
1180
optimize()1181 void PhaseIterGVN::optimize() {
1182 DEBUG_ONLY(uint num_processed = 0;)
1183 NOT_PRODUCT(init_verifyPhaseIterGVN();)
1184 if (StressIGVN) {
1185 shuffle_worklist();
1186 }
1187
1188 uint loop_count = 0;
1189 // Pull from worklist and transform the node. If the node has changed,
1190 // update edge info and put uses on worklist.
1191 while(_worklist.size()) {
1192 if (C->check_node_count(NodeLimitFudgeFactor * 2, "Out of nodes")) {
1193 return;
1194 }
1195 Node* n = _worklist.pop();
1196 if (loop_count >= K * C->live_nodes()) {
1197 DEBUG_ONLY(dump_infinite_loop_info(n, "PhaseIterGVN::optimize");)
1198 C->record_method_not_compilable("infinite loop in PhaseIterGVN::optimize");
1199 return;
1200 }
1201 DEBUG_ONLY(trace_PhaseIterGVN_verbose(n, num_processed++);)
1202 if (n->outcnt() != 0) {
1203 NOT_PRODUCT(const Type* oldtype = type_or_null(n));
1204 // Do the transformation
1205 Node* nn = transform_old(n);
1206 NOT_PRODUCT(trace_PhaseIterGVN(n, nn, oldtype);)
1207 } else if (!n->is_top()) {
1208 remove_dead_node(n);
1209 }
1210 loop_count++;
1211 }
1212 NOT_PRODUCT(verify_PhaseIterGVN();)
1213 }
1214
1215
1216 /**
1217 * Register a new node with the optimizer. Update the types array, the def-use
1218 * info. Put on worklist.
1219 */
register_new_node_with_optimizer(Node * n,Node * orig)1220 Node* PhaseIterGVN::register_new_node_with_optimizer(Node* n, Node* orig) {
1221 set_type_bottom(n);
1222 _worklist.push(n);
1223 if (orig != NULL) C->copy_node_notes_to(n, orig);
1224 return n;
1225 }
1226
1227 //------------------------------transform--------------------------------------
1228 // Non-recursive: idealize Node 'n' with respect to its inputs and its value
transform(Node * n)1229 Node *PhaseIterGVN::transform( Node *n ) {
1230 if (_delay_transform) {
1231 // Register the node but don't optimize for now
1232 register_new_node_with_optimizer(n);
1233 return n;
1234 }
1235
1236 // If brand new node, make space in type array, and give it a type.
1237 ensure_type_or_null(n);
1238 if (type_or_null(n) == NULL) {
1239 set_type_bottom(n);
1240 }
1241
1242 return transform_old(n);
1243 }
1244
transform_old(Node * n)1245 Node *PhaseIterGVN::transform_old(Node* n) {
1246 NOT_PRODUCT(set_transforms());
1247 // Remove 'n' from hash table in case it gets modified
1248 _table.hash_delete(n);
1249 if (VerifyIterativeGVN) {
1250 assert(!_table.find_index(n->_idx), "found duplicate entry in table");
1251 }
1252
1253 // Apply the Ideal call in a loop until it no longer applies
1254 Node* k = n;
1255 DEBUG_ONLY(dead_loop_check(k);)
1256 DEBUG_ONLY(bool is_new = (k->outcnt() == 0);)
1257 C->remove_modified_node(k);
1258 Node* i = apply_ideal(k, /*can_reshape=*/true);
1259 assert(i != k || is_new || i->outcnt() > 0, "don't return dead nodes");
1260 #ifndef PRODUCT
1261 verify_step(k);
1262 #endif
1263
1264 DEBUG_ONLY(uint loop_count = 1;)
1265 while (i != NULL) {
1266 #ifdef ASSERT
1267 if (loop_count >= K + C->live_nodes()) {
1268 dump_infinite_loop_info(i, "PhaseIterGVN::transform_old");
1269 }
1270 #endif
1271 assert((i->_idx >= k->_idx) || i->is_top(), "Idealize should return new nodes, use Identity to return old nodes");
1272 // Made a change; put users of original Node on worklist
1273 add_users_to_worklist(k);
1274 // Replacing root of transform tree?
1275 if (k != i) {
1276 // Make users of old Node now use new.
1277 subsume_node(k, i);
1278 k = i;
1279 }
1280 DEBUG_ONLY(dead_loop_check(k);)
1281 // Try idealizing again
1282 DEBUG_ONLY(is_new = (k->outcnt() == 0);)
1283 C->remove_modified_node(k);
1284 i = apply_ideal(k, /*can_reshape=*/true);
1285 assert(i != k || is_new || (i->outcnt() > 0), "don't return dead nodes");
1286 #ifndef PRODUCT
1287 verify_step(k);
1288 #endif
1289 DEBUG_ONLY(loop_count++;)
1290 }
1291
1292 // If brand new node, make space in type array.
1293 ensure_type_or_null(k);
1294
1295 // See what kind of values 'k' takes on at runtime
1296 const Type* t = k->Value(this);
1297 assert(t != NULL, "value sanity");
1298
1299 // Since I just called 'Value' to compute the set of run-time values
1300 // for this Node, and 'Value' is non-local (and therefore expensive) I'll
1301 // cache Value. Later requests for the local phase->type of this Node can
1302 // use the cached Value instead of suffering with 'bottom_type'.
1303 if (type_or_null(k) != t) {
1304 #ifndef PRODUCT
1305 inc_new_values();
1306 set_progress();
1307 #endif
1308 set_type(k, t);
1309 // If k is a TypeNode, capture any more-precise type permanently into Node
1310 k->raise_bottom_type(t);
1311 // Move users of node to worklist
1312 add_users_to_worklist(k);
1313 }
1314 // If 'k' computes a constant, replace it with a constant
1315 if (t->singleton() && !k->is_Con()) {
1316 NOT_PRODUCT(set_progress();)
1317 Node* con = makecon(t); // Make a constant
1318 add_users_to_worklist(k);
1319 subsume_node(k, con); // Everybody using k now uses con
1320 return con;
1321 }
1322
1323 // Now check for Identities
1324 i = k->Identity(this); // Look for a nearby replacement
1325 if (i != k) { // Found? Return replacement!
1326 NOT_PRODUCT(set_progress();)
1327 add_users_to_worklist(k);
1328 subsume_node(k, i); // Everybody using k now uses i
1329 return i;
1330 }
1331
1332 // Global Value Numbering
1333 i = hash_find_insert(k); // Check for pre-existing node
1334 if (i && (i != k)) {
1335 // Return the pre-existing node if it isn't dead
1336 NOT_PRODUCT(set_progress();)
1337 add_users_to_worklist(k);
1338 subsume_node(k, i); // Everybody using k now uses i
1339 return i;
1340 }
1341
1342 // Return Idealized original
1343 return k;
1344 }
1345
1346 //---------------------------------saturate------------------------------------
saturate(const Type * new_type,const Type * old_type,const Type * limit_type) const1347 const Type* PhaseIterGVN::saturate(const Type* new_type, const Type* old_type,
1348 const Type* limit_type) const {
1349 return new_type->narrow(old_type);
1350 }
1351
1352 //------------------------------remove_globally_dead_node----------------------
1353 // Kill a globally dead Node. All uses are also globally dead and are
1354 // aggressively trimmed.
remove_globally_dead_node(Node * dead)1355 void PhaseIterGVN::remove_globally_dead_node( Node *dead ) {
1356 enum DeleteProgress {
1357 PROCESS_INPUTS,
1358 PROCESS_OUTPUTS
1359 };
1360 assert(_stack.is_empty(), "not empty");
1361 _stack.push(dead, PROCESS_INPUTS);
1362
1363 while (_stack.is_nonempty()) {
1364 dead = _stack.node();
1365 if (dead->Opcode() == Op_SafePoint) {
1366 dead->as_SafePoint()->disconnect_from_root(this);
1367 }
1368 uint progress_state = _stack.index();
1369 assert(dead != C->root(), "killing root, eh?");
1370 assert(!dead->is_top(), "add check for top when pushing");
1371 NOT_PRODUCT( set_progress(); )
1372 if (progress_state == PROCESS_INPUTS) {
1373 // After following inputs, continue to outputs
1374 _stack.set_index(PROCESS_OUTPUTS);
1375 if (!dead->is_Con()) { // Don't kill cons but uses
1376 bool recurse = false;
1377 // Remove from hash table
1378 _table.hash_delete( dead );
1379 // Smash all inputs to 'dead', isolating him completely
1380 for (uint i = 0; i < dead->req(); i++) {
1381 Node *in = dead->in(i);
1382 if (in != NULL && in != C->top()) { // Points to something?
1383 int nrep = dead->replace_edge(in, NULL, this); // Kill edges
1384 assert((nrep > 0), "sanity");
1385 if (in->outcnt() == 0) { // Made input go dead?
1386 _stack.push(in, PROCESS_INPUTS); // Recursively remove
1387 recurse = true;
1388 } else if (in->outcnt() == 1 &&
1389 in->has_special_unique_user()) {
1390 _worklist.push(in->unique_out());
1391 } else if (in->outcnt() <= 2 && dead->is_Phi()) {
1392 if (in->Opcode() == Op_Region) {
1393 _worklist.push(in);
1394 } else if (in->is_Store()) {
1395 DUIterator_Fast imax, i = in->fast_outs(imax);
1396 _worklist.push(in->fast_out(i));
1397 i++;
1398 if (in->outcnt() == 2) {
1399 _worklist.push(in->fast_out(i));
1400 i++;
1401 }
1402 assert(!(i < imax), "sanity");
1403 }
1404 } else {
1405 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(this, in);
1406 }
1407 if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
1408 in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
1409 // A Load that directly follows an InitializeNode is
1410 // going away. The Stores that follow are candidates
1411 // again to be captured by the InitializeNode.
1412 for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
1413 Node *n = in->fast_out(j);
1414 if (n->is_Store()) {
1415 _worklist.push(n);
1416 }
1417 }
1418 }
1419 } // if (in != NULL && in != C->top())
1420 } // for (uint i = 0; i < dead->req(); i++)
1421 if (recurse) {
1422 continue;
1423 }
1424 } // if (!dead->is_Con())
1425 } // if (progress_state == PROCESS_INPUTS)
1426
1427 // Aggressively kill globally dead uses
1428 // (Rather than pushing all the outs at once, we push one at a time,
1429 // plus the parent to resume later, because of the indefinite number
1430 // of edge deletions per loop trip.)
1431 if (dead->outcnt() > 0) {
1432 // Recursively remove output edges
1433 _stack.push(dead->raw_out(0), PROCESS_INPUTS);
1434 } else {
1435 // Finished disconnecting all input and output edges.
1436 _stack.pop();
1437 // Remove dead node from iterative worklist
1438 _worklist.remove(dead);
1439 C->remove_useless_node(dead);
1440 }
1441 } // while (_stack.is_nonempty())
1442 }
1443
1444 //------------------------------subsume_node-----------------------------------
1445 // Remove users from node 'old' and add them to node 'nn'.
subsume_node(Node * old,Node * nn)1446 void PhaseIterGVN::subsume_node( Node *old, Node *nn ) {
1447 if (old->Opcode() == Op_SafePoint) {
1448 old->as_SafePoint()->disconnect_from_root(this);
1449 }
1450 assert( old != hash_find(old), "should already been removed" );
1451 assert( old != C->top(), "cannot subsume top node");
1452 // Copy debug or profile information to the new version:
1453 C->copy_node_notes_to(nn, old);
1454 // Move users of node 'old' to node 'nn'
1455 for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
1456 Node* use = old->last_out(i); // for each use...
1457 // use might need re-hashing (but it won't if it's a new node)
1458 rehash_node_delayed(use);
1459 // Update use-def info as well
1460 // We remove all occurrences of old within use->in,
1461 // so as to avoid rehashing any node more than once.
1462 // The hash table probe swamps any outer loop overhead.
1463 uint num_edges = 0;
1464 for (uint jmax = use->len(), j = 0; j < jmax; j++) {
1465 if (use->in(j) == old) {
1466 use->set_req(j, nn);
1467 ++num_edges;
1468 }
1469 }
1470 i -= num_edges; // we deleted 1 or more copies of this edge
1471 }
1472
1473 // Search for instance field data PhiNodes in the same region pointing to the old
1474 // memory PhiNode and update their instance memory ids to point to the new node.
1475 if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
1476 Node* region = old->in(0);
1477 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
1478 PhiNode* phi = region->fast_out(i)->isa_Phi();
1479 if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
1480 phi->set_inst_mem_id((int)nn->_idx);
1481 }
1482 }
1483 }
1484
1485 // Smash all inputs to 'old', isolating him completely
1486 Node *temp = new Node(1);
1487 temp->init_req(0,nn); // Add a use to nn to prevent him from dying
1488 remove_dead_node( old );
1489 temp->del_req(0); // Yank bogus edge
1490 if (nn != NULL && nn->outcnt() == 0) {
1491 _worklist.push(nn);
1492 }
1493 #ifndef PRODUCT
1494 if( VerifyIterativeGVN ) {
1495 for ( int i = 0; i < _verify_window_size; i++ ) {
1496 if ( _verify_window[i] == old )
1497 _verify_window[i] = nn;
1498 }
1499 }
1500 #endif
1501 temp->destruct(this); // reuse the _idx of this little guy
1502 }
1503
1504 //------------------------------add_users_to_worklist--------------------------
add_users_to_worklist0(Node * n)1505 void PhaseIterGVN::add_users_to_worklist0( Node *n ) {
1506 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1507 _worklist.push(n->fast_out(i)); // Push on worklist
1508 }
1509 }
1510
1511 // Return counted loop Phi if as a counted loop exit condition, cmp
1512 // compares the the induction variable with n
countedloop_phi_from_cmp(CmpINode * cmp,Node * n)1513 static PhiNode* countedloop_phi_from_cmp(CmpINode* cmp, Node* n) {
1514 for (DUIterator_Fast imax, i = cmp->fast_outs(imax); i < imax; i++) {
1515 Node* bol = cmp->fast_out(i);
1516 for (DUIterator_Fast i2max, i2 = bol->fast_outs(i2max); i2 < i2max; i2++) {
1517 Node* iff = bol->fast_out(i2);
1518 if (iff->is_CountedLoopEnd()) {
1519 CountedLoopEndNode* cle = iff->as_CountedLoopEnd();
1520 if (cle->limit() == n) {
1521 PhiNode* phi = cle->phi();
1522 if (phi != NULL) {
1523 return phi;
1524 }
1525 }
1526 }
1527 }
1528 }
1529 return NULL;
1530 }
1531
add_users_to_worklist(Node * n)1532 void PhaseIterGVN::add_users_to_worklist( Node *n ) {
1533 add_users_to_worklist0(n);
1534
1535 // Move users of node to worklist
1536 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1537 Node* use = n->fast_out(i); // Get use
1538
1539 if( use->is_Multi() || // Multi-definer? Push projs on worklist
1540 use->is_Store() ) // Enable store/load same address
1541 add_users_to_worklist0(use);
1542
1543 // If we changed the receiver type to a call, we need to revisit
1544 // the Catch following the call. It's looking for a non-NULL
1545 // receiver to know when to enable the regular fall-through path
1546 // in addition to the NullPtrException path.
1547 if (use->is_CallDynamicJava() && n == use->in(TypeFunc::Parms)) {
1548 Node* p = use->as_CallDynamicJava()->proj_out_or_null(TypeFunc::Control);
1549 if (p != NULL) {
1550 add_users_to_worklist0(p);
1551 }
1552 }
1553
1554 uint use_op = use->Opcode();
1555 if(use->is_Cmp()) { // Enable CMP/BOOL optimization
1556 add_users_to_worklist(use); // Put Bool on worklist
1557 if (use->outcnt() > 0) {
1558 Node* bol = use->raw_out(0);
1559 if (bol->outcnt() > 0) {
1560 Node* iff = bol->raw_out(0);
1561 if (iff->outcnt() == 2) {
1562 // Look for the 'is_x2logic' pattern: "x ? : 0 : 1" and put the
1563 // phi merging either 0 or 1 onto the worklist
1564 Node* ifproj0 = iff->raw_out(0);
1565 Node* ifproj1 = iff->raw_out(1);
1566 if (ifproj0->outcnt() > 0 && ifproj1->outcnt() > 0) {
1567 Node* region0 = ifproj0->raw_out(0);
1568 Node* region1 = ifproj1->raw_out(0);
1569 if( region0 == region1 )
1570 add_users_to_worklist0(region0);
1571 }
1572 }
1573 }
1574 }
1575 if (use_op == Op_CmpI) {
1576 Node* phi = countedloop_phi_from_cmp((CmpINode*)use, n);
1577 if (phi != NULL) {
1578 // If an opaque node feeds into the limit condition of a
1579 // CountedLoop, we need to process the Phi node for the
1580 // induction variable when the opaque node is removed:
1581 // the range of values taken by the Phi is now known and
1582 // so its type is also known.
1583 _worklist.push(phi);
1584 }
1585 Node* in1 = use->in(1);
1586 for (uint i = 0; i < in1->outcnt(); i++) {
1587 if (in1->raw_out(i)->Opcode() == Op_CastII) {
1588 Node* castii = in1->raw_out(i);
1589 if (castii->in(0) != NULL && castii->in(0)->in(0) != NULL && castii->in(0)->in(0)->is_If()) {
1590 Node* ifnode = castii->in(0)->in(0);
1591 if (ifnode->in(1) != NULL && ifnode->in(1)->is_Bool() && ifnode->in(1)->in(1) == use) {
1592 // Reprocess a CastII node that may depend on an
1593 // opaque node value when the opaque node is
1594 // removed. In case it carries a dependency we can do
1595 // a better job of computing its type.
1596 _worklist.push(castii);
1597 }
1598 }
1599 }
1600 }
1601 }
1602 }
1603
1604 // If changed Cast input, check Phi users for simple cycles
1605 if (use->is_ConstraintCast()) {
1606 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1607 Node* u = use->fast_out(i2);
1608 if (u->is_Phi())
1609 _worklist.push(u);
1610 }
1611 }
1612 // If changed LShift inputs, check RShift users for useless sign-ext
1613 if( use_op == Op_LShiftI ) {
1614 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1615 Node* u = use->fast_out(i2);
1616 if (u->Opcode() == Op_RShiftI)
1617 _worklist.push(u);
1618 }
1619 }
1620 // If changed AddI/SubI inputs, check CmpU for range check optimization.
1621 if (use_op == Op_AddI || use_op == Op_SubI) {
1622 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1623 Node* u = use->fast_out(i2);
1624 if (u->is_Cmp() && (u->Opcode() == Op_CmpU)) {
1625 _worklist.push(u);
1626 }
1627 }
1628 }
1629 // If changed AddP inputs, check Stores for loop invariant
1630 if( use_op == Op_AddP ) {
1631 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1632 Node* u = use->fast_out(i2);
1633 if (u->is_Mem())
1634 _worklist.push(u);
1635 }
1636 }
1637 // If changed initialization activity, check dependent Stores
1638 if (use_op == Op_Allocate || use_op == Op_AllocateArray) {
1639 InitializeNode* init = use->as_Allocate()->initialization();
1640 if (init != NULL) {
1641 Node* imem = init->proj_out_or_null(TypeFunc::Memory);
1642 if (imem != NULL) add_users_to_worklist0(imem);
1643 }
1644 }
1645 if (use_op == Op_Initialize) {
1646 Node* imem = use->as_Initialize()->proj_out_or_null(TypeFunc::Memory);
1647 if (imem != NULL) add_users_to_worklist0(imem);
1648 }
1649 // Loading the java mirror from a Klass requires two loads and the type
1650 // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1651 // LoadBarrier?(LoadP(LoadP(AddP(foo:Klass, #java_mirror))))
1652 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1653 bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1654
1655 if (use_op == Op_LoadP && use->bottom_type()->isa_rawptr()) {
1656 for (DUIterator_Fast i2max, i2 = use->fast_outs(i2max); i2 < i2max; i2++) {
1657 Node* u = use->fast_out(i2);
1658 const Type* ut = u->bottom_type();
1659 if (u->Opcode() == Op_LoadP && ut->isa_instptr()) {
1660 if (has_load_barrier_nodes) {
1661 // Search for load barriers behind the load
1662 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1663 Node* b = u->fast_out(i3);
1664 if (bs->is_gc_barrier_node(b)) {
1665 _worklist.push(b);
1666 }
1667 }
1668 }
1669 _worklist.push(u);
1670 }
1671 }
1672 }
1673 }
1674 }
1675
1676 /**
1677 * Remove the speculative part of all types that we know of
1678 */
remove_speculative_types()1679 void PhaseIterGVN::remove_speculative_types() {
1680 assert(UseTypeSpeculation, "speculation is off");
1681 for (uint i = 0; i < _types.Size(); i++) {
1682 const Type* t = _types.fast_lookup(i);
1683 if (t != NULL) {
1684 _types.map(i, t->remove_speculative());
1685 }
1686 }
1687 _table.check_no_speculative_types();
1688 }
1689
1690 // Check if the type of a divisor of a Div or Mod node includes zero.
no_dependent_zero_check(Node * n) const1691 bool PhaseIterGVN::no_dependent_zero_check(Node* n) const {
1692 switch (n->Opcode()) {
1693 case Op_DivI:
1694 case Op_ModI: {
1695 // Type of divisor includes 0?
1696 if (n->in(2)->is_top()) {
1697 // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1698 return false;
1699 }
1700 const TypeInt* type_divisor = type(n->in(2))->is_int();
1701 return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1702 }
1703 case Op_DivL:
1704 case Op_ModL: {
1705 // Type of divisor includes 0?
1706 if (n->in(2)->is_top()) {
1707 // 'n' is dead. Treat as if zero check is still there to avoid any further optimizations.
1708 return false;
1709 }
1710 const TypeLong* type_divisor = type(n->in(2))->is_long();
1711 return (type_divisor->_hi < 0 || type_divisor->_lo > 0);
1712 }
1713 }
1714 return true;
1715 }
1716
1717 //=============================================================================
1718 #ifndef PRODUCT
1719 uint PhaseCCP::_total_invokes = 0;
1720 uint PhaseCCP::_total_constants = 0;
1721 #endif
1722 //------------------------------PhaseCCP---------------------------------------
1723 // Conditional Constant Propagation, ala Wegman & Zadeck
PhaseCCP(PhaseIterGVN * igvn)1724 PhaseCCP::PhaseCCP( PhaseIterGVN *igvn ) : PhaseIterGVN(igvn) {
1725 NOT_PRODUCT( clear_constants(); )
1726 assert( _worklist.size() == 0, "" );
1727 // Clear out _nodes from IterGVN. Must be clear to transform call.
1728 _nodes.clear(); // Clear out from IterGVN
1729 analyze();
1730 }
1731
1732 #ifndef PRODUCT
1733 //------------------------------~PhaseCCP--------------------------------------
~PhaseCCP()1734 PhaseCCP::~PhaseCCP() {
1735 inc_invokes();
1736 _total_constants += count_constants();
1737 }
1738 #endif
1739
1740
1741 #ifdef ASSERT
ccp_type_widens(const Type * t,const Type * t0)1742 static bool ccp_type_widens(const Type* t, const Type* t0) {
1743 assert(t->meet(t0) == t, "Not monotonic");
1744 switch (t->base() == t0->base() ? t->base() : Type::Top) {
1745 case Type::Int:
1746 assert(t0->isa_int()->_widen <= t->isa_int()->_widen, "widen increases");
1747 break;
1748 case Type::Long:
1749 assert(t0->isa_long()->_widen <= t->isa_long()->_widen, "widen increases");
1750 break;
1751 default:
1752 break;
1753 }
1754 return true;
1755 }
1756 #endif //ASSERT
1757
1758 //------------------------------analyze----------------------------------------
analyze()1759 void PhaseCCP::analyze() {
1760 // Initialize all types to TOP, optimistic analysis
1761 for (int i = C->unique() - 1; i >= 0; i--) {
1762 _types.map(i,Type::TOP);
1763 }
1764
1765 // Push root onto worklist
1766 Unique_Node_List worklist;
1767 worklist.push(C->root());
1768
1769 // Pull from worklist; compute new value; push changes out.
1770 // This loop is the meat of CCP.
1771 while( worklist.size() ) {
1772 Node* n; // Node to be examined in this iteration
1773 if (StressCCP) {
1774 n = worklist.remove(C->random() % worklist.size());
1775 } else {
1776 n = worklist.pop();
1777 }
1778 const Type *t = n->Value(this);
1779 if (t != type(n)) {
1780 assert(ccp_type_widens(t, type(n)), "ccp type must widen");
1781 #ifndef PRODUCT
1782 if( TracePhaseCCP ) {
1783 t->dump();
1784 do { tty->print("\t"); } while (tty->position() < 16);
1785 n->dump();
1786 }
1787 #endif
1788 set_type(n, t);
1789 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1790 Node* m = n->fast_out(i); // Get user
1791 if (m->is_Region()) { // New path to Region? Must recheck Phis too
1792 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1793 Node* p = m->fast_out(i2); // Propagate changes to uses
1794 if (p->bottom_type() != type(p)) { // If not already bottomed out
1795 worklist.push(p); // Propagate change to user
1796 }
1797 }
1798 }
1799 // If we changed the receiver type to a call, we need to revisit
1800 // the Catch following the call. It's looking for a non-NULL
1801 // receiver to know when to enable the regular fall-through path
1802 // in addition to the NullPtrException path
1803 if (m->is_Call()) {
1804 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1805 Node* p = m->fast_out(i2); // Propagate changes to uses
1806 if (p->is_Proj() && p->as_Proj()->_con == TypeFunc::Control) {
1807 Node* catch_node = p->find_out_with(Op_Catch);
1808 if (catch_node != NULL) {
1809 worklist.push(catch_node);
1810 }
1811 }
1812 }
1813 }
1814 if (m->bottom_type() != type(m)) { // If not already bottomed out
1815 worklist.push(m); // Propagate change to user
1816 }
1817
1818 // CmpU nodes can get their type information from two nodes up in the
1819 // graph (instead of from the nodes immediately above). Make sure they
1820 // are added to the worklist if nodes they depend on are updated, since
1821 // they could be missed and get wrong types otherwise.
1822 uint m_op = m->Opcode();
1823 if (m_op == Op_AddI || m_op == Op_SubI) {
1824 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1825 Node* p = m->fast_out(i2); // Propagate changes to uses
1826 if (p->Opcode() == Op_CmpU) {
1827 // Got a CmpU which might need the new type information from node n.
1828 if(p->bottom_type() != type(p)) { // If not already bottomed out
1829 worklist.push(p); // Propagate change to user
1830 }
1831 }
1832 }
1833 }
1834 // If n is used in a counted loop exit condition then the type
1835 // of the counted loop's Phi depends on the type of n. See
1836 // PhiNode::Value().
1837 if (m_op == Op_CmpI) {
1838 PhiNode* phi = countedloop_phi_from_cmp((CmpINode*)m, n);
1839 if (phi != NULL) {
1840 worklist.push(phi);
1841 }
1842 }
1843 // Loading the java mirror from a Klass requires two loads and the type
1844 // of the mirror load depends on the type of 'n'. See LoadNode::Value().
1845 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1846 bool has_load_barrier_nodes = bs->has_load_barrier_nodes();
1847
1848 if (m_op == Op_LoadP && m->bottom_type()->isa_rawptr()) {
1849 for (DUIterator_Fast i2max, i2 = m->fast_outs(i2max); i2 < i2max; i2++) {
1850 Node* u = m->fast_out(i2);
1851 const Type* ut = u->bottom_type();
1852 if (u->Opcode() == Op_LoadP && ut->isa_instptr() && ut != type(u)) {
1853 if (has_load_barrier_nodes) {
1854 // Search for load barriers behind the load
1855 for (DUIterator_Fast i3max, i3 = u->fast_outs(i3max); i3 < i3max; i3++) {
1856 Node* b = u->fast_out(i3);
1857 if (bs->is_gc_barrier_node(b)) {
1858 worklist.push(b);
1859 }
1860 }
1861 }
1862 worklist.push(u);
1863 }
1864 }
1865 }
1866 }
1867 }
1868 }
1869 }
1870
1871 //------------------------------do_transform-----------------------------------
1872 // Top level driver for the recursive transformer
do_transform()1873 void PhaseCCP::do_transform() {
1874 // Correct leaves of new-space Nodes; they point to old-space.
1875 C->set_root( transform(C->root())->as_Root() );
1876 assert( C->top(), "missing TOP node" );
1877 assert( C->root(), "missing root" );
1878 }
1879
1880 //------------------------------transform--------------------------------------
1881 // Given a Node in old-space, clone him into new-space.
1882 // Convert any of his old-space children into new-space children.
transform(Node * n)1883 Node *PhaseCCP::transform( Node *n ) {
1884 Node *new_node = _nodes[n->_idx]; // Check for transformed node
1885 if( new_node != NULL )
1886 return new_node; // Been there, done that, return old answer
1887 new_node = transform_once(n); // Check for constant
1888 _nodes.map( n->_idx, new_node ); // Flag as having been cloned
1889
1890 // Allocate stack of size _nodes.Size()/2 to avoid frequent realloc
1891 GrowableArray <Node *> trstack(C->live_nodes() >> 1);
1892
1893 trstack.push(new_node); // Process children of cloned node
1894 while ( trstack.is_nonempty() ) {
1895 Node *clone = trstack.pop();
1896 uint cnt = clone->req();
1897 for( uint i = 0; i < cnt; i++ ) { // For all inputs do
1898 Node *input = clone->in(i);
1899 if( input != NULL ) { // Ignore NULLs
1900 Node *new_input = _nodes[input->_idx]; // Check for cloned input node
1901 if( new_input == NULL ) {
1902 new_input = transform_once(input); // Check for constant
1903 _nodes.map( input->_idx, new_input );// Flag as having been cloned
1904 trstack.push(new_input);
1905 }
1906 assert( new_input == clone->in(i), "insanity check");
1907 }
1908 }
1909 }
1910 return new_node;
1911 }
1912
1913
1914 //------------------------------transform_once---------------------------------
1915 // For PhaseCCP, transformation is IDENTITY unless Node computed a constant.
transform_once(Node * n)1916 Node *PhaseCCP::transform_once( Node *n ) {
1917 const Type *t = type(n);
1918 // Constant? Use constant Node instead
1919 if( t->singleton() ) {
1920 Node *nn = n; // Default is to return the original constant
1921 if( t == Type::TOP ) {
1922 // cache my top node on the Compile instance
1923 if( C->cached_top_node() == NULL || C->cached_top_node()->in(0) == NULL ) {
1924 C->set_cached_top_node(ConNode::make(Type::TOP));
1925 set_type(C->top(), Type::TOP);
1926 }
1927 nn = C->top();
1928 }
1929 if( !n->is_Con() ) {
1930 if( t != Type::TOP ) {
1931 nn = makecon(t); // ConNode::make(t);
1932 NOT_PRODUCT( inc_constants(); )
1933 } else if( n->is_Region() ) { // Unreachable region
1934 // Note: nn == C->top()
1935 n->set_req(0, NULL); // Cut selfreference
1936 bool progress = true;
1937 uint max = n->outcnt();
1938 DUIterator i;
1939 while (progress) {
1940 progress = false;
1941 // Eagerly remove dead phis to avoid phis copies creation.
1942 for (i = n->outs(); n->has_out(i); i++) {
1943 Node* m = n->out(i);
1944 if (m->is_Phi()) {
1945 assert(type(m) == Type::TOP, "Unreachable region should not have live phis.");
1946 replace_node(m, nn);
1947 if (max != n->outcnt()) {
1948 progress = true;
1949 i = n->refresh_out_pos(i);
1950 max = n->outcnt();
1951 }
1952 }
1953 }
1954 }
1955 }
1956 replace_node(n,nn); // Update DefUse edges for new constant
1957 }
1958 return nn;
1959 }
1960
1961 // If x is a TypeNode, capture any more-precise type permanently into Node
1962 if (t != n->bottom_type()) {
1963 hash_delete(n); // changing bottom type may force a rehash
1964 n->raise_bottom_type(t);
1965 _worklist.push(n); // n re-enters the hash table via the worklist
1966 }
1967
1968 // TEMPORARY fix to ensure that 2nd GVN pass eliminates NULL checks
1969 switch( n->Opcode() ) {
1970 case Op_FastLock: // Revisit FastLocks for lock coarsening
1971 case Op_If:
1972 case Op_CountedLoopEnd:
1973 case Op_Region:
1974 case Op_Loop:
1975 case Op_CountedLoop:
1976 case Op_Conv2B:
1977 case Op_Opaque1:
1978 case Op_Opaque2:
1979 _worklist.push(n);
1980 break;
1981 default:
1982 break;
1983 }
1984
1985 return n;
1986 }
1987
1988 //---------------------------------saturate------------------------------------
saturate(const Type * new_type,const Type * old_type,const Type * limit_type) const1989 const Type* PhaseCCP::saturate(const Type* new_type, const Type* old_type,
1990 const Type* limit_type) const {
1991 const Type* wide_type = new_type->widen(old_type, limit_type);
1992 if (wide_type != new_type) { // did we widen?
1993 // If so, we may have widened beyond the limit type. Clip it back down.
1994 new_type = wide_type->filter(limit_type);
1995 }
1996 return new_type;
1997 }
1998
1999 //------------------------------print_statistics-------------------------------
2000 #ifndef PRODUCT
print_statistics()2001 void PhaseCCP::print_statistics() {
2002 tty->print_cr("CCP: %d constants found: %d", _total_invokes, _total_constants);
2003 }
2004 #endif
2005
2006
2007 //=============================================================================
2008 #ifndef PRODUCT
2009 uint PhasePeephole::_total_peepholes = 0;
2010 #endif
2011 //------------------------------PhasePeephole----------------------------------
2012 // Conditional Constant Propagation, ala Wegman & Zadeck
PhasePeephole(PhaseRegAlloc * regalloc,PhaseCFG & cfg)2013 PhasePeephole::PhasePeephole( PhaseRegAlloc *regalloc, PhaseCFG &cfg )
2014 : PhaseTransform(Peephole), _regalloc(regalloc), _cfg(cfg) {
2015 NOT_PRODUCT( clear_peepholes(); )
2016 }
2017
2018 #ifndef PRODUCT
2019 //------------------------------~PhasePeephole---------------------------------
~PhasePeephole()2020 PhasePeephole::~PhasePeephole() {
2021 _total_peepholes += count_peepholes();
2022 }
2023 #endif
2024
2025 //------------------------------transform--------------------------------------
transform(Node * n)2026 Node *PhasePeephole::transform( Node *n ) {
2027 ShouldNotCallThis();
2028 return NULL;
2029 }
2030
2031 //------------------------------do_transform-----------------------------------
do_transform()2032 void PhasePeephole::do_transform() {
2033 bool method_name_not_printed = true;
2034
2035 // Examine each basic block
2036 for (uint block_number = 1; block_number < _cfg.number_of_blocks(); ++block_number) {
2037 Block* block = _cfg.get_block(block_number);
2038 bool block_not_printed = true;
2039
2040 // and each instruction within a block
2041 uint end_index = block->number_of_nodes();
2042 // block->end_idx() not valid after PhaseRegAlloc
2043 for( uint instruction_index = 1; instruction_index < end_index; ++instruction_index ) {
2044 Node *n = block->get_node(instruction_index);
2045 if( n->is_Mach() ) {
2046 MachNode *m = n->as_Mach();
2047 int deleted_count = 0;
2048 // check for peephole opportunities
2049 MachNode *m2 = m->peephole(block, instruction_index, _regalloc, deleted_count);
2050 if( m2 != NULL ) {
2051 #ifndef PRODUCT
2052 if( PrintOptoPeephole ) {
2053 // Print method, first time only
2054 if( C->method() && method_name_not_printed ) {
2055 C->method()->print_short_name(); tty->cr();
2056 method_name_not_printed = false;
2057 }
2058 // Print this block
2059 if( Verbose && block_not_printed) {
2060 tty->print_cr("in block");
2061 block->dump();
2062 block_not_printed = false;
2063 }
2064 // Print instructions being deleted
2065 for( int i = (deleted_count - 1); i >= 0; --i ) {
2066 block->get_node(instruction_index-i)->as_Mach()->format(_regalloc); tty->cr();
2067 }
2068 tty->print_cr("replaced with");
2069 // Print new instruction
2070 m2->format(_regalloc);
2071 tty->print("\n\n");
2072 }
2073 #endif
2074 // Remove old nodes from basic block and update instruction_index
2075 // (old nodes still exist and may have edges pointing to them
2076 // as register allocation info is stored in the allocator using
2077 // the node index to live range mappings.)
2078 uint safe_instruction_index = (instruction_index - deleted_count);
2079 for( ; (instruction_index > safe_instruction_index); --instruction_index ) {
2080 block->remove_node( instruction_index );
2081 }
2082 // install new node after safe_instruction_index
2083 block->insert_node(m2, safe_instruction_index + 1);
2084 end_index = block->number_of_nodes() - 1; // Recompute new block size
2085 NOT_PRODUCT( inc_peepholes(); )
2086 }
2087 }
2088 }
2089 }
2090 }
2091
2092 //------------------------------print_statistics-------------------------------
2093 #ifndef PRODUCT
print_statistics()2094 void PhasePeephole::print_statistics() {
2095 tty->print_cr("Peephole: peephole rules applied: %d", _total_peepholes);
2096 }
2097 #endif
2098
2099
2100 //=============================================================================
2101 //------------------------------set_req_X--------------------------------------
set_req_X(uint i,Node * n,PhaseIterGVN * igvn)2102 void Node::set_req_X( uint i, Node *n, PhaseIterGVN *igvn ) {
2103 assert( is_not_dead(n), "can not use dead node");
2104 assert( igvn->hash_find(this) != this, "Need to remove from hash before changing edges" );
2105 Node *old = in(i);
2106 set_req(i, n);
2107
2108 // old goes dead?
2109 if( old ) {
2110 switch (old->outcnt()) {
2111 case 0:
2112 // Put into the worklist to kill later. We do not kill it now because the
2113 // recursive kill will delete the current node (this) if dead-loop exists
2114 if (!old->is_top())
2115 igvn->_worklist.push( old );
2116 break;
2117 case 1:
2118 if( old->is_Store() || old->has_special_unique_user() )
2119 igvn->add_users_to_worklist( old );
2120 break;
2121 case 2:
2122 if( old->is_Store() )
2123 igvn->add_users_to_worklist( old );
2124 if( old->Opcode() == Op_Region )
2125 igvn->_worklist.push(old);
2126 break;
2127 case 3:
2128 if( old->Opcode() == Op_Region ) {
2129 igvn->_worklist.push(old);
2130 igvn->add_users_to_worklist( old );
2131 }
2132 break;
2133 default:
2134 break;
2135 }
2136
2137 BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, old);
2138 }
2139 }
2140
set_req_X(uint i,Node * n,PhaseGVN * gvn)2141 void Node::set_req_X(uint i, Node *n, PhaseGVN *gvn) {
2142 PhaseIterGVN* igvn = gvn->is_IterGVN();
2143 if (igvn == NULL) {
2144 set_req(i, n);
2145 return;
2146 }
2147 set_req_X(i, n, igvn);
2148 }
2149
2150 //-------------------------------replace_by-----------------------------------
2151 // Using def-use info, replace one node for another. Follow the def-use info
2152 // to all users of the OLD node. Then make all uses point to the NEW node.
replace_by(Node * new_node)2153 void Node::replace_by(Node *new_node) {
2154 assert(!is_top(), "top node has no DU info");
2155 for (DUIterator_Last imin, i = last_outs(imin); i >= imin; ) {
2156 Node* use = last_out(i);
2157 uint uses_found = 0;
2158 for (uint j = 0; j < use->len(); j++) {
2159 if (use->in(j) == this) {
2160 if (j < use->req())
2161 use->set_req(j, new_node);
2162 else use->set_prec(j, new_node);
2163 uses_found++;
2164 }
2165 }
2166 i -= uses_found; // we deleted 1 or more copies of this edge
2167 }
2168 }
2169
2170 //=============================================================================
2171 //-----------------------------------------------------------------------------
grow(uint i)2172 void Type_Array::grow( uint i ) {
2173 if( !_max ) {
2174 _max = 1;
2175 _types = (const Type**)_a->Amalloc( _max * sizeof(Type*) );
2176 _types[0] = NULL;
2177 }
2178 uint old = _max;
2179 _max = next_power_of_2(i);
2180 _types = (const Type**)_a->Arealloc( _types, old*sizeof(Type*),_max*sizeof(Type*));
2181 memset( &_types[old], 0, (_max-old)*sizeof(Type*) );
2182 }
2183
2184 //------------------------------dump-------------------------------------------
2185 #ifndef PRODUCT
dump() const2186 void Type_Array::dump() const {
2187 uint max = Size();
2188 for( uint i = 0; i < max; i++ ) {
2189 if( _types[i] != NULL ) {
2190 tty->print(" %d\t== ", i); _types[i]->dump(); tty->cr();
2191 }
2192 }
2193 }
2194 #endif
2195