1 /*
2  * Copyright (c) 1997, 2016, 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 "libadt/vectset.hpp"
29 #include "memory/allocation.inline.hpp"
30 #include "memory/resourceArea.hpp"
31 #include "opto/ad.hpp"
32 #include "opto/castnode.hpp"
33 #include "opto/cfgnode.hpp"
34 #include "opto/connode.hpp"
35 #include "opto/loopnode.hpp"
36 #include "opto/machnode.hpp"
37 #include "opto/matcher.hpp"
38 #include "opto/node.hpp"
39 #include "opto/opcodes.hpp"
40 #include "opto/regmask.hpp"
41 #include "opto/rootnode.hpp"
42 #include "opto/type.hpp"
43 #include "utilities/copy.hpp"
44 #include "utilities/macros.hpp"
45 #include "utilities/powerOfTwo.hpp"
46 
47 class RegMask;
48 // #include "phase.hpp"
49 class PhaseTransform;
50 class PhaseGVN;
51 
52 // Arena we are currently building Nodes in
53 const uint Node::NotAMachineReg = 0xffff0000;
54 
55 #ifndef PRODUCT
56 extern int nodes_created;
57 #endif
58 #ifdef __clang__
59 #pragma clang diagnostic push
60 #pragma GCC diagnostic ignored "-Wuninitialized"
61 #endif
62 
63 #ifdef ASSERT
64 
65 //-------------------------- construct_node------------------------------------
66 // Set a breakpoint here to identify where a particular node index is built.
verify_construction()67 void Node::verify_construction() {
68   _debug_orig = NULL;
69   int old_debug_idx = Compile::debug_idx();
70   int new_debug_idx = old_debug_idx + 1;
71   if (new_debug_idx > 0) {
72     // Arrange that the lowest five decimal digits of _debug_idx
73     // will repeat those of _idx. In case this is somehow pathological,
74     // we continue to assign negative numbers (!) consecutively.
75     const int mod = 100000;
76     int bump = (int)(_idx - new_debug_idx) % mod;
77     if (bump < 0) {
78       bump += mod;
79     }
80     assert(bump >= 0 && bump < mod, "");
81     new_debug_idx += bump;
82   }
83   Compile::set_debug_idx(new_debug_idx);
84   set_debug_idx(new_debug_idx);
85   Compile* C = Compile::current();
86   assert(C->unique() < (INT_MAX - 1), "Node limit exceeded INT_MAX");
87   if (!C->phase_optimize_finished()) {
88     // Only check assert during parsing and optimization phase. Skip it while generating code.
89     assert(C->live_nodes() <= C->max_node_limit(), "Live Node limit exceeded limit");
90   }
91   if (BreakAtNode != 0 && (_debug_idx == BreakAtNode || (int)_idx == BreakAtNode)) {
92     tty->print_cr("BreakAtNode: _idx=%d _debug_idx=%d", _idx, _debug_idx);
93     BREAKPOINT;
94   }
95 #if OPTO_DU_ITERATOR_ASSERT
96   _last_del = NULL;
97   _del_tick = 0;
98 #endif
99   _hash_lock = 0;
100 }
101 
102 
103 // #ifdef ASSERT ...
104 
105 #if OPTO_DU_ITERATOR_ASSERT
sample(const Node * node)106 void DUIterator_Common::sample(const Node* node) {
107   _vdui     = VerifyDUIterators;
108   _node     = node;
109   _outcnt   = node->_outcnt;
110   _del_tick = node->_del_tick;
111   _last     = NULL;
112 }
113 
verify(const Node * node,bool at_end_ok)114 void DUIterator_Common::verify(const Node* node, bool at_end_ok) {
115   assert(_node     == node, "consistent iterator source");
116   assert(_del_tick == node->_del_tick, "no unexpected deletions allowed");
117 }
118 
verify_resync()119 void DUIterator_Common::verify_resync() {
120   // Ensure that the loop body has just deleted the last guy produced.
121   const Node* node = _node;
122   // Ensure that at least one copy of the last-seen edge was deleted.
123   // Note:  It is OK to delete multiple copies of the last-seen edge.
124   // Unfortunately, we have no way to verify that all the deletions delete
125   // that same edge.  On this point we must use the Honor System.
126   assert(node->_del_tick >= _del_tick+1, "must have deleted an edge");
127   assert(node->_last_del == _last, "must have deleted the edge just produced");
128   // We liked this deletion, so accept the resulting outcnt and tick.
129   _outcnt   = node->_outcnt;
130   _del_tick = node->_del_tick;
131 }
132 
reset(const DUIterator_Common & that)133 void DUIterator_Common::reset(const DUIterator_Common& that) {
134   if (this == &that)  return;  // ignore assignment to self
135   if (!_vdui) {
136     // We need to initialize everything, overwriting garbage values.
137     _last = that._last;
138     _vdui = that._vdui;
139   }
140   // Note:  It is legal (though odd) for an iterator over some node x
141   // to be reassigned to iterate over another node y.  Some doubly-nested
142   // progress loops depend on being able to do this.
143   const Node* node = that._node;
144   // Re-initialize everything, except _last.
145   _node     = node;
146   _outcnt   = node->_outcnt;
147   _del_tick = node->_del_tick;
148 }
149 
sample(const Node * node)150 void DUIterator::sample(const Node* node) {
151   DUIterator_Common::sample(node);      // Initialize the assertion data.
152   _refresh_tick = 0;                    // No refreshes have happened, as yet.
153 }
154 
verify(const Node * node,bool at_end_ok)155 void DUIterator::verify(const Node* node, bool at_end_ok) {
156   DUIterator_Common::verify(node, at_end_ok);
157   assert(_idx      <  node->_outcnt + (uint)at_end_ok, "idx in range");
158 }
159 
verify_increment()160 void DUIterator::verify_increment() {
161   if (_refresh_tick & 1) {
162     // We have refreshed the index during this loop.
163     // Fix up _idx to meet asserts.
164     if (_idx > _outcnt)  _idx = _outcnt;
165   }
166   verify(_node, true);
167 }
168 
verify_resync()169 void DUIterator::verify_resync() {
170   // Note:  We do not assert on _outcnt, because insertions are OK here.
171   DUIterator_Common::verify_resync();
172   // Make sure we are still in sync, possibly with no more out-edges:
173   verify(_node, true);
174 }
175 
reset(const DUIterator & that)176 void DUIterator::reset(const DUIterator& that) {
177   if (this == &that)  return;  // self assignment is always a no-op
178   assert(that._refresh_tick == 0, "assign only the result of Node::outs()");
179   assert(that._idx          == 0, "assign only the result of Node::outs()");
180   assert(_idx               == that._idx, "already assigned _idx");
181   if (!_vdui) {
182     // We need to initialize everything, overwriting garbage values.
183     sample(that._node);
184   } else {
185     DUIterator_Common::reset(that);
186     if (_refresh_tick & 1) {
187       _refresh_tick++;                  // Clear the "was refreshed" flag.
188     }
189     assert(_refresh_tick < 2*100000, "DU iteration must converge quickly");
190   }
191 }
192 
refresh()193 void DUIterator::refresh() {
194   DUIterator_Common::sample(_node);     // Re-fetch assertion data.
195   _refresh_tick |= 1;                   // Set the "was refreshed" flag.
196 }
197 
verify_finish()198 void DUIterator::verify_finish() {
199   // If the loop has killed the node, do not require it to re-run.
200   if (_node->_outcnt == 0)  _refresh_tick &= ~1;
201   // If this assert triggers, it means that a loop used refresh_out_pos
202   // to re-synch an iteration index, but the loop did not correctly
203   // re-run itself, using a "while (progress)" construct.
204   // This iterator enforces the rule that you must keep trying the loop
205   // until it "runs clean" without any need for refreshing.
206   assert(!(_refresh_tick & 1), "the loop must run once with no refreshing");
207 }
208 
209 
verify(const Node * node,bool at_end_ok)210 void DUIterator_Fast::verify(const Node* node, bool at_end_ok) {
211   DUIterator_Common::verify(node, at_end_ok);
212   Node** out    = node->_out;
213   uint   cnt    = node->_outcnt;
214   assert(cnt == _outcnt, "no insertions allowed");
215   assert(_outp >= out && _outp <= out + cnt - !at_end_ok, "outp in range");
216   // This last check is carefully designed to work for NO_OUT_ARRAY.
217 }
218 
verify_limit()219 void DUIterator_Fast::verify_limit() {
220   const Node* node = _node;
221   verify(node, true);
222   assert(_outp == node->_out + node->_outcnt, "limit still correct");
223 }
224 
verify_resync()225 void DUIterator_Fast::verify_resync() {
226   const Node* node = _node;
227   if (_outp == node->_out + _outcnt) {
228     // Note that the limit imax, not the pointer i, gets updated with the
229     // exact count of deletions.  (For the pointer it's always "--i".)
230     assert(node->_outcnt+node->_del_tick == _outcnt+_del_tick, "no insertions allowed with deletion(s)");
231     // This is a limit pointer, with a name like "imax".
232     // Fudge the _last field so that the common assert will be happy.
233     _last = (Node*) node->_last_del;
234     DUIterator_Common::verify_resync();
235   } else {
236     assert(node->_outcnt < _outcnt, "no insertions allowed with deletion(s)");
237     // A normal internal pointer.
238     DUIterator_Common::verify_resync();
239     // Make sure we are still in sync, possibly with no more out-edges:
240     verify(node, true);
241   }
242 }
243 
verify_relimit(uint n)244 void DUIterator_Fast::verify_relimit(uint n) {
245   const Node* node = _node;
246   assert((int)n > 0, "use imax -= n only with a positive count");
247   // This must be a limit pointer, with a name like "imax".
248   assert(_outp == node->_out + node->_outcnt, "apply -= only to a limit (imax)");
249   // The reported number of deletions must match what the node saw.
250   assert(node->_del_tick == _del_tick + n, "must have deleted n edges");
251   // Fudge the _last field so that the common assert will be happy.
252   _last = (Node*) node->_last_del;
253   DUIterator_Common::verify_resync();
254 }
255 
reset(const DUIterator_Fast & that)256 void DUIterator_Fast::reset(const DUIterator_Fast& that) {
257   assert(_outp              == that._outp, "already assigned _outp");
258   DUIterator_Common::reset(that);
259 }
260 
verify(const Node * node,bool at_end_ok)261 void DUIterator_Last::verify(const Node* node, bool at_end_ok) {
262   // at_end_ok means the _outp is allowed to underflow by 1
263   _outp += at_end_ok;
264   DUIterator_Fast::verify(node, at_end_ok);  // check _del_tick, etc.
265   _outp -= at_end_ok;
266   assert(_outp == (node->_out + node->_outcnt) - 1, "pointer must point to end of nodes");
267 }
268 
verify_limit()269 void DUIterator_Last::verify_limit() {
270   // Do not require the limit address to be resynched.
271   //verify(node, true);
272   assert(_outp == _node->_out, "limit still correct");
273 }
274 
verify_step(uint num_edges)275 void DUIterator_Last::verify_step(uint num_edges) {
276   assert((int)num_edges > 0, "need non-zero edge count for loop progress");
277   _outcnt   -= num_edges;
278   _del_tick += num_edges;
279   // Make sure we are still in sync, possibly with no more out-edges:
280   const Node* node = _node;
281   verify(node, true);
282   assert(node->_last_del == _last, "must have deleted the edge just produced");
283 }
284 
285 #endif //OPTO_DU_ITERATOR_ASSERT
286 
287 
288 #endif //ASSERT
289 
290 
291 // This constant used to initialize _out may be any non-null value.
292 // The value NULL is reserved for the top node only.
293 #define NO_OUT_ARRAY ((Node**)-1)
294 
295 // Out-of-line code from node constructors.
296 // Executed only when extra debug info. is being passed around.
init_node_notes(Compile * C,int idx,Node_Notes * nn)297 static void init_node_notes(Compile* C, int idx, Node_Notes* nn) {
298   C->set_node_notes_at(idx, nn);
299 }
300 
301 // Shared initialization code.
Init(int req)302 inline int Node::Init(int req) {
303   Compile* C = Compile::current();
304   int idx = C->next_unique();
305 
306   // Allocate memory for the necessary number of edges.
307   if (req > 0) {
308     // Allocate space for _in array to have double alignment.
309     _in = (Node **) ((char *) (C->node_arena()->Amalloc_D(req * sizeof(void*))));
310   }
311   // If there are default notes floating around, capture them:
312   Node_Notes* nn = C->default_node_notes();
313   if (nn != NULL)  init_node_notes(C, idx, nn);
314 
315   // Note:  At this point, C is dead,
316   // and we begin to initialize the new Node.
317 
318   _cnt = _max = req;
319   _outcnt = _outmax = 0;
320   _class_id = Class_Node;
321   _flags = 0;
322   _out = NO_OUT_ARRAY;
323   return idx;
324 }
325 
326 //------------------------------Node-------------------------------------------
327 // Create a Node, with a given number of required edges.
Node(uint req)328 Node::Node(uint req)
329   : _idx(Init(req))
330 #ifdef ASSERT
331   , _parse_idx(_idx)
332 #endif
333 {
334   assert( req < Compile::current()->max_node_limit() - NodeLimitFudgeFactor, "Input limit exceeded" );
335   debug_only( verify_construction() );
336   NOT_PRODUCT(nodes_created++);
337   if (req == 0) {
338     _in = NULL;
339   } else {
340     Node** to = _in;
341     for(uint i = 0; i < req; i++) {
342       to[i] = NULL;
343     }
344   }
345 }
346 
347 //------------------------------Node-------------------------------------------
Node(Node * n0)348 Node::Node(Node *n0)
349   : _idx(Init(1))
350 #ifdef ASSERT
351   , _parse_idx(_idx)
352 #endif
353 {
354   debug_only( verify_construction() );
355   NOT_PRODUCT(nodes_created++);
356   assert( is_not_dead(n0), "can not use dead node");
357   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
358 }
359 
360 //------------------------------Node-------------------------------------------
Node(Node * n0,Node * n1)361 Node::Node(Node *n0, Node *n1)
362   : _idx(Init(2))
363 #ifdef ASSERT
364   , _parse_idx(_idx)
365 #endif
366 {
367   debug_only( verify_construction() );
368   NOT_PRODUCT(nodes_created++);
369   assert( is_not_dead(n0), "can not use dead node");
370   assert( is_not_dead(n1), "can not use dead node");
371   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
372   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
373 }
374 
375 //------------------------------Node-------------------------------------------
Node(Node * n0,Node * n1,Node * n2)376 Node::Node(Node *n0, Node *n1, Node *n2)
377   : _idx(Init(3))
378 #ifdef ASSERT
379   , _parse_idx(_idx)
380 #endif
381 {
382   debug_only( verify_construction() );
383   NOT_PRODUCT(nodes_created++);
384   assert( is_not_dead(n0), "can not use dead node");
385   assert( is_not_dead(n1), "can not use dead node");
386   assert( is_not_dead(n2), "can not use dead node");
387   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
388   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
389   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
390 }
391 
392 //------------------------------Node-------------------------------------------
Node(Node * n0,Node * n1,Node * n2,Node * n3)393 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3)
394   : _idx(Init(4))
395 #ifdef ASSERT
396   , _parse_idx(_idx)
397 #endif
398 {
399   debug_only( verify_construction() );
400   NOT_PRODUCT(nodes_created++);
401   assert( is_not_dead(n0), "can not use dead node");
402   assert( is_not_dead(n1), "can not use dead node");
403   assert( is_not_dead(n2), "can not use dead node");
404   assert( is_not_dead(n3), "can not use dead node");
405   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
406   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
407   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
408   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
409 }
410 
411 //------------------------------Node-------------------------------------------
Node(Node * n0,Node * n1,Node * n2,Node * n3,Node * n4)412 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3, Node *n4)
413   : _idx(Init(5))
414 #ifdef ASSERT
415   , _parse_idx(_idx)
416 #endif
417 {
418   debug_only( verify_construction() );
419   NOT_PRODUCT(nodes_created++);
420   assert( is_not_dead(n0), "can not use dead node");
421   assert( is_not_dead(n1), "can not use dead node");
422   assert( is_not_dead(n2), "can not use dead node");
423   assert( is_not_dead(n3), "can not use dead node");
424   assert( is_not_dead(n4), "can not use dead node");
425   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
426   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
427   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
428   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
429   _in[4] = n4; if (n4 != NULL) n4->add_out((Node *)this);
430 }
431 
432 //------------------------------Node-------------------------------------------
Node(Node * n0,Node * n1,Node * n2,Node * n3,Node * n4,Node * n5)433 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
434                      Node *n4, Node *n5)
435   : _idx(Init(6))
436 #ifdef ASSERT
437   , _parse_idx(_idx)
438 #endif
439 {
440   debug_only( verify_construction() );
441   NOT_PRODUCT(nodes_created++);
442   assert( is_not_dead(n0), "can not use dead node");
443   assert( is_not_dead(n1), "can not use dead node");
444   assert( is_not_dead(n2), "can not use dead node");
445   assert( is_not_dead(n3), "can not use dead node");
446   assert( is_not_dead(n4), "can not use dead node");
447   assert( is_not_dead(n5), "can not use dead node");
448   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
449   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
450   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
451   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
452   _in[4] = n4; if (n4 != NULL) n4->add_out((Node *)this);
453   _in[5] = n5; if (n5 != NULL) n5->add_out((Node *)this);
454 }
455 
456 //------------------------------Node-------------------------------------------
Node(Node * n0,Node * n1,Node * n2,Node * n3,Node * n4,Node * n5,Node * n6)457 Node::Node(Node *n0, Node *n1, Node *n2, Node *n3,
458                      Node *n4, Node *n5, Node *n6)
459   : _idx(Init(7))
460 #ifdef ASSERT
461   , _parse_idx(_idx)
462 #endif
463 {
464   debug_only( verify_construction() );
465   NOT_PRODUCT(nodes_created++);
466   assert( is_not_dead(n0), "can not use dead node");
467   assert( is_not_dead(n1), "can not use dead node");
468   assert( is_not_dead(n2), "can not use dead node");
469   assert( is_not_dead(n3), "can not use dead node");
470   assert( is_not_dead(n4), "can not use dead node");
471   assert( is_not_dead(n5), "can not use dead node");
472   assert( is_not_dead(n6), "can not use dead node");
473   _in[0] = n0; if (n0 != NULL) n0->add_out((Node *)this);
474   _in[1] = n1; if (n1 != NULL) n1->add_out((Node *)this);
475   _in[2] = n2; if (n2 != NULL) n2->add_out((Node *)this);
476   _in[3] = n3; if (n3 != NULL) n3->add_out((Node *)this);
477   _in[4] = n4; if (n4 != NULL) n4->add_out((Node *)this);
478   _in[5] = n5; if (n5 != NULL) n5->add_out((Node *)this);
479   _in[6] = n6; if (n6 != NULL) n6->add_out((Node *)this);
480 }
481 
482 #ifdef __clang__
483 #pragma clang diagnostic pop
484 #endif
485 
486 
487 //------------------------------clone------------------------------------------
488 // Clone a Node.
clone() const489 Node *Node::clone() const {
490   Compile* C = Compile::current();
491   uint s = size_of();           // Size of inherited Node
492   Node *n = (Node*)C->node_arena()->Amalloc_D(size_of() + _max*sizeof(Node*));
493   Copy::conjoint_words_to_lower((HeapWord*)this, (HeapWord*)n, s);
494   // Set the new input pointer array
495   n->_in = (Node**)(((char*)n)+s);
496   // Cannot share the old output pointer array, so kill it
497   n->_out = NO_OUT_ARRAY;
498   // And reset the counters to 0
499   n->_outcnt = 0;
500   n->_outmax = 0;
501   // Unlock this guy, since he is not in any hash table.
502   debug_only(n->_hash_lock = 0);
503   // Walk the old node's input list to duplicate its edges
504   uint i;
505   for( i = 0; i < len(); i++ ) {
506     Node *x = in(i);
507     n->_in[i] = x;
508     if (x != NULL) x->add_out(n);
509   }
510   if (is_macro())
511     C->add_macro_node(n);
512   if (is_expensive())
513     C->add_expensive_node(n);
514   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
515   bs->register_potential_barrier_node(n);
516   // If the cloned node is a range check dependent CastII, add it to the list.
517   CastIINode* cast = n->isa_CastII();
518   if (cast != NULL && cast->has_range_check()) {
519     C->add_range_check_cast(cast);
520   }
521   if (n->Opcode() == Op_Opaque4) {
522     C->add_opaque4_node(n);
523   }
524 
525   n->set_idx(C->next_unique()); // Get new unique index as well
526   debug_only( n->verify_construction() );
527   NOT_PRODUCT(nodes_created++);
528   // Do not patch over the debug_idx of a clone, because it makes it
529   // impossible to break on the clone's moment of creation.
530   //debug_only( n->set_debug_idx( debug_idx() ) );
531 
532   C->copy_node_notes_to(n, (Node*) this);
533 
534   // MachNode clone
535   uint nopnds;
536   if (this->is_Mach() && (nopnds = this->as_Mach()->num_opnds()) > 0) {
537     MachNode *mach  = n->as_Mach();
538     MachNode *mthis = this->as_Mach();
539     // Get address of _opnd_array.
540     // It should be the same offset since it is the clone of this node.
541     MachOper **from = mthis->_opnds;
542     MachOper **to = (MachOper **)((size_t)(&mach->_opnds) +
543                     pointer_delta((const void*)from,
544                                   (const void*)(&mthis->_opnds), 1));
545     mach->_opnds = to;
546     for ( uint i = 0; i < nopnds; ++i ) {
547       to[i] = from[i]->clone();
548     }
549   }
550   // cloning CallNode may need to clone JVMState
551   if (n->is_Call()) {
552     n->as_Call()->clone_jvms(C);
553   }
554   if (n->is_SafePoint()) {
555     n->as_SafePoint()->clone_replaced_nodes();
556   }
557   return n;                     // Return the clone
558 }
559 
560 //---------------------------setup_is_top--------------------------------------
561 // Call this when changing the top node, to reassert the invariants
562 // required by Node::is_top.  See Compile::set_cached_top_node.
setup_is_top()563 void Node::setup_is_top() {
564   if (this == (Node*)Compile::current()->top()) {
565     // This node has just become top.  Kill its out array.
566     _outcnt = _outmax = 0;
567     _out = NULL;                           // marker value for top
568     assert(is_top(), "must be top");
569   } else {
570     if (_out == NULL)  _out = NO_OUT_ARRAY;
571     assert(!is_top(), "must not be top");
572   }
573 }
574 
575 //------------------------------~Node------------------------------------------
576 // Fancy destructor; eagerly attempt to reclaim Node numberings and storage
destruct()577 void Node::destruct() {
578   // Eagerly reclaim unique Node numberings
579   Compile* compile = Compile::current();
580   if ((uint)_idx+1 == compile->unique()) {
581     compile->set_unique(compile->unique()-1);
582   }
583   // Clear debug info:
584   Node_Notes* nn = compile->node_notes_at(_idx);
585   if (nn != NULL)  nn->clear();
586   // Walk the input array, freeing the corresponding output edges
587   _cnt = _max;  // forget req/prec distinction
588   uint i;
589   for( i = 0; i < _max; i++ ) {
590     set_req(i, NULL);
591     //assert(def->out(def->outcnt()-1) == (Node *)this,"bad def-use hacking in reclaim");
592   }
593   assert(outcnt() == 0, "deleting a node must not leave a dangling use");
594   // See if the input array was allocated just prior to the object
595   int edge_size = _max*sizeof(void*);
596   int out_edge_size = _outmax*sizeof(void*);
597   char *edge_end = ((char*)_in) + edge_size;
598   char *out_array = (char*)(_out == NO_OUT_ARRAY? NULL: _out);
599   int node_size = size_of();
600 
601   // Free the output edge array
602   if (out_edge_size > 0) {
603     compile->node_arena()->Afree(out_array, out_edge_size);
604   }
605 
606   // Free the input edge array and the node itself
607   if( edge_end == (char*)this ) {
608     // It was; free the input array and object all in one hit
609 #ifndef ASSERT
610     compile->node_arena()->Afree(_in,edge_size+node_size);
611 #endif
612   } else {
613     // Free just the input array
614     compile->node_arena()->Afree(_in,edge_size);
615 
616     // Free just the object
617 #ifndef ASSERT
618     compile->node_arena()->Afree(this,node_size);
619 #endif
620   }
621   if (is_macro()) {
622     compile->remove_macro_node(this);
623   }
624   if (is_expensive()) {
625     compile->remove_expensive_node(this);
626   }
627   CastIINode* cast = isa_CastII();
628   if (cast != NULL && cast->has_range_check()) {
629     compile->remove_range_check_cast(cast);
630   }
631   if (Opcode() == Op_Opaque4) {
632     compile->remove_opaque4_node(this);
633   }
634 
635   if (is_SafePoint()) {
636     as_SafePoint()->delete_replaced_nodes();
637   }
638   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
639   bs->unregister_potential_barrier_node(this);
640 #ifdef ASSERT
641   // We will not actually delete the storage, but we'll make the node unusable.
642   *(address*)this = badAddress;  // smash the C++ vtbl, probably
643   _in = _out = (Node**) badAddress;
644   _max = _cnt = _outmax = _outcnt = 0;
645   compile->remove_modified_node(this);
646 #endif
647 }
648 
649 //------------------------------grow-------------------------------------------
650 // Grow the input array, making space for more edges
grow(uint len)651 void Node::grow( uint len ) {
652   Arena* arena = Compile::current()->node_arena();
653   uint new_max = _max;
654   if( new_max == 0 ) {
655     _max = 4;
656     _in = (Node**)arena->Amalloc(4*sizeof(Node*));
657     Node** to = _in;
658     to[0] = NULL;
659     to[1] = NULL;
660     to[2] = NULL;
661     to[3] = NULL;
662     return;
663   }
664   new_max = next_power_of_2(len);
665   // Trimming to limit allows a uint8 to handle up to 255 edges.
666   // Previously I was using only powers-of-2 which peaked at 128 edges.
667   //if( new_max >= limit ) new_max = limit-1;
668   _in = (Node**)arena->Arealloc(_in, _max*sizeof(Node*), new_max*sizeof(Node*));
669   Copy::zero_to_bytes(&_in[_max], (new_max-_max)*sizeof(Node*)); // NULL all new space
670   _max = new_max;               // Record new max length
671   // This assertion makes sure that Node::_max is wide enough to
672   // represent the numerical value of new_max.
673   assert(_max == new_max && _max > len, "int width of _max is too small");
674 }
675 
676 //-----------------------------out_grow----------------------------------------
677 // Grow the input array, making space for more edges
out_grow(uint len)678 void Node::out_grow( uint len ) {
679   assert(!is_top(), "cannot grow a top node's out array");
680   Arena* arena = Compile::current()->node_arena();
681   uint new_max = _outmax;
682   if( new_max == 0 ) {
683     _outmax = 4;
684     _out = (Node **)arena->Amalloc(4*sizeof(Node*));
685     return;
686   }
687   new_max = next_power_of_2(len);
688   // Trimming to limit allows a uint8 to handle up to 255 edges.
689   // Previously I was using only powers-of-2 which peaked at 128 edges.
690   //if( new_max >= limit ) new_max = limit-1;
691   assert(_out != NULL && _out != NO_OUT_ARRAY, "out must have sensible value");
692   _out = (Node**)arena->Arealloc(_out,_outmax*sizeof(Node*),new_max*sizeof(Node*));
693   //Copy::zero_to_bytes(&_out[_outmax], (new_max-_outmax)*sizeof(Node*)); // NULL all new space
694   _outmax = new_max;               // Record new max length
695   // This assertion makes sure that Node::_max is wide enough to
696   // represent the numerical value of new_max.
697   assert(_outmax == new_max && _outmax > len, "int width of _outmax is too small");
698 }
699 
700 #ifdef ASSERT
701 //------------------------------is_dead----------------------------------------
is_dead() const702 bool Node::is_dead() const {
703   // Mach and pinch point nodes may look like dead.
704   if( is_top() || is_Mach() || (Opcode() == Op_Node && _outcnt > 0) )
705     return false;
706   for( uint i = 0; i < _max; i++ )
707     if( _in[i] != NULL )
708       return false;
709   dump();
710   return true;
711 }
712 
is_reachable_from_root() const713 bool Node::is_reachable_from_root() const {
714   ResourceMark rm;
715   Unique_Node_List wq;
716   wq.push((Node*)this);
717   RootNode* root = Compile::current()->root();
718   for (uint i = 0; i < wq.size(); i++) {
719     Node* m = wq.at(i);
720     if (m == root) {
721       return true;
722     }
723     for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
724       Node* u = m->fast_out(j);
725       wq.push(u);
726     }
727   }
728   return false;
729 }
730 #endif
731 
732 //------------------------------is_unreachable---------------------------------
is_unreachable(PhaseIterGVN & igvn) const733 bool Node::is_unreachable(PhaseIterGVN &igvn) const {
734   assert(!is_Mach(), "doesn't work with MachNodes");
735   return outcnt() == 0 || igvn.type(this) == Type::TOP || (in(0) != NULL && in(0)->is_top());
736 }
737 
738 //------------------------------add_req----------------------------------------
739 // Add a new required input at the end
add_req(Node * n)740 void Node::add_req( Node *n ) {
741   assert( is_not_dead(n), "can not use dead node");
742 
743   // Look to see if I can move precedence down one without reallocating
744   if( (_cnt >= _max) || (in(_max-1) != NULL) )
745     grow( _max+1 );
746 
747   // Find a precedence edge to move
748   if( in(_cnt) != NULL ) {       // Next precedence edge is busy?
749     uint i;
750     for( i=_cnt; i<_max; i++ )
751       if( in(i) == NULL )       // Find the NULL at end of prec edge list
752         break;                  // There must be one, since we grew the array
753     _in[i] = in(_cnt);          // Move prec over, making space for req edge
754   }
755   _in[_cnt++] = n;            // Stuff over old prec edge
756   if (n != NULL) n->add_out((Node *)this);
757 }
758 
759 //---------------------------add_req_batch-------------------------------------
760 // Add a new required input at the end
add_req_batch(Node * n,uint m)761 void Node::add_req_batch( Node *n, uint m ) {
762   assert( is_not_dead(n), "can not use dead node");
763   // check various edge cases
764   if ((int)m <= 1) {
765     assert((int)m >= 0, "oob");
766     if (m != 0)  add_req(n);
767     return;
768   }
769 
770   // Look to see if I can move precedence down one without reallocating
771   if( (_cnt+m) > _max || _in[_max-m] )
772     grow( _max+m );
773 
774   // Find a precedence edge to move
775   if( _in[_cnt] != NULL ) {     // Next precedence edge is busy?
776     uint i;
777     for( i=_cnt; i<_max; i++ )
778       if( _in[i] == NULL )      // Find the NULL at end of prec edge list
779         break;                  // There must be one, since we grew the array
780     // Slide all the precs over by m positions (assume #prec << m).
781     Copy::conjoint_words_to_higher((HeapWord*)&_in[_cnt], (HeapWord*)&_in[_cnt+m], ((i-_cnt)*sizeof(Node*)));
782   }
783 
784   // Stuff over the old prec edges
785   for(uint i=0; i<m; i++ ) {
786     _in[_cnt++] = n;
787   }
788 
789   // Insert multiple out edges on the node.
790   if (n != NULL && !n->is_top()) {
791     for(uint i=0; i<m; i++ ) {
792       n->add_out((Node *)this);
793     }
794   }
795 }
796 
797 //------------------------------del_req----------------------------------------
798 // Delete the required edge and compact the edge array
del_req(uint idx)799 void Node::del_req( uint idx ) {
800   assert( idx < _cnt, "oob");
801   assert( !VerifyHashTableKeys || _hash_lock == 0,
802           "remove node from hash table before modifying it");
803   // First remove corresponding def-use edge
804   Node *n = in(idx);
805   if (n != NULL) n->del_out((Node *)this);
806   _in[idx] = in(--_cnt); // Compact the array
807   // Avoid spec violation: Gap in prec edges.
808   close_prec_gap_at(_cnt);
809   Compile::current()->record_modified_node(this);
810 }
811 
812 //------------------------------del_req_ordered--------------------------------
813 // Delete the required edge and compact the edge array with preserved order
del_req_ordered(uint idx)814 void Node::del_req_ordered( uint idx ) {
815   assert( idx < _cnt, "oob");
816   assert( !VerifyHashTableKeys || _hash_lock == 0,
817           "remove node from hash table before modifying it");
818   // First remove corresponding def-use edge
819   Node *n = in(idx);
820   if (n != NULL) n->del_out((Node *)this);
821   if (idx < --_cnt) {    // Not last edge ?
822     Copy::conjoint_words_to_lower((HeapWord*)&_in[idx+1], (HeapWord*)&_in[idx], ((_cnt-idx)*sizeof(Node*)));
823   }
824   // Avoid spec violation: Gap in prec edges.
825   close_prec_gap_at(_cnt);
826   Compile::current()->record_modified_node(this);
827 }
828 
829 //------------------------------ins_req----------------------------------------
830 // Insert a new required input at the end
ins_req(uint idx,Node * n)831 void Node::ins_req( uint idx, Node *n ) {
832   assert( is_not_dead(n), "can not use dead node");
833   add_req(NULL);                // Make space
834   assert( idx < _max, "Must have allocated enough space");
835   // Slide over
836   if(_cnt-idx-1 > 0) {
837     Copy::conjoint_words_to_higher((HeapWord*)&_in[idx], (HeapWord*)&_in[idx+1], ((_cnt-idx-1)*sizeof(Node*)));
838   }
839   _in[idx] = n;                            // Stuff over old required edge
840   if (n != NULL) n->add_out((Node *)this); // Add reciprocal def-use edge
841 }
842 
843 //-----------------------------find_edge---------------------------------------
find_edge(Node * n)844 int Node::find_edge(Node* n) {
845   for (uint i = 0; i < len(); i++) {
846     if (_in[i] == n)  return i;
847   }
848   return -1;
849 }
850 
851 //----------------------------replace_edge-------------------------------------
replace_edge(Node * old,Node * neww)852 int Node::replace_edge(Node* old, Node* neww) {
853   if (old == neww)  return 0;  // nothing to do
854   uint nrep = 0;
855   for (uint i = 0; i < len(); i++) {
856     if (in(i) == old) {
857       if (i < req()) {
858         set_req(i, neww);
859       } else {
860         assert(find_prec_edge(neww) == -1, "spec violation: duplicated prec edge (node %d -> %d)", _idx, neww->_idx);
861         set_prec(i, neww);
862       }
863       nrep++;
864     }
865   }
866   return nrep;
867 }
868 
869 /**
870  * Replace input edges in the range pointing to 'old' node.
871  */
replace_edges_in_range(Node * old,Node * neww,int start,int end)872 int Node::replace_edges_in_range(Node* old, Node* neww, int start, int end) {
873   if (old == neww)  return 0;  // nothing to do
874   uint nrep = 0;
875   for (int i = start; i < end; i++) {
876     if (in(i) == old) {
877       set_req(i, neww);
878       nrep++;
879     }
880   }
881   return nrep;
882 }
883 
884 //-------------------------disconnect_inputs-----------------------------------
885 // NULL out all inputs to eliminate incoming Def-Use edges.
886 // Return the number of edges between 'n' and 'this'
disconnect_inputs(Node * n,Compile * C)887 int Node::disconnect_inputs(Node *n, Compile* C) {
888   int edges_to_n = 0;
889 
890   uint cnt = req();
891   for( uint i = 0; i < cnt; ++i ) {
892     if( in(i) == 0 ) continue;
893     if( in(i) == n ) ++edges_to_n;
894     set_req(i, NULL);
895   }
896   // Remove precedence edges if any exist
897   // Note: Safepoints may have precedence edges, even during parsing
898   if( (req() != len()) && (in(req()) != NULL) ) {
899     uint max = len();
900     for( uint i = 0; i < max; ++i ) {
901       if( in(i) == 0 ) continue;
902       if( in(i) == n ) ++edges_to_n;
903       set_prec(i, NULL);
904     }
905   }
906 
907   // Node::destruct requires all out edges be deleted first
908   // debug_only(destruct();)   // no reuse benefit expected
909   if (edges_to_n == 0) {
910     C->record_dead_node(_idx);
911   }
912   return edges_to_n;
913 }
914 
915 //-----------------------------uncast---------------------------------------
916 // %%% Temporary, until we sort out CheckCastPP vs. CastPP.
917 // Strip away casting.  (It is depth-limited.)
918 // Optionally, keep casts with dependencies.
uncast(bool keep_deps) const919 Node* Node::uncast(bool keep_deps) const {
920   // Should be inline:
921   //return is_ConstraintCast() ? uncast_helper(this) : (Node*) this;
922   if (is_ConstraintCast()) {
923     return uncast_helper(this, keep_deps);
924   } else {
925     return (Node*) this;
926   }
927 }
928 
929 // Find out of current node that matches opcode.
find_out_with(int opcode)930 Node* Node::find_out_with(int opcode) {
931   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
932     Node* use = fast_out(i);
933     if (use->Opcode() == opcode) {
934       return use;
935     }
936   }
937   return NULL;
938 }
939 
940 // Return true if the current node has an out that matches opcode.
has_out_with(int opcode)941 bool Node::has_out_with(int opcode) {
942   return (find_out_with(opcode) != NULL);
943 }
944 
945 // Return true if the current node has an out that matches any of the opcodes.
has_out_with(int opcode1,int opcode2,int opcode3,int opcode4)946 bool Node::has_out_with(int opcode1, int opcode2, int opcode3, int opcode4) {
947   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
948       int opcode = fast_out(i)->Opcode();
949       if (opcode == opcode1 || opcode == opcode2 || opcode == opcode3 || opcode == opcode4) {
950         return true;
951       }
952   }
953   return false;
954 }
955 
956 
957 //---------------------------uncast_helper-------------------------------------
uncast_helper(const Node * p,bool keep_deps)958 Node* Node::uncast_helper(const Node* p, bool keep_deps) {
959 #ifdef ASSERT
960   uint depth_count = 0;
961   const Node* orig_p = p;
962 #endif
963 
964   while (true) {
965 #ifdef ASSERT
966     if (depth_count >= K) {
967       orig_p->dump(4);
968       if (p != orig_p)
969         p->dump(1);
970     }
971     assert(depth_count++ < K, "infinite loop in Node::uncast_helper");
972 #endif
973     if (p == NULL || p->req() != 2) {
974       break;
975     } else if (p->is_ConstraintCast()) {
976       if (keep_deps && p->as_ConstraintCast()->carry_dependency()) {
977         break; // stop at casts with dependencies
978       }
979       p = p->in(1);
980     } else {
981       break;
982     }
983   }
984   return (Node*) p;
985 }
986 
987 //------------------------------add_prec---------------------------------------
988 // Add a new precedence input.  Precedence inputs are unordered, with
989 // duplicates removed and NULLs packed down at the end.
add_prec(Node * n)990 void Node::add_prec( Node *n ) {
991   assert( is_not_dead(n), "can not use dead node");
992 
993   // Check for NULL at end
994   if( _cnt >= _max || in(_max-1) )
995     grow( _max+1 );
996 
997   // Find a precedence edge to move
998   uint i = _cnt;
999   while( in(i) != NULL ) {
1000     if (in(i) == n) return; // Avoid spec violation: duplicated prec edge.
1001     i++;
1002   }
1003   _in[i] = n;                                // Stuff prec edge over NULL
1004   if ( n != NULL) n->add_out((Node *)this);  // Add mirror edge
1005 
1006 #ifdef ASSERT
1007   while ((++i)<_max) { assert(_in[i] == NULL, "spec violation: Gap in prec edges (node %d)", _idx); }
1008 #endif
1009 }
1010 
1011 //------------------------------rm_prec----------------------------------------
1012 // Remove a precedence input.  Precedence inputs are unordered, with
1013 // duplicates removed and NULLs packed down at the end.
rm_prec(uint j)1014 void Node::rm_prec( uint j ) {
1015   assert(j < _max, "oob: i=%d, _max=%d", j, _max);
1016   assert(j >= _cnt, "not a precedence edge");
1017   if (_in[j] == NULL) return;   // Avoid spec violation: Gap in prec edges.
1018   _in[j]->del_out((Node *)this);
1019   close_prec_gap_at(j);
1020 }
1021 
1022 //------------------------------size_of----------------------------------------
size_of() const1023 uint Node::size_of() const { return sizeof(*this); }
1024 
1025 //------------------------------ideal_reg--------------------------------------
ideal_reg() const1026 uint Node::ideal_reg() const { return 0; }
1027 
1028 //------------------------------jvms-------------------------------------------
jvms() const1029 JVMState* Node::jvms() const { return NULL; }
1030 
1031 #ifdef ASSERT
1032 //------------------------------jvms-------------------------------------------
verify_jvms(const JVMState * using_jvms) const1033 bool Node::verify_jvms(const JVMState* using_jvms) const {
1034   for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
1035     if (jvms == using_jvms)  return true;
1036   }
1037   return false;
1038 }
1039 
1040 //------------------------------init_NodeProperty------------------------------
init_NodeProperty()1041 void Node::init_NodeProperty() {
1042   assert(_max_classes <= max_jushort, "too many NodeProperty classes");
1043   assert(max_flags() <= max_jushort, "too many NodeProperty flags");
1044 }
1045 
1046 //-----------------------------max_flags---------------------------------------
max_flags()1047 juint Node::max_flags() {
1048   return (PD::_last_flag << 1) - 1; // allow flags combination
1049 }
1050 #endif
1051 
1052 //------------------------------format-----------------------------------------
1053 // Print as assembly
format(PhaseRegAlloc *,outputStream * st) const1054 void Node::format( PhaseRegAlloc *, outputStream *st ) const {}
1055 //------------------------------emit-------------------------------------------
1056 // Emit bytes starting at parameter 'ptr'.
emit(CodeBuffer & cbuf,PhaseRegAlloc * ra_) const1057 void Node::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {}
1058 //------------------------------size-------------------------------------------
1059 // Size of instruction in bytes
size(PhaseRegAlloc * ra_) const1060 uint Node::size(PhaseRegAlloc *ra_) const { return 0; }
1061 
1062 //------------------------------CFG Construction-------------------------------
1063 // Nodes that end basic blocks, e.g. IfTrue/IfFalse, JumpProjNode, Root,
1064 // Goto and Return.
is_block_proj() const1065 const Node *Node::is_block_proj() const { return 0; }
1066 
1067 // Minimum guaranteed type
bottom_type() const1068 const Type *Node::bottom_type() const { return Type::BOTTOM; }
1069 
1070 
1071 //------------------------------raise_bottom_type------------------------------
1072 // Get the worst-case Type output for this Node.
raise_bottom_type(const Type * new_type)1073 void Node::raise_bottom_type(const Type* new_type) {
1074   if (is_Type()) {
1075     TypeNode *n = this->as_Type();
1076     if (VerifyAliases) {
1077       assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1078     }
1079     n->set_type(new_type);
1080   } else if (is_Load()) {
1081     LoadNode *n = this->as_Load();
1082     if (VerifyAliases) {
1083       assert(new_type->higher_equal_speculative(n->type()), "new type must refine old type");
1084     }
1085     n->set_type(new_type);
1086   }
1087 }
1088 
1089 //------------------------------Identity---------------------------------------
1090 // Return a node that the given node is equivalent to.
Identity(PhaseGVN * phase)1091 Node* Node::Identity(PhaseGVN* phase) {
1092   return this;                  // Default to no identities
1093 }
1094 
1095 //------------------------------Value------------------------------------------
1096 // Compute a new Type for a node using the Type of the inputs.
Value(PhaseGVN * phase) const1097 const Type* Node::Value(PhaseGVN* phase) const {
1098   return bottom_type();         // Default to worst-case Type
1099 }
1100 
1101 //------------------------------Ideal------------------------------------------
1102 //
1103 // 'Idealize' the graph rooted at this Node.
1104 //
1105 // In order to be efficient and flexible there are some subtle invariants
1106 // these Ideal calls need to hold.  Running with '+VerifyIterativeGVN' checks
1107 // these invariants, although its too slow to have on by default.  If you are
1108 // hacking an Ideal call, be sure to test with +VerifyIterativeGVN!
1109 //
1110 // The Ideal call almost arbitrarily reshape the graph rooted at the 'this'
1111 // pointer.  If ANY change is made, it must return the root of the reshaped
1112 // graph - even if the root is the same Node.  Example: swapping the inputs
1113 // to an AddINode gives the same answer and same root, but you still have to
1114 // return the 'this' pointer instead of NULL.
1115 //
1116 // You cannot return an OLD Node, except for the 'this' pointer.  Use the
1117 // Identity call to return an old Node; basically if Identity can find
1118 // another Node have the Ideal call make no change and return NULL.
1119 // Example: AddINode::Ideal must check for add of zero; in this case it
1120 // returns NULL instead of doing any graph reshaping.
1121 //
1122 // You cannot modify any old Nodes except for the 'this' pointer.  Due to
1123 // sharing there may be other users of the old Nodes relying on their current
1124 // semantics.  Modifying them will break the other users.
1125 // Example: when reshape "(X+3)+4" into "X+7" you must leave the Node for
1126 // "X+3" unchanged in case it is shared.
1127 //
1128 // If you modify the 'this' pointer's inputs, you should use
1129 // 'set_req'.  If you are making a new Node (either as the new root or
1130 // some new internal piece) you may use 'init_req' to set the initial
1131 // value.  You can make a new Node with either 'new' or 'clone'.  In
1132 // either case, def-use info is correctly maintained.
1133 //
1134 // Example: reshape "(X+3)+4" into "X+7":
1135 //    set_req(1, in(1)->in(1));
1136 //    set_req(2, phase->intcon(7));
1137 //    return this;
1138 // Example: reshape "X*4" into "X<<2"
1139 //    return new LShiftINode(in(1), phase->intcon(2));
1140 //
1141 // You must call 'phase->transform(X)' on any new Nodes X you make, except
1142 // for the returned root node.  Example: reshape "X*31" with "(X<<5)-X".
1143 //    Node *shift=phase->transform(new LShiftINode(in(1),phase->intcon(5)));
1144 //    return new AddINode(shift, in(1));
1145 //
1146 // When making a Node for a constant use 'phase->makecon' or 'phase->intcon'.
1147 // These forms are faster than 'phase->transform(new ConNode())' and Do
1148 // The Right Thing with def-use info.
1149 //
1150 // You cannot bury the 'this' Node inside of a graph reshape.  If the reshaped
1151 // graph uses the 'this' Node it must be the root.  If you want a Node with
1152 // the same Opcode as the 'this' pointer use 'clone'.
1153 //
Ideal(PhaseGVN * phase,bool can_reshape)1154 Node *Node::Ideal(PhaseGVN *phase, bool can_reshape) {
1155   return NULL;                  // Default to being Ideal already
1156 }
1157 
1158 // Some nodes have specific Ideal subgraph transformations only if they are
1159 // unique users of specific nodes. Such nodes should be put on IGVN worklist
1160 // for the transformations to happen.
has_special_unique_user() const1161 bool Node::has_special_unique_user() const {
1162   assert(outcnt() == 1, "match only for unique out");
1163   Node* n = unique_out();
1164   int op  = Opcode();
1165   if (this->is_Store()) {
1166     // Condition for back-to-back stores folding.
1167     return n->Opcode() == op && n->in(MemNode::Memory) == this;
1168   } else if (this->is_Load() || this->is_DecodeN() || this->is_Phi()) {
1169     // Condition for removing an unused LoadNode or DecodeNNode from the MemBarAcquire precedence input
1170     return n->Opcode() == Op_MemBarAcquire;
1171   } else if (op == Op_AddL) {
1172     // Condition for convL2I(addL(x,y)) ==> addI(convL2I(x),convL2I(y))
1173     return n->Opcode() == Op_ConvL2I && n->in(1) == this;
1174   } else if (op == Op_SubI || op == Op_SubL) {
1175     // Condition for subI(x,subI(y,z)) ==> subI(addI(x,z),y)
1176     return n->Opcode() == op && n->in(2) == this;
1177   } else if (is_If() && (n->is_IfFalse() || n->is_IfTrue())) {
1178     // See IfProjNode::Identity()
1179     return true;
1180   } else {
1181     return false;
1182   }
1183 };
1184 
1185 //--------------------------find_exact_control---------------------------------
1186 // Skip Proj and CatchProj nodes chains. Check for Null and Top.
find_exact_control(Node * ctrl)1187 Node* Node::find_exact_control(Node* ctrl) {
1188   if (ctrl == NULL && this->is_Region())
1189     ctrl = this->as_Region()->is_copy();
1190 
1191   if (ctrl != NULL && ctrl->is_CatchProj()) {
1192     if (ctrl->as_CatchProj()->_con == CatchProjNode::fall_through_index)
1193       ctrl = ctrl->in(0);
1194     if (ctrl != NULL && !ctrl->is_top())
1195       ctrl = ctrl->in(0);
1196   }
1197 
1198   if (ctrl != NULL && ctrl->is_Proj())
1199     ctrl = ctrl->in(0);
1200 
1201   return ctrl;
1202 }
1203 
1204 //--------------------------dominates------------------------------------------
1205 // Helper function for MemNode::all_controls_dominate().
1206 // Check if 'this' control node dominates or equal to 'sub' control node.
1207 // We already know that if any path back to Root or Start reaches 'this',
1208 // then all paths so, so this is a simple search for one example,
1209 // not an exhaustive search for a counterexample.
dominates(Node * sub,Node_List & nlist)1210 bool Node::dominates(Node* sub, Node_List &nlist) {
1211   assert(this->is_CFG(), "expecting control");
1212   assert(sub != NULL && sub->is_CFG(), "expecting control");
1213 
1214   // detect dead cycle without regions
1215   int iterations_without_region_limit = DominatorSearchLimit;
1216 
1217   Node* orig_sub = sub;
1218   Node* dom      = this;
1219   bool  met_dom  = false;
1220   nlist.clear();
1221 
1222   // Walk 'sub' backward up the chain to 'dom', watching for regions.
1223   // After seeing 'dom', continue up to Root or Start.
1224   // If we hit a region (backward split point), it may be a loop head.
1225   // Keep going through one of the region's inputs.  If we reach the
1226   // same region again, go through a different input.  Eventually we
1227   // will either exit through the loop head, or give up.
1228   // (If we get confused, break out and return a conservative 'false'.)
1229   while (sub != NULL) {
1230     if (sub->is_top())  break; // Conservative answer for dead code.
1231     if (sub == dom) {
1232       if (nlist.size() == 0) {
1233         // No Region nodes except loops were visited before and the EntryControl
1234         // path was taken for loops: it did not walk in a cycle.
1235         return true;
1236       } else if (met_dom) {
1237         break;          // already met before: walk in a cycle
1238       } else {
1239         // Region nodes were visited. Continue walk up to Start or Root
1240         // to make sure that it did not walk in a cycle.
1241         met_dom = true; // first time meet
1242         iterations_without_region_limit = DominatorSearchLimit; // Reset
1243      }
1244     }
1245     if (sub->is_Start() || sub->is_Root()) {
1246       // Success if we met 'dom' along a path to Start or Root.
1247       // We assume there are no alternative paths that avoid 'dom'.
1248       // (This assumption is up to the caller to ensure!)
1249       return met_dom;
1250     }
1251     Node* up = sub->in(0);
1252     // Normalize simple pass-through regions and projections:
1253     up = sub->find_exact_control(up);
1254     // If sub == up, we found a self-loop.  Try to push past it.
1255     if (sub == up && sub->is_Loop()) {
1256       // Take loop entry path on the way up to 'dom'.
1257       up = sub->in(1); // in(LoopNode::EntryControl);
1258     } else if (sub == up && sub->is_Region() && sub->req() == 2) {
1259       // Take in(1) path on the way up to 'dom' for regions with only one input
1260       up = sub->in(1);
1261     } else if (sub == up && sub->is_Region() && sub->req() == 3) {
1262       // Try both paths for Regions with 2 input paths (it may be a loop head).
1263       // It could give conservative 'false' answer without information
1264       // which region's input is the entry path.
1265       iterations_without_region_limit = DominatorSearchLimit; // Reset
1266 
1267       bool region_was_visited_before = false;
1268       // Was this Region node visited before?
1269       // If so, we have reached it because we accidentally took a
1270       // loop-back edge from 'sub' back into the body of the loop,
1271       // and worked our way up again to the loop header 'sub'.
1272       // So, take the first unexplored path on the way up to 'dom'.
1273       for (int j = nlist.size() - 1; j >= 0; j--) {
1274         intptr_t ni = (intptr_t)nlist.at(j);
1275         Node* visited = (Node*)(ni & ~1);
1276         bool  visited_twice_already = ((ni & 1) != 0);
1277         if (visited == sub) {
1278           if (visited_twice_already) {
1279             // Visited 2 paths, but still stuck in loop body.  Give up.
1280             return false;
1281           }
1282           // The Region node was visited before only once.
1283           // (We will repush with the low bit set, below.)
1284           nlist.remove(j);
1285           // We will find a new edge and re-insert.
1286           region_was_visited_before = true;
1287           break;
1288         }
1289       }
1290 
1291       // Find an incoming edge which has not been seen yet; walk through it.
1292       assert(up == sub, "");
1293       uint skip = region_was_visited_before ? 1 : 0;
1294       for (uint i = 1; i < sub->req(); i++) {
1295         Node* in = sub->in(i);
1296         if (in != NULL && !in->is_top() && in != sub) {
1297           if (skip == 0) {
1298             up = in;
1299             break;
1300           }
1301           --skip;               // skip this nontrivial input
1302         }
1303       }
1304 
1305       // Set 0 bit to indicate that both paths were taken.
1306       nlist.push((Node*)((intptr_t)sub + (region_was_visited_before ? 1 : 0)));
1307     }
1308 
1309     if (up == sub) {
1310       break;    // some kind of tight cycle
1311     }
1312     if (up == orig_sub && met_dom) {
1313       // returned back after visiting 'dom'
1314       break;    // some kind of cycle
1315     }
1316     if (--iterations_without_region_limit < 0) {
1317       break;    // dead cycle
1318     }
1319     sub = up;
1320   }
1321 
1322   // Did not meet Root or Start node in pred. chain.
1323   // Conservative answer for dead code.
1324   return false;
1325 }
1326 
1327 //------------------------------remove_dead_region-----------------------------
1328 // This control node is dead.  Follow the subgraph below it making everything
1329 // using it dead as well.  This will happen normally via the usual IterGVN
1330 // worklist but this call is more efficient.  Do not update use-def info
1331 // inside the dead region, just at the borders.
kill_dead_code(Node * dead,PhaseIterGVN * igvn)1332 static void kill_dead_code( Node *dead, PhaseIterGVN *igvn ) {
1333   // Con's are a popular node to re-hit in the hash table again.
1334   if( dead->is_Con() ) return;
1335 
1336   ResourceMark rm;
1337   Node_List  nstack(Thread::current()->resource_area());
1338 
1339   Node *top = igvn->C->top();
1340   nstack.push(dead);
1341   bool has_irreducible_loop = igvn->C->has_irreducible_loop();
1342 
1343   while (nstack.size() > 0) {
1344     dead = nstack.pop();
1345     if (dead->Opcode() == Op_SafePoint) {
1346       dead->as_SafePoint()->disconnect_from_root(igvn);
1347     }
1348     if (dead->outcnt() > 0) {
1349       // Keep dead node on stack until all uses are processed.
1350       nstack.push(dead);
1351       // For all Users of the Dead...    ;-)
1352       for (DUIterator_Last kmin, k = dead->last_outs(kmin); k >= kmin; ) {
1353         Node* use = dead->last_out(k);
1354         igvn->hash_delete(use);       // Yank from hash table prior to mod
1355         if (use->in(0) == dead) {     // Found another dead node
1356           assert (!use->is_Con(), "Control for Con node should be Root node.");
1357           use->set_req(0, top);       // Cut dead edge to prevent processing
1358           nstack.push(use);           // the dead node again.
1359         } else if (!has_irreducible_loop && // Backedge could be alive in irreducible loop
1360                    use->is_Loop() && !use->is_Root() &&       // Don't kill Root (RootNode extends LoopNode)
1361                    use->in(LoopNode::EntryControl) == dead) { // Dead loop if its entry is dead
1362           use->set_req(LoopNode::EntryControl, top);          // Cut dead edge to prevent processing
1363           use->set_req(0, top);       // Cut self edge
1364           nstack.push(use);
1365         } else {                      // Else found a not-dead user
1366           // Dead if all inputs are top or null
1367           bool dead_use = !use->is_Root(); // Keep empty graph alive
1368           for (uint j = 1; j < use->req(); j++) {
1369             Node* in = use->in(j);
1370             if (in == dead) {         // Turn all dead inputs into TOP
1371               use->set_req(j, top);
1372             } else if (in != NULL && !in->is_top()) {
1373               dead_use = false;
1374             }
1375           }
1376           if (dead_use) {
1377             if (use->is_Region()) {
1378               use->set_req(0, top);   // Cut self edge
1379             }
1380             nstack.push(use);
1381           } else {
1382             igvn->_worklist.push(use);
1383           }
1384         }
1385         // Refresh the iterator, since any number of kills might have happened.
1386         k = dead->last_outs(kmin);
1387       }
1388     } else { // (dead->outcnt() == 0)
1389       // Done with outputs.
1390       igvn->hash_delete(dead);
1391       igvn->_worklist.remove(dead);
1392       igvn->C->remove_modified_node(dead);
1393       igvn->set_type(dead, Type::TOP);
1394       if (dead->is_macro()) {
1395         igvn->C->remove_macro_node(dead);
1396       }
1397       if (dead->is_expensive()) {
1398         igvn->C->remove_expensive_node(dead);
1399       }
1400       CastIINode* cast = dead->isa_CastII();
1401       if (cast != NULL && cast->has_range_check()) {
1402         igvn->C->remove_range_check_cast(cast);
1403       }
1404       if (dead->Opcode() == Op_Opaque4) {
1405         igvn->C->remove_opaque4_node(dead);
1406       }
1407       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1408       bs->unregister_potential_barrier_node(dead);
1409       igvn->C->record_dead_node(dead->_idx);
1410       // Kill all inputs to the dead guy
1411       for (uint i=0; i < dead->req(); i++) {
1412         Node *n = dead->in(i);      // Get input to dead guy
1413         if (n != NULL && !n->is_top()) { // Input is valid?
1414           dead->set_req(i, top);    // Smash input away
1415           if (n->outcnt() == 0) {   // Input also goes dead?
1416             if (!n->is_Con())
1417               nstack.push(n);       // Clear it out as well
1418           } else if (n->outcnt() == 1 &&
1419                      n->has_special_unique_user()) {
1420             igvn->add_users_to_worklist( n );
1421           } else if (n->outcnt() <= 2 && n->is_Store()) {
1422             // Push store's uses on worklist to enable folding optimization for
1423             // store/store and store/load to the same address.
1424             // The restriction (outcnt() <= 2) is the same as in set_req_X()
1425             // and remove_globally_dead_node().
1426             igvn->add_users_to_worklist( n );
1427           } else {
1428             BarrierSet::barrier_set()->barrier_set_c2()->enqueue_useful_gc_barrier(igvn, n);
1429           }
1430         }
1431       }
1432     } // (dead->outcnt() == 0)
1433   }   // while (nstack.size() > 0) for outputs
1434   return;
1435 }
1436 
1437 //------------------------------remove_dead_region-----------------------------
remove_dead_region(PhaseGVN * phase,bool can_reshape)1438 bool Node::remove_dead_region(PhaseGVN *phase, bool can_reshape) {
1439   Node *n = in(0);
1440   if( !n ) return false;
1441   // Lost control into this guy?  I.e., it became unreachable?
1442   // Aggressively kill all unreachable code.
1443   if (can_reshape && n->is_top()) {
1444     kill_dead_code(this, phase->is_IterGVN());
1445     return false; // Node is dead.
1446   }
1447 
1448   if( n->is_Region() && n->as_Region()->is_copy() ) {
1449     Node *m = n->nonnull_req();
1450     set_req(0, m);
1451     return true;
1452   }
1453   return false;
1454 }
1455 
1456 //------------------------------hash-------------------------------------------
1457 // Hash function over Nodes.
hash() const1458 uint Node::hash() const {
1459   uint sum = 0;
1460   for( uint i=0; i<_cnt; i++ )  // Add in all inputs
1461     sum = (sum<<1)-(uintptr_t)in(i);        // Ignore embedded NULLs
1462   return (sum>>2) + _cnt + Opcode();
1463 }
1464 
1465 //------------------------------cmp--------------------------------------------
1466 // Compare special parts of simple Nodes
cmp(const Node & n) const1467 bool Node::cmp( const Node &n ) const {
1468   return true;                  // Must be same
1469 }
1470 
1471 //------------------------------rematerialize-----------------------------------
1472 // Should we clone rather than spill this instruction?
rematerialize() const1473 bool Node::rematerialize() const {
1474   if ( is_Mach() )
1475     return this->as_Mach()->rematerialize();
1476   else
1477     return (_flags & Flag_rematerialize) != 0;
1478 }
1479 
1480 //------------------------------needs_anti_dependence_check---------------------
1481 // Nodes which use memory without consuming it, hence need antidependences.
needs_anti_dependence_check() const1482 bool Node::needs_anti_dependence_check() const {
1483   if (req() < 2 || (_flags & Flag_needs_anti_dependence_check) == 0) {
1484     return false;
1485   }
1486   return in(1)->bottom_type()->has_memory();
1487 }
1488 
1489 // Get an integer constant from a ConNode (or CastIINode).
1490 // Return a default value if there is no apparent constant here.
find_int_type() const1491 const TypeInt* Node::find_int_type() const {
1492   if (this->is_Type()) {
1493     return this->as_Type()->type()->isa_int();
1494   } else if (this->is_Con()) {
1495     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1496     return this->bottom_type()->isa_int();
1497   }
1498   return NULL;
1499 }
1500 
1501 // Get a pointer constant from a ConstNode.
1502 // Returns the constant if it is a pointer ConstNode
get_ptr() const1503 intptr_t Node::get_ptr() const {
1504   assert( Opcode() == Op_ConP, "" );
1505   return ((ConPNode*)this)->type()->is_ptr()->get_con();
1506 }
1507 
1508 // Get a narrow oop constant from a ConNNode.
get_narrowcon() const1509 intptr_t Node::get_narrowcon() const {
1510   assert( Opcode() == Op_ConN, "" );
1511   return ((ConNNode*)this)->type()->is_narrowoop()->get_con();
1512 }
1513 
1514 // Get a long constant from a ConNode.
1515 // Return a default value if there is no apparent constant here.
find_long_type() const1516 const TypeLong* Node::find_long_type() const {
1517   if (this->is_Type()) {
1518     return this->as_Type()->type()->isa_long();
1519   } else if (this->is_Con()) {
1520     assert(is_Mach(), "should be ConNode(TypeNode) or else a MachNode");
1521     return this->bottom_type()->isa_long();
1522   }
1523   return NULL;
1524 }
1525 
1526 
1527 /**
1528  * Return a ptr type for nodes which should have it.
1529  */
get_ptr_type() const1530 const TypePtr* Node::get_ptr_type() const {
1531   const TypePtr* tp = this->bottom_type()->make_ptr();
1532 #ifdef ASSERT
1533   if (tp == NULL) {
1534     this->dump(1);
1535     assert((tp != NULL), "unexpected node type");
1536   }
1537 #endif
1538   return tp;
1539 }
1540 
1541 // Get a double constant from a ConstNode.
1542 // Returns the constant if it is a double ConstNode
getd() const1543 jdouble Node::getd() const {
1544   assert( Opcode() == Op_ConD, "" );
1545   return ((ConDNode*)this)->type()->is_double_constant()->getd();
1546 }
1547 
1548 // Get a float constant from a ConstNode.
1549 // Returns the constant if it is a float ConstNode
getf() const1550 jfloat Node::getf() const {
1551   assert( Opcode() == Op_ConF, "" );
1552   return ((ConFNode*)this)->type()->is_float_constant()->getf();
1553 }
1554 
1555 #ifndef PRODUCT
1556 
1557 //------------------------------find------------------------------------------
1558 // Find a neighbor of this Node with the given _idx
1559 // If idx is negative, find its absolute value, following both _in and _out.
find_recur(Compile * C,Node * & result,Node * n,int idx,bool only_ctrl,VectorSet * old_space,VectorSet * new_space)1560 static void find_recur(Compile* C,  Node* &result, Node *n, int idx, bool only_ctrl,
1561                         VectorSet* old_space, VectorSet* new_space ) {
1562   int node_idx = (idx >= 0) ? idx : -idx;
1563   if (NotANode(n))  return;  // Gracefully handle NULL, -1, 0xabababab, etc.
1564   // Contained in new_space or old_space?   Check old_arena first since it's mostly empty.
1565   VectorSet *v = C->old_arena()->contains(n) ? old_space : new_space;
1566   if( v->test(n->_idx) ) return;
1567   if( (int)n->_idx == node_idx
1568       debug_only(|| n->debug_idx() == node_idx) ) {
1569     if (result != NULL)
1570       tty->print("find: " INTPTR_FORMAT " and " INTPTR_FORMAT " both have idx==%d\n",
1571                  (uintptr_t)result, (uintptr_t)n, node_idx);
1572     result = n;
1573   }
1574   v->set(n->_idx);
1575   for( uint i=0; i<n->len(); i++ ) {
1576     if( only_ctrl && !(n->is_Region()) && (n->Opcode() != Op_Root) && (i != TypeFunc::Control) ) continue;
1577     find_recur(C, result, n->in(i), idx, only_ctrl, old_space, new_space );
1578   }
1579   // Search along forward edges also:
1580   if (idx < 0 && !only_ctrl) {
1581     for( uint j=0; j<n->outcnt(); j++ ) {
1582       find_recur(C, result, n->raw_out(j), idx, only_ctrl, old_space, new_space );
1583     }
1584   }
1585 #ifdef ASSERT
1586   // Search along debug_orig edges last, checking for cycles
1587   Node* orig = n->debug_orig();
1588   if (orig != NULL) {
1589     do {
1590       if (NotANode(orig))  break;
1591       find_recur(C, result, orig, idx, only_ctrl, old_space, new_space );
1592       orig = orig->debug_orig();
1593     } while (orig != NULL && orig != n->debug_orig());
1594   }
1595 #endif //ASSERT
1596 }
1597 
1598 // call this from debugger:
find_node(Node * n,int idx)1599 Node* find_node(Node* n, int idx) {
1600   return n->find(idx);
1601 }
1602 
1603 // call this from debugger with root node as default:
find_node(int idx)1604 Node* find_node(int idx) {
1605   return Compile::current()->root()->find(idx);
1606 }
1607 
1608 //------------------------------find-------------------------------------------
find(int idx) const1609 Node* Node::find(int idx) const {
1610   ResourceArea *area = Thread::current()->resource_area();
1611   VectorSet old_space(area), new_space(area);
1612   Node* result = NULL;
1613   find_recur(Compile::current(), result, (Node*) this, idx, false, &old_space, &new_space );
1614   return result;
1615 }
1616 
1617 //------------------------------find_ctrl--------------------------------------
1618 // Find an ancestor to this node in the control history with given _idx
find_ctrl(int idx) const1619 Node* Node::find_ctrl(int idx) const {
1620   ResourceArea *area = Thread::current()->resource_area();
1621   VectorSet old_space(area), new_space(area);
1622   Node* result = NULL;
1623   find_recur(Compile::current(), result, (Node*) this, idx, true, &old_space, &new_space );
1624   return result;
1625 }
1626 #endif
1627 
1628 
1629 
1630 #ifndef PRODUCT
1631 
1632 // -----------------------------Name-------------------------------------------
1633 extern const char *NodeClassNames[];
Name() const1634 const char *Node::Name() const { return NodeClassNames[Opcode()]; }
1635 
is_disconnected(const Node * n)1636 static bool is_disconnected(const Node* n) {
1637   for (uint i = 0; i < n->req(); i++) {
1638     if (n->in(i) != NULL)  return false;
1639   }
1640   return true;
1641 }
1642 
1643 #ifdef ASSERT
dump_orig(outputStream * st,bool print_key) const1644 void Node::dump_orig(outputStream *st, bool print_key) const {
1645   Compile* C = Compile::current();
1646   Node* orig = _debug_orig;
1647   if (NotANode(orig)) orig = NULL;
1648   if (orig != NULL && !C->node_arena()->contains(orig)) orig = NULL;
1649   if (orig == NULL) return;
1650   if (print_key) {
1651     st->print(" !orig=");
1652   }
1653   Node* fast = orig->debug_orig(); // tortoise & hare algorithm to detect loops
1654   if (NotANode(fast)) fast = NULL;
1655   while (orig != NULL) {
1656     bool discon = is_disconnected(orig);  // if discon, print [123] else 123
1657     if (discon) st->print("[");
1658     if (!Compile::current()->node_arena()->contains(orig))
1659       st->print("o");
1660     st->print("%d", orig->_idx);
1661     if (discon) st->print("]");
1662     orig = orig->debug_orig();
1663     if (NotANode(orig)) orig = NULL;
1664     if (orig != NULL && !C->node_arena()->contains(orig)) orig = NULL;
1665     if (orig != NULL) st->print(",");
1666     if (fast != NULL) {
1667       // Step fast twice for each single step of orig:
1668       fast = fast->debug_orig();
1669       if (NotANode(fast)) fast = NULL;
1670       if (fast != NULL && fast != orig) {
1671         fast = fast->debug_orig();
1672         if (NotANode(fast)) fast = NULL;
1673       }
1674       if (fast == orig) {
1675         st->print("...");
1676         break;
1677       }
1678     }
1679   }
1680 }
1681 
set_debug_orig(Node * orig)1682 void Node::set_debug_orig(Node* orig) {
1683   _debug_orig = orig;
1684   if (BreakAtNode == 0)  return;
1685   if (NotANode(orig))  orig = NULL;
1686   int trip = 10;
1687   while (orig != NULL) {
1688     if (orig->debug_idx() == BreakAtNode || (int)orig->_idx == BreakAtNode) {
1689       tty->print_cr("BreakAtNode: _idx=%d _debug_idx=%d orig._idx=%d orig._debug_idx=%d",
1690                     this->_idx, this->debug_idx(), orig->_idx, orig->debug_idx());
1691       BREAKPOINT;
1692     }
1693     orig = orig->debug_orig();
1694     if (NotANode(orig))  orig = NULL;
1695     if (trip-- <= 0)  break;
1696   }
1697 }
1698 #endif //ASSERT
1699 
1700 //------------------------------dump------------------------------------------
1701 // Dump a Node
dump(const char * suffix,bool mark,outputStream * st) const1702 void Node::dump(const char* suffix, bool mark, outputStream *st) const {
1703   Compile* C = Compile::current();
1704   bool is_new = C->node_arena()->contains(this);
1705   C->_in_dump_cnt++;
1706   st->print("%c%d%s\t%s\t=== ", is_new ? ' ' : 'o', _idx, mark ? " >" : "", Name());
1707 
1708   // Dump the required and precedence inputs
1709   dump_req(st);
1710   dump_prec(st);
1711   // Dump the outputs
1712   dump_out(st);
1713 
1714   if (is_disconnected(this)) {
1715 #ifdef ASSERT
1716     st->print("  [%d]",debug_idx());
1717     dump_orig(st);
1718 #endif
1719     st->cr();
1720     C->_in_dump_cnt--;
1721     return;                     // don't process dead nodes
1722   }
1723 
1724   if (C->clone_map().value(_idx) != 0) {
1725     C->clone_map().dump(_idx);
1726   }
1727   // Dump node-specific info
1728   dump_spec(st);
1729 #ifdef ASSERT
1730   // Dump the non-reset _debug_idx
1731   if (Verbose && WizardMode) {
1732     st->print("  [%d]",debug_idx());
1733   }
1734 #endif
1735 
1736   const Type *t = bottom_type();
1737 
1738   if (t != NULL && (t->isa_instptr() || t->isa_klassptr())) {
1739     const TypeInstPtr  *toop = t->isa_instptr();
1740     const TypeKlassPtr *tkls = t->isa_klassptr();
1741     ciKlass*           klass = toop ? toop->klass() : (tkls ? tkls->klass() : NULL );
1742     if (klass && klass->is_loaded() && klass->is_interface()) {
1743       st->print("  Interface:");
1744     } else if (toop) {
1745       st->print("  Oop:");
1746     } else if (tkls) {
1747       st->print("  Klass:");
1748     }
1749     t->dump_on(st);
1750   } else if (t == Type::MEMORY) {
1751     st->print("  Memory:");
1752     MemNode::dump_adr_type(this, adr_type(), st);
1753   } else if (Verbose || WizardMode) {
1754     st->print("  Type:");
1755     if (t) {
1756       t->dump_on(st);
1757     } else {
1758       st->print("no type");
1759     }
1760   } else if (t->isa_vect() && this->is_MachSpillCopy()) {
1761     // Dump MachSpillcopy vector type.
1762     t->dump_on(st);
1763   }
1764   if (is_new) {
1765     DEBUG_ONLY(dump_orig(st));
1766     Node_Notes* nn = C->node_notes_at(_idx);
1767     if (nn != NULL && !nn->is_clear()) {
1768       if (nn->jvms() != NULL) {
1769         st->print(" !jvms:");
1770         nn->jvms()->dump_spec(st);
1771       }
1772     }
1773   }
1774   if (suffix) st->print("%s", suffix);
1775   C->_in_dump_cnt--;
1776 }
1777 
1778 //------------------------------dump_req--------------------------------------
dump_req(outputStream * st) const1779 void Node::dump_req(outputStream *st) const {
1780   // Dump the required input edges
1781   for (uint i = 0; i < req(); i++) {    // For all required inputs
1782     Node* d = in(i);
1783     if (d == NULL) {
1784       st->print("_ ");
1785     } else if (NotANode(d)) {
1786       st->print("NotANode ");  // uninitialized, sentinel, garbage, etc.
1787     } else {
1788       st->print("%c%d ", Compile::current()->node_arena()->contains(d) ? ' ' : 'o', d->_idx);
1789     }
1790   }
1791 }
1792 
1793 
1794 //------------------------------dump_prec-------------------------------------
dump_prec(outputStream * st) const1795 void Node::dump_prec(outputStream *st) const {
1796   // Dump the precedence edges
1797   int any_prec = 0;
1798   for (uint i = req(); i < len(); i++) {       // For all precedence inputs
1799     Node* p = in(i);
1800     if (p != NULL) {
1801       if (!any_prec++) st->print(" |");
1802       if (NotANode(p)) { st->print("NotANode "); continue; }
1803       st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
1804     }
1805   }
1806 }
1807 
1808 //------------------------------dump_out--------------------------------------
dump_out(outputStream * st) const1809 void Node::dump_out(outputStream *st) const {
1810   // Delimit the output edges
1811   st->print(" [[");
1812   // Dump the output edges
1813   for (uint i = 0; i < _outcnt; i++) {    // For all outputs
1814     Node* u = _out[i];
1815     if (u == NULL) {
1816       st->print("_ ");
1817     } else if (NotANode(u)) {
1818       st->print("NotANode ");
1819     } else {
1820       st->print("%c%d ", Compile::current()->node_arena()->contains(u) ? ' ' : 'o', u->_idx);
1821     }
1822   }
1823   st->print("]] ");
1824 }
1825 
1826 //----------------------------collect_nodes_i----------------------------------
1827 // Collects nodes from an Ideal graph, starting from a given start node and
1828 // moving in a given direction until a certain depth (distance from the start
1829 // node) is reached. Duplicates are ignored.
1830 // Arguments:
1831 //   nstack:        the nodes are collected into this array.
1832 //   start:         the node at which to start collecting.
1833 //   direction:     if this is a positive number, collect input nodes; if it is
1834 //                  a negative number, collect output nodes.
1835 //   depth:         collect nodes up to this distance from the start node.
1836 //   include_start: whether to include the start node in the result collection.
1837 //   only_ctrl:     whether to regard control edges only during traversal.
1838 //   only_data:     whether to regard data edges only during traversal.
collect_nodes_i(GrowableArray<Node * > * nstack,const Node * start,int direction,uint depth,bool include_start,bool only_ctrl,bool only_data)1839 static void collect_nodes_i(GrowableArray<Node*> *nstack, const Node* start, int direction, uint depth, bool include_start, bool only_ctrl, bool only_data) {
1840   Node* s = (Node*) start; // remove const
1841   nstack->append(s);
1842   int begin = 0;
1843   int end = 0;
1844   for(uint i = 0; i < depth; i++) {
1845     end = nstack->length();
1846     for(int j = begin; j < end; j++) {
1847       Node* tp  = nstack->at(j);
1848       uint limit = direction > 0 ? tp->len() : tp->outcnt();
1849       for(uint k = 0; k < limit; k++) {
1850         Node* n = direction > 0 ? tp->in(k) : tp->raw_out(k);
1851 
1852         if (NotANode(n))  continue;
1853         // do not recurse through top or the root (would reach unrelated stuff)
1854         if (n->is_Root() || n->is_top()) continue;
1855         if (only_ctrl && !n->is_CFG()) continue;
1856         if (only_data && n->is_CFG()) continue;
1857 
1858         bool on_stack = nstack->contains(n);
1859         if (!on_stack) {
1860           nstack->append(n);
1861         }
1862       }
1863     }
1864     begin = end;
1865   }
1866   if (!include_start) {
1867     nstack->remove(s);
1868   }
1869 }
1870 
1871 //------------------------------dump_nodes-------------------------------------
dump_nodes(const Node * start,int d,bool only_ctrl)1872 static void dump_nodes(const Node* start, int d, bool only_ctrl) {
1873   if (NotANode(start)) return;
1874 
1875   GrowableArray <Node *> nstack(Compile::current()->live_nodes());
1876   collect_nodes_i(&nstack, start, d, (uint) ABS(d), true, only_ctrl, false);
1877 
1878   int end = nstack.length();
1879   if (d > 0) {
1880     for(int j = end-1; j >= 0; j--) {
1881       nstack.at(j)->dump();
1882     }
1883   } else {
1884     for(int j = 0; j < end; j++) {
1885       nstack.at(j)->dump();
1886     }
1887   }
1888 }
1889 
1890 //------------------------------dump-------------------------------------------
dump(int d) const1891 void Node::dump(int d) const {
1892   dump_nodes(this, d, false);
1893 }
1894 
1895 //------------------------------dump_ctrl--------------------------------------
1896 // Dump a Node's control history to depth
dump_ctrl(int d) const1897 void Node::dump_ctrl(int d) const {
1898   dump_nodes(this, d, true);
1899 }
1900 
1901 //-----------------------------dump_compact------------------------------------
dump_comp() const1902 void Node::dump_comp() const {
1903   this->dump_comp("\n");
1904 }
1905 
1906 //-----------------------------dump_compact------------------------------------
1907 // Dump a Node in compact representation, i.e., just print its name and index.
1908 // Nodes can specify additional specifics to print in compact representation by
1909 // implementing dump_compact_spec.
dump_comp(const char * suffix,outputStream * st) const1910 void Node::dump_comp(const char* suffix, outputStream *st) const {
1911   Compile* C = Compile::current();
1912   C->_in_dump_cnt++;
1913   st->print("%s(%d)", Name(), _idx);
1914   this->dump_compact_spec(st);
1915   if (suffix) {
1916     st->print("%s", suffix);
1917   }
1918   C->_in_dump_cnt--;
1919 }
1920 
1921 //----------------------------dump_related-------------------------------------
1922 // Dump a Node's related nodes - the notion of "related" depends on the Node at
1923 // hand and is determined by the implementation of the virtual method rel.
dump_related() const1924 void Node::dump_related() const {
1925   Compile* C = Compile::current();
1926   GrowableArray <Node *> in_rel(C->unique());
1927   GrowableArray <Node *> out_rel(C->unique());
1928   this->related(&in_rel, &out_rel, false);
1929   for (int i = in_rel.length() - 1; i >= 0; i--) {
1930     in_rel.at(i)->dump();
1931   }
1932   this->dump("\n", true);
1933   for (int i = 0; i < out_rel.length(); i++) {
1934     out_rel.at(i)->dump();
1935   }
1936 }
1937 
1938 //----------------------------dump_related-------------------------------------
1939 // Dump a Node's related nodes up to a given depth (distance from the start
1940 // node).
1941 // Arguments:
1942 //   d_in:  depth for input nodes.
1943 //   d_out: depth for output nodes (note: this also is a positive number).
dump_related(uint d_in,uint d_out) const1944 void Node::dump_related(uint d_in, uint d_out) const {
1945   Compile* C = Compile::current();
1946   GrowableArray <Node *> in_rel(C->unique());
1947   GrowableArray <Node *> out_rel(C->unique());
1948 
1949   // call collect_nodes_i directly
1950   collect_nodes_i(&in_rel, this, 1, d_in, false, false, false);
1951   collect_nodes_i(&out_rel, this, -1, d_out, false, false, false);
1952 
1953   for (int i = in_rel.length() - 1; i >= 0; i--) {
1954     in_rel.at(i)->dump();
1955   }
1956   this->dump("\n", true);
1957   for (int i = 0; i < out_rel.length(); i++) {
1958     out_rel.at(i)->dump();
1959   }
1960 }
1961 
1962 //------------------------dump_related_compact---------------------------------
1963 // Dump a Node's related nodes in compact representation. The notion of
1964 // "related" depends on the Node at hand and is determined by the implementation
1965 // of the virtual method rel.
dump_related_compact() const1966 void Node::dump_related_compact() const {
1967   Compile* C = Compile::current();
1968   GrowableArray <Node *> in_rel(C->unique());
1969   GrowableArray <Node *> out_rel(C->unique());
1970   this->related(&in_rel, &out_rel, true);
1971   int n_in = in_rel.length();
1972   int n_out = out_rel.length();
1973 
1974   this->dump_comp(n_in == 0 ? "\n" : "  ");
1975   for (int i = 0; i < n_in; i++) {
1976     in_rel.at(i)->dump_comp(i == n_in - 1 ? "\n" : "  ");
1977   }
1978   for (int i = 0; i < n_out; i++) {
1979     out_rel.at(i)->dump_comp(i == n_out - 1 ? "\n" : "  ");
1980   }
1981 }
1982 
1983 //------------------------------related----------------------------------------
1984 // Collect a Node's related nodes. The default behaviour just collects the
1985 // inputs and outputs at depth 1, including both control and data flow edges,
1986 // regardless of whether the presentation is compact or not. For data nodes,
1987 // the default is to collect all data inputs (till level 1 if compact), and
1988 // outputs till level 1.
related(GrowableArray<Node * > * in_rel,GrowableArray<Node * > * out_rel,bool compact) const1989 void Node::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1990   if (this->is_CFG()) {
1991     collect_nodes_i(in_rel, this, 1, 1, false, false, false);
1992     collect_nodes_i(out_rel, this, -1, 1, false, false, false);
1993   } else {
1994     if (compact) {
1995       this->collect_nodes(in_rel, 1, false, true);
1996     } else {
1997       this->collect_nodes_in_all_data(in_rel, false);
1998     }
1999     this->collect_nodes(out_rel, -1, false, false);
2000   }
2001 }
2002 
2003 //---------------------------collect_nodes-------------------------------------
2004 // An entry point to the low-level node collection facility, to start from a
2005 // given node in the graph. The start node is by default not included in the
2006 // result.
2007 // Arguments:
2008 //   ns:   collect the nodes into this data structure.
2009 //   d:    the depth (distance from start node) to which nodes should be
2010 //         collected. A value >0 indicates input nodes, a value <0, output
2011 //         nodes.
2012 //   ctrl: include only control nodes.
2013 //   data: include only data nodes.
collect_nodes(GrowableArray<Node * > * ns,int d,bool ctrl,bool data) const2014 void Node::collect_nodes(GrowableArray<Node*> *ns, int d, bool ctrl, bool data) const {
2015   if (ctrl && data) {
2016     // ignore nonsensical combination
2017     return;
2018   }
2019   collect_nodes_i(ns, this, d, (uint) ABS(d), false, ctrl, data);
2020 }
2021 
2022 //--------------------------collect_nodes_in-----------------------------------
collect_nodes_in(Node * start,GrowableArray<Node * > * ns,bool primary_is_data,bool collect_secondary)2023 static void collect_nodes_in(Node* start, GrowableArray<Node*> *ns, bool primary_is_data, bool collect_secondary) {
2024   // The maximum depth is determined using a BFS that visits all primary (data
2025   // or control) inputs and increments the depth at each level.
2026   uint d_in = 0;
2027   GrowableArray<Node*> nodes(Compile::current()->unique());
2028   nodes.push(start);
2029   int nodes_at_current_level = 1;
2030   int n_idx = 0;
2031   while (nodes_at_current_level > 0) {
2032     // Add all primary inputs reachable from the current level to the list, and
2033     // increase the depth if there were any.
2034     int nodes_at_next_level = 0;
2035     bool nodes_added = false;
2036     while (nodes_at_current_level > 0) {
2037       nodes_at_current_level--;
2038       Node* current = nodes.at(n_idx++);
2039       for (uint i = 0; i < current->len(); i++) {
2040         Node* n = current->in(i);
2041         if (NotANode(n)) {
2042           continue;
2043         }
2044         if ((primary_is_data && n->is_CFG()) || (!primary_is_data && !n->is_CFG())) {
2045           continue;
2046         }
2047         if (!nodes.contains(n)) {
2048           nodes.push(n);
2049           nodes_added = true;
2050           nodes_at_next_level++;
2051         }
2052       }
2053     }
2054     if (nodes_added) {
2055       d_in++;
2056     }
2057     nodes_at_current_level = nodes_at_next_level;
2058   }
2059   start->collect_nodes(ns, d_in, !primary_is_data, primary_is_data);
2060   if (collect_secondary) {
2061     // Now, iterate over the secondary nodes in ns and add the respective
2062     // boundary reachable from them.
2063     GrowableArray<Node*> sns(Compile::current()->unique());
2064     for (GrowableArrayIterator<Node*> it = ns->begin(); it != ns->end(); ++it) {
2065       Node* n = *it;
2066       n->collect_nodes(&sns, 1, primary_is_data, !primary_is_data);
2067       for (GrowableArrayIterator<Node*> d = sns.begin(); d != sns.end(); ++d) {
2068         ns->append_if_missing(*d);
2069       }
2070       sns.clear();
2071     }
2072   }
2073 }
2074 
2075 //---------------------collect_nodes_in_all_data-------------------------------
2076 // Collect the entire data input graph. Include the control boundary if
2077 // requested.
2078 // Arguments:
2079 //   ns:   collect the nodes into this data structure.
2080 //   ctrl: if true, include the control boundary.
collect_nodes_in_all_data(GrowableArray<Node * > * ns,bool ctrl) const2081 void Node::collect_nodes_in_all_data(GrowableArray<Node*> *ns, bool ctrl) const {
2082   collect_nodes_in((Node*) this, ns, true, ctrl);
2083 }
2084 
2085 //--------------------------collect_nodes_in_all_ctrl--------------------------
2086 // Collect the entire control input graph. Include the data boundary if
2087 // requested.
2088 //   ns:   collect the nodes into this data structure.
2089 //   data: if true, include the control boundary.
collect_nodes_in_all_ctrl(GrowableArray<Node * > * ns,bool data) const2090 void Node::collect_nodes_in_all_ctrl(GrowableArray<Node*> *ns, bool data) const {
2091   collect_nodes_in((Node*) this, ns, false, data);
2092 }
2093 
2094 //------------------collect_nodes_out_all_ctrl_boundary------------------------
2095 // Collect the entire output graph until hitting control node boundaries, and
2096 // include those.
collect_nodes_out_all_ctrl_boundary(GrowableArray<Node * > * ns) const2097 void Node::collect_nodes_out_all_ctrl_boundary(GrowableArray<Node*> *ns) const {
2098   // Perform a BFS and stop at control nodes.
2099   GrowableArray<Node*> nodes(Compile::current()->unique());
2100   nodes.push((Node*) this);
2101   while (nodes.length() > 0) {
2102     Node* current = nodes.pop();
2103     if (NotANode(current)) {
2104       continue;
2105     }
2106     ns->append_if_missing(current);
2107     if (!current->is_CFG()) {
2108       for (DUIterator i = current->outs(); current->has_out(i); i++) {
2109         nodes.push(current->out(i));
2110       }
2111     }
2112   }
2113   ns->remove((Node*) this);
2114 }
2115 
2116 // VERIFICATION CODE
2117 // For each input edge to a node (ie - for each Use-Def edge), verify that
2118 // there is a corresponding Def-Use edge.
2119 //------------------------------verify_edges-----------------------------------
verify_edges(Unique_Node_List & visited)2120 void Node::verify_edges(Unique_Node_List &visited) {
2121   uint i, j, idx;
2122   int  cnt;
2123   Node *n;
2124 
2125   // Recursive termination test
2126   if (visited.member(this))  return;
2127   visited.push(this);
2128 
2129   // Walk over all input edges, checking for correspondence
2130   for( i = 0; i < len(); i++ ) {
2131     n = in(i);
2132     if (n != NULL && !n->is_top()) {
2133       // Count instances of (Node *)this
2134       cnt = 0;
2135       for (idx = 0; idx < n->_outcnt; idx++ ) {
2136         if (n->_out[idx] == (Node *)this)  cnt++;
2137       }
2138       assert( cnt > 0,"Failed to find Def-Use edge." );
2139       // Check for duplicate edges
2140       // walk the input array downcounting the input edges to n
2141       for( j = 0; j < len(); j++ ) {
2142         if( in(j) == n ) cnt--;
2143       }
2144       assert( cnt == 0,"Mismatched edge count.");
2145     } else if (n == NULL) {
2146       assert(i >= req() || i == 0 || is_Region() || is_Phi() || is_ArrayCopy() || (is_Unlock() && i == req()-1)
2147               || (is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
2148               "only region, phi, arraycopy, unlock or membar nodes have null data edges");
2149     } else {
2150       assert(n->is_top(), "sanity");
2151       // Nothing to check.
2152     }
2153   }
2154   // Recursive walk over all input edges
2155   for( i = 0; i < len(); i++ ) {
2156     n = in(i);
2157     if( n != NULL )
2158       in(i)->verify_edges(visited);
2159   }
2160 }
2161 
verify_recur(const Node * n,int verify_depth,VectorSet & old_space,VectorSet & new_space)2162 void Node::verify_recur(const Node *n, int verify_depth,
2163                         VectorSet &old_space, VectorSet &new_space) {
2164   if ( verify_depth == 0 )  return;
2165   if (verify_depth > 0)  --verify_depth;
2166 
2167   Compile* C = Compile::current();
2168 
2169   // Contained in new_space or old_space?
2170   VectorSet *v = C->node_arena()->contains(n) ? &new_space : &old_space;
2171   // Check for visited in the proper space.  Numberings are not unique
2172   // across spaces so we need a separate VectorSet for each space.
2173   if( v->test_set(n->_idx) ) return;
2174 
2175   if (n->is_Con() && n->bottom_type() == Type::TOP) {
2176     if (C->cached_top_node() == NULL)
2177       C->set_cached_top_node((Node*)n);
2178     assert(C->cached_top_node() == n, "TOP node must be unique");
2179   }
2180 
2181   for( uint i = 0; i < n->len(); i++ ) {
2182     Node *x = n->in(i);
2183     if (!x || x->is_top()) continue;
2184 
2185     // Verify my input has a def-use edge to me
2186     if (true /*VerifyDefUse*/) {
2187       // Count use-def edges from n to x
2188       int cnt = 0;
2189       for( uint j = 0; j < n->len(); j++ )
2190         if( n->in(j) == x )
2191           cnt++;
2192       // Count def-use edges from x to n
2193       uint max = x->_outcnt;
2194       for( uint k = 0; k < max; k++ )
2195         if (x->_out[k] == n)
2196           cnt--;
2197       assert( cnt == 0, "mismatched def-use edge counts" );
2198     }
2199 
2200     verify_recur(x, verify_depth, old_space, new_space);
2201   }
2202 
2203 }
2204 
2205 //------------------------------verify-----------------------------------------
2206 // Check Def-Use info for my subgraph
verify() const2207 void Node::verify() const {
2208   Compile* C = Compile::current();
2209   Node* old_top = C->cached_top_node();
2210   ResourceMark rm;
2211   ResourceArea *area = Thread::current()->resource_area();
2212   VectorSet old_space(area), new_space(area);
2213   verify_recur(this, -1, old_space, new_space);
2214   C->set_cached_top_node(old_top);
2215 }
2216 #endif
2217 
2218 
2219 //------------------------------walk-------------------------------------------
2220 // Graph walk, with both pre-order and post-order functions
walk(NFunc pre,NFunc post,void * env)2221 void Node::walk(NFunc pre, NFunc post, void *env) {
2222   VectorSet visited(Thread::current()->resource_area()); // Setup for local walk
2223   walk_(pre, post, env, visited);
2224 }
2225 
walk_(NFunc pre,NFunc post,void * env,VectorSet & visited)2226 void Node::walk_(NFunc pre, NFunc post, void *env, VectorSet &visited) {
2227   if( visited.test_set(_idx) ) return;
2228   pre(*this,env);               // Call the pre-order walk function
2229   for( uint i=0; i<_max; i++ )
2230     if( in(i) )                 // Input exists and is not walked?
2231       in(i)->walk_(pre,post,env,visited); // Walk it with pre & post functions
2232   post(*this,env);              // Call the post-order walk function
2233 }
2234 
nop(Node &,void *)2235 void Node::nop(Node &, void*) {}
2236 
2237 //------------------------------Registers--------------------------------------
2238 // Do we Match on this edge index or not?  Generally false for Control
2239 // and true for everything else.  Weird for calls & returns.
match_edge(uint idx) const2240 uint Node::match_edge(uint idx) const {
2241   return idx;                   // True for other than index 0 (control)
2242 }
2243 
2244 static RegMask _not_used_at_all;
2245 // Register classes are defined for specific machines
out_RegMask() const2246 const RegMask &Node::out_RegMask() const {
2247   ShouldNotCallThis();
2248   return _not_used_at_all;
2249 }
2250 
in_RegMask(uint) const2251 const RegMask &Node::in_RegMask(uint) const {
2252   ShouldNotCallThis();
2253   return _not_used_at_all;
2254 }
2255 
2256 //=============================================================================
2257 //-----------------------------------------------------------------------------
reset(Arena * new_arena)2258 void Node_Array::reset( Arena *new_arena ) {
2259   _a->Afree(_nodes,_max*sizeof(Node*));
2260   _max   = 0;
2261   _nodes = NULL;
2262   _a     = new_arena;
2263 }
2264 
2265 //------------------------------clear------------------------------------------
2266 // Clear all entries in _nodes to NULL but keep storage
clear()2267 void Node_Array::clear() {
2268   Copy::zero_to_bytes( _nodes, _max*sizeof(Node*) );
2269 }
2270 
2271 //-----------------------------------------------------------------------------
grow(uint i)2272 void Node_Array::grow( uint i ) {
2273   if( !_max ) {
2274     _max = 1;
2275     _nodes = (Node**)_a->Amalloc( _max * sizeof(Node*) );
2276     _nodes[0] = NULL;
2277   }
2278   uint old = _max;
2279   _max = next_power_of_2(i);
2280   _nodes = (Node**)_a->Arealloc( _nodes, old*sizeof(Node*),_max*sizeof(Node*));
2281   Copy::zero_to_bytes( &_nodes[old], (_max-old)*sizeof(Node*) );
2282 }
2283 
2284 //-----------------------------------------------------------------------------
insert(uint i,Node * n)2285 void Node_Array::insert( uint i, Node *n ) {
2286   if( _nodes[_max-1] ) grow(_max);      // Get more space if full
2287   Copy::conjoint_words_to_higher((HeapWord*)&_nodes[i], (HeapWord*)&_nodes[i+1], ((_max-i-1)*sizeof(Node*)));
2288   _nodes[i] = n;
2289 }
2290 
2291 //-----------------------------------------------------------------------------
remove(uint i)2292 void Node_Array::remove( uint i ) {
2293   Copy::conjoint_words_to_lower((HeapWord*)&_nodes[i+1], (HeapWord*)&_nodes[i], ((_max-i-1)*sizeof(Node*)));
2294   _nodes[_max-1] = NULL;
2295 }
2296 
2297 //-----------------------------------------------------------------------------
sort(C_sort_func_t func)2298 void Node_Array::sort( C_sort_func_t func) {
2299   qsort( _nodes, _max, sizeof( Node* ), func );
2300 }
2301 
2302 //-----------------------------------------------------------------------------
dump() const2303 void Node_Array::dump() const {
2304 #ifndef PRODUCT
2305   for( uint i = 0; i < _max; i++ ) {
2306     Node *nn = _nodes[i];
2307     if( nn != NULL ) {
2308       tty->print("%5d--> ",i); nn->dump();
2309     }
2310   }
2311 #endif
2312 }
2313 
2314 //--------------------------is_iteratively_computed------------------------------
2315 // Operation appears to be iteratively computed (such as an induction variable)
2316 // It is possible for this operation to return false for a loop-varying
2317 // value, if it appears (by local graph inspection) to be computed by a simple conditional.
is_iteratively_computed()2318 bool Node::is_iteratively_computed() {
2319   if (ideal_reg()) { // does operation have a result register?
2320     for (uint i = 1; i < req(); i++) {
2321       Node* n = in(i);
2322       if (n != NULL && n->is_Phi()) {
2323         for (uint j = 1; j < n->req(); j++) {
2324           if (n->in(j) == this) {
2325             return true;
2326           }
2327         }
2328       }
2329     }
2330   }
2331   return false;
2332 }
2333 
2334 //--------------------------find_similar------------------------------
2335 // Return a node with opcode "opc" and same inputs as "this" if one can
2336 // be found; Otherwise return NULL;
find_similar(int opc)2337 Node* Node::find_similar(int opc) {
2338   if (req() >= 2) {
2339     Node* def = in(1);
2340     if (def && def->outcnt() >= 2) {
2341       for (DUIterator_Fast dmax, i = def->fast_outs(dmax); i < dmax; i++) {
2342         Node* use = def->fast_out(i);
2343         if (use != this &&
2344             use->Opcode() == opc &&
2345             use->req() == req()) {
2346           uint j;
2347           for (j = 0; j < use->req(); j++) {
2348             if (use->in(j) != in(j)) {
2349               break;
2350             }
2351           }
2352           if (j == use->req()) {
2353             return use;
2354           }
2355         }
2356       }
2357     }
2358   }
2359   return NULL;
2360 }
2361 
2362 
2363 //--------------------------unique_ctrl_out------------------------------
2364 // Return the unique control out if only one. Null if none or more than one.
unique_ctrl_out() const2365 Node* Node::unique_ctrl_out() const {
2366   Node* found = NULL;
2367   for (uint i = 0; i < outcnt(); i++) {
2368     Node* use = raw_out(i);
2369     if (use->is_CFG() && use != this) {
2370       if (found != NULL) return NULL;
2371       found = use;
2372     }
2373   }
2374   return found;
2375 }
2376 
ensure_control_or_add_prec(Node * c)2377 void Node::ensure_control_or_add_prec(Node* c) {
2378   if (in(0) == NULL) {
2379     set_req(0, c);
2380   } else if (in(0) != c) {
2381     add_prec(c);
2382   }
2383 }
2384 
2385 //=============================================================================
2386 //------------------------------yank-------------------------------------------
2387 // Find and remove
yank(Node * n)2388 void Node_List::yank( Node *n ) {
2389   uint i;
2390   for( i = 0; i < _cnt; i++ )
2391     if( _nodes[i] == n )
2392       break;
2393 
2394   if( i < _cnt )
2395     _nodes[i] = _nodes[--_cnt];
2396 }
2397 
2398 //------------------------------dump-------------------------------------------
dump() const2399 void Node_List::dump() const {
2400 #ifndef PRODUCT
2401   for( uint i = 0; i < _cnt; i++ )
2402     if( _nodes[i] ) {
2403       tty->print("%5d--> ",i);
2404       _nodes[i]->dump();
2405     }
2406 #endif
2407 }
2408 
dump_simple() const2409 void Node_List::dump_simple() const {
2410 #ifndef PRODUCT
2411   for( uint i = 0; i < _cnt; i++ )
2412     if( _nodes[i] ) {
2413       tty->print(" %d", _nodes[i]->_idx);
2414     } else {
2415       tty->print(" NULL");
2416     }
2417 #endif
2418 }
2419 
2420 //=============================================================================
2421 //------------------------------remove-----------------------------------------
remove(Node * n)2422 void Unique_Node_List::remove(Node* n) {
2423   if (_in_worklist.test(n->_idx)) {
2424     for (uint i = 0; i < size(); i++) {
2425       if (_nodes[i] == n) {
2426         map(i, Node_List::pop());
2427         _in_worklist.remove(n->_idx);
2428         return;
2429       }
2430     }
2431     ShouldNotReachHere();
2432   }
2433 }
2434 
2435 //-----------------------remove_useless_nodes----------------------------------
2436 // Remove useless nodes from worklist
remove_useless_nodes(VectorSet & useful)2437 void Unique_Node_List::remove_useless_nodes(VectorSet &useful) {
2438 
2439   for (uint i = 0; i < size(); ++i) {
2440     Node *n = at(i);
2441     assert( n != NULL, "Did not expect null entries in worklist");
2442     if (!useful.test(n->_idx)) {
2443       _in_worklist.remove(n->_idx);
2444       map(i,Node_List::pop());
2445       // Node *replacement = Node_List::pop();
2446       // if( i != size() ) { // Check if removing last entry
2447       //   _nodes[i] = replacement;
2448       // }
2449       --i;  // Visit popped node
2450       // If it was last entry, loop terminates since size() was also reduced
2451     }
2452   }
2453 }
2454 
2455 //=============================================================================
grow()2456 void Node_Stack::grow() {
2457   size_t old_top = pointer_delta(_inode_top,_inodes,sizeof(INode)); // save _top
2458   size_t old_max = pointer_delta(_inode_max,_inodes,sizeof(INode));
2459   size_t max = old_max << 1;             // max * 2
2460   _inodes = REALLOC_ARENA_ARRAY(_a, INode, _inodes, old_max, max);
2461   _inode_max = _inodes + max;
2462   _inode_top = _inodes + old_top;        // restore _top
2463 }
2464 
2465 // Node_Stack is used to map nodes.
find(uint idx) const2466 Node* Node_Stack::find(uint idx) const {
2467   uint sz = size();
2468   for (uint i=0; i < sz; i++) {
2469     if (idx == index_at(i) )
2470       return node_at(i);
2471   }
2472   return NULL;
2473 }
2474 
2475 //=============================================================================
size_of() const2476 uint TypeNode::size_of() const { return sizeof(*this); }
2477 #ifndef PRODUCT
dump_spec(outputStream * st) const2478 void TypeNode::dump_spec(outputStream *st) const {
2479   if( !Verbose && !WizardMode ) {
2480     // standard dump does this in Verbose and WizardMode
2481     st->print(" #"); _type->dump_on(st);
2482   }
2483 }
2484 
dump_compact_spec(outputStream * st) const2485 void TypeNode::dump_compact_spec(outputStream *st) const {
2486   st->print("#");
2487   _type->dump_on(st);
2488 }
2489 #endif
hash() const2490 uint TypeNode::hash() const {
2491   return Node::hash() + _type->hash();
2492 }
cmp(const Node & n) const2493 bool TypeNode::cmp( const Node &n ) const
2494 { return !Type::cmp( _type, ((TypeNode&)n)._type ); }
bottom_type() const2495 const Type *TypeNode::bottom_type() const { return _type; }
Value(PhaseGVN * phase) const2496 const Type* TypeNode::Value(PhaseGVN* phase) const { return _type; }
2497 
2498 //------------------------------ideal_reg--------------------------------------
ideal_reg() const2499 uint TypeNode::ideal_reg() const {
2500   return _type->ideal_reg();
2501 }
2502