buildOopMap.cpp revision 6760:22b98ab2a69f
1/*
2 * Copyright (c) 2002, 2014, 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 "code/vmreg.inline.hpp"
27#include "compiler/oopMap.hpp"
28#include "opto/addnode.hpp"
29#include "opto/callnode.hpp"
30#include "opto/compile.hpp"
31#include "opto/machnode.hpp"
32#include "opto/matcher.hpp"
33#include "opto/phase.hpp"
34#include "opto/regalloc.hpp"
35#include "opto/rootnode.hpp"
36
37// The functions in this file builds OopMaps after all scheduling is done.
38//
39// OopMaps contain a list of all registers and stack-slots containing oops (so
40// they can be updated by GC).  OopMaps also contain a list of derived-pointer
41// base-pointer pairs.  When the base is moved, the derived pointer moves to
42// follow it.  Finally, any registers holding callee-save values are also
43// recorded.  These might contain oops, but only the caller knows.
44//
45// BuildOopMaps implements a simple forward reaching-defs solution.  At each
46// GC point we'll have the reaching-def Nodes.  If the reaching Nodes are
47// typed as pointers (no offset), then they are oops.  Pointers+offsets are
48// derived pointers, and bases can be found from them.  Finally, we'll also
49// track reaching callee-save values.  Note that a copy of a callee-save value
50// "kills" it's source, so that only 1 copy of a callee-save value is alive at
51// a time.
52//
53// We run a simple bitvector liveness pass to help trim out dead oops.  Due to
54// irreducible loops, we can have a reaching def of an oop that only reaches
55// along one path and no way to know if it's valid or not on the other path.
56// The bitvectors are quite dense and the liveness pass is fast.
57//
58// At GC points, we consult this information to build OopMaps.  All reaching
59// defs typed as oops are added to the OopMap.  Only 1 instance of a
60// callee-save register can be recorded.  For derived pointers, we'll have to
61// find and record the register holding the base.
62//
63// The reaching def's is a simple 1-pass worklist approach.  I tried a clever
64// breadth-first approach but it was worse (showed O(n^2) in the
65// pick-next-block code).
66//
67// The relevant data is kept in a struct of arrays (it could just as well be
68// an array of structs, but the struct-of-arrays is generally a little more
69// efficient).  The arrays are indexed by register number (including
70// stack-slots as registers) and so is bounded by 200 to 300 elements in
71// practice.  One array will map to a reaching def Node (or NULL for
72// conflict/dead).  The other array will map to a callee-saved register or
73// OptoReg::Bad for not-callee-saved.
74
75
76// Structure to pass around
77struct OopFlow : public ResourceObj {
78  short *_callees;              // Array mapping register to callee-saved
79  Node **_defs;                 // array mapping register to reaching def
80                                // or NULL if dead/conflict
81  // OopFlow structs, when not being actively modified, describe the _end_ of
82  // this block.
83  Block *_b;                    // Block for this struct
84  OopFlow *_next;               // Next free OopFlow
85                                // or NULL if dead/conflict
86  Compile* C;
87
88  OopFlow( short *callees, Node **defs, Compile* c ) : _callees(callees), _defs(defs),
89    _b(NULL), _next(NULL), C(c) { }
90
91  // Given reaching-defs for this block start, compute it for this block end
92  void compute_reach( PhaseRegAlloc *regalloc, int max_reg, Dict *safehash );
93
94  // Merge these two OopFlows into the 'this' pointer.
95  void merge( OopFlow *flow, int max_reg );
96
97  // Copy a 'flow' over an existing flow
98  void clone( OopFlow *flow, int max_size);
99
100  // Make a new OopFlow from scratch
101  static OopFlow *make( Arena *A, int max_size, Compile* C );
102
103  // Build an oopmap from the current flow info
104  OopMap *build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, int* live );
105};
106
107// Given reaching-defs for this block start, compute it for this block end
108void OopFlow::compute_reach( PhaseRegAlloc *regalloc, int max_reg, Dict *safehash ) {
109
110  for( uint i=0; i<_b->number_of_nodes(); i++ ) {
111    Node *n = _b->get_node(i);
112
113    if( n->jvms() ) {           // Build an OopMap here?
114      JVMState *jvms = n->jvms();
115      // no map needed for leaf calls
116      if( n->is_MachSafePoint() && !n->is_MachCallLeaf() ) {
117        int *live = (int*) (*safehash)[n];
118        assert( live, "must find live" );
119        n->as_MachSafePoint()->set_oop_map( build_oop_map(n,max_reg,regalloc, live) );
120      }
121    }
122
123    // Assign new reaching def's.
124    // Note that I padded the _defs and _callees arrays so it's legal
125    // to index at _defs[OptoReg::Bad].
126    OptoReg::Name first = regalloc->get_reg_first(n);
127    OptoReg::Name second = regalloc->get_reg_second(n);
128    _defs[first] = n;
129    _defs[second] = n;
130
131    // Pass callee-save info around copies
132    int idx = n->is_Copy();
133    if( idx ) {                 // Copies move callee-save info
134      OptoReg::Name old_first = regalloc->get_reg_first(n->in(idx));
135      OptoReg::Name old_second = regalloc->get_reg_second(n->in(idx));
136      int tmp_first = _callees[old_first];
137      int tmp_second = _callees[old_second];
138      _callees[old_first] = OptoReg::Bad; // callee-save is moved, dead in old location
139      _callees[old_second] = OptoReg::Bad;
140      _callees[first] = tmp_first;
141      _callees[second] = tmp_second;
142    } else if( n->is_Phi() ) {  // Phis do not mod callee-saves
143      assert( _callees[first] == _callees[regalloc->get_reg_first(n->in(1))], "" );
144      assert( _callees[second] == _callees[regalloc->get_reg_second(n->in(1))], "" );
145      assert( _callees[first] == _callees[regalloc->get_reg_first(n->in(n->req()-1))], "" );
146      assert( _callees[second] == _callees[regalloc->get_reg_second(n->in(n->req()-1))], "" );
147    } else {
148      _callees[first] = OptoReg::Bad; // No longer holding a callee-save value
149      _callees[second] = OptoReg::Bad;
150
151      // Find base case for callee saves
152      if( n->is_Proj() && n->in(0)->is_Start() ) {
153        if( OptoReg::is_reg(first) &&
154            regalloc->_matcher.is_save_on_entry(first) )
155          _callees[first] = first;
156        if( OptoReg::is_reg(second) &&
157            regalloc->_matcher.is_save_on_entry(second) )
158          _callees[second] = second;
159      }
160    }
161  }
162}
163
164// Merge the given flow into the 'this' flow
165void OopFlow::merge( OopFlow *flow, int max_reg ) {
166  assert( _b == NULL, "merging into a happy flow" );
167  assert( flow->_b, "this flow is still alive" );
168  assert( flow != this, "no self flow" );
169
170  // Do the merge.  If there are any differences, drop to 'bottom' which
171  // is OptoReg::Bad or NULL depending.
172  for( int i=0; i<max_reg; i++ ) {
173    // Merge the callee-save's
174    if( _callees[i] != flow->_callees[i] )
175      _callees[i] = OptoReg::Bad;
176    // Merge the reaching defs
177    if( _defs[i] != flow->_defs[i] )
178      _defs[i] = NULL;
179  }
180
181}
182
183void OopFlow::clone( OopFlow *flow, int max_size ) {
184  _b = flow->_b;
185  memcpy( _callees, flow->_callees, sizeof(short)*max_size);
186  memcpy( _defs   , flow->_defs   , sizeof(Node*)*max_size);
187}
188
189OopFlow *OopFlow::make( Arena *A, int max_size, Compile* C ) {
190  short *callees = NEW_ARENA_ARRAY(A,short,max_size+1);
191  Node **defs    = NEW_ARENA_ARRAY(A,Node*,max_size+1);
192  debug_only( memset(defs,0,(max_size+1)*sizeof(Node*)) );
193  OopFlow *flow = new (A) OopFlow(callees+1, defs+1, C);
194  assert( &flow->_callees[OptoReg::Bad] == callees, "Ok to index at OptoReg::Bad" );
195  assert( &flow->_defs   [OptoReg::Bad] == defs   , "Ok to index at OptoReg::Bad" );
196  return flow;
197}
198
199static int get_live_bit( int *live, int reg ) {
200  return live[reg>>LogBitsPerInt] &   (1<<(reg&(BitsPerInt-1))); }
201static void set_live_bit( int *live, int reg ) {
202         live[reg>>LogBitsPerInt] |=  (1<<(reg&(BitsPerInt-1))); }
203static void clr_live_bit( int *live, int reg ) {
204         live[reg>>LogBitsPerInt] &= ~(1<<(reg&(BitsPerInt-1))); }
205
206// Build an oopmap from the current flow info
207OopMap *OopFlow::build_oop_map( Node *n, int max_reg, PhaseRegAlloc *regalloc, int* live ) {
208  int framesize = regalloc->_framesize;
209  int max_inarg_slot = OptoReg::reg2stack(regalloc->_matcher._new_SP);
210  debug_only( char *dup_check = NEW_RESOURCE_ARRAY(char,OptoReg::stack0());
211              memset(dup_check,0,OptoReg::stack0()) );
212
213  OopMap *omap = new OopMap( framesize,  max_inarg_slot );
214  MachCallNode *mcall = n->is_MachCall() ? n->as_MachCall() : NULL;
215  JVMState* jvms = n->jvms();
216
217  // For all registers do...
218  for( int reg=0; reg<max_reg; reg++ ) {
219    if( get_live_bit(live,reg) == 0 )
220      continue;                 // Ignore if not live
221
222    // %%% C2 can use 2 OptoRegs when the physical register is only one 64bit
223    // register in that case we'll get an non-concrete register for the second
224    // half. We only need to tell the map the register once!
225    //
226    // However for the moment we disable this change and leave things as they
227    // were.
228
229    VMReg r = OptoReg::as_VMReg(OptoReg::Name(reg), framesize, max_inarg_slot);
230
231    if (false && r->is_reg() && !r->is_concrete()) {
232      continue;
233    }
234
235    // See if dead (no reaching def).
236    Node *def = _defs[reg];     // Get reaching def
237    assert( def, "since live better have reaching def" );
238
239    // Classify the reaching def as oop, derived, callee-save, dead, or other
240    const Type *t = def->bottom_type();
241    if( t->isa_oop_ptr() ) {    // Oop or derived?
242      assert( !OptoReg::is_valid(_callees[reg]), "oop can't be callee save" );
243#ifdef _LP64
244      // 64-bit pointers record oop-ishness on 2 aligned adjacent registers.
245      // Make sure both are record from the same reaching def, but do not
246      // put both into the oopmap.
247      if( (reg&1) == 1 ) {      // High half of oop-pair?
248        assert( _defs[reg-1] == _defs[reg], "both halves from same reaching def" );
249        continue;               // Do not record high parts in oopmap
250      }
251#endif
252
253      // Check for a legal reg name in the oopMap and bailout if it is not.
254      if (!omap->legal_vm_reg_name(r)) {
255        regalloc->C->record_method_not_compilable("illegal oopMap register name");
256        continue;
257      }
258      if( t->is_ptr()->_offset == 0 ) { // Not derived?
259        if( mcall ) {
260          // Outgoing argument GC mask responsibility belongs to the callee,
261          // not the caller.  Inspect the inputs to the call, to see if
262          // this live-range is one of them.
263          uint cnt = mcall->tf()->domain()->cnt();
264          uint j;
265          for( j = TypeFunc::Parms; j < cnt; j++)
266            if( mcall->in(j) == def )
267              break;            // reaching def is an argument oop
268          if( j < cnt )         // arg oops dont go in GC map
269            continue;           // Continue on to the next register
270        }
271        omap->set_oop(r);
272      } else {                  // Else it's derived.
273        // Find the base of the derived value.
274        uint i;
275        // Fast, common case, scan
276        for( i = jvms->oopoff(); i < n->req(); i+=2 )
277          if( n->in(i) == def ) break; // Common case
278        if( i == n->req() ) {   // Missed, try a more generous scan
279          // Scan again, but this time peek through copies
280          for( i = jvms->oopoff(); i < n->req(); i+=2 ) {
281            Node *m = n->in(i); // Get initial derived value
282            while( 1 ) {
283              Node *d = def;    // Get initial reaching def
284              while( 1 ) {      // Follow copies of reaching def to end
285                if( m == d ) goto found; // breaks 3 loops
286                int idx = d->is_Copy();
287                if( !idx ) break;
288                d = d->in(idx);     // Link through copy
289              }
290              int idx = m->is_Copy();
291              if( !idx ) break;
292              m = m->in(idx);
293            }
294          }
295          guarantee( 0, "must find derived/base pair" );
296        }
297      found: ;
298        Node *base = n->in(i+1); // Base is other half of pair
299        int breg = regalloc->get_reg_first(base);
300        VMReg b = OptoReg::as_VMReg(OptoReg::Name(breg), framesize, max_inarg_slot);
301
302        // I record liveness at safepoints BEFORE I make the inputs
303        // live.  This is because argument oops are NOT live at a
304        // safepoint (or at least they cannot appear in the oopmap).
305        // Thus bases of base/derived pairs might not be in the
306        // liveness data but they need to appear in the oopmap.
307        if( get_live_bit(live,breg) == 0 ) {// Not live?
308          // Flag it, so next derived pointer won't re-insert into oopmap
309          set_live_bit(live,breg);
310          // Already missed our turn?
311          if( breg < reg ) {
312            if (b->is_stack() || b->is_concrete() || true ) {
313              omap->set_oop( b);
314            }
315          }
316        }
317        if (b->is_stack() || b->is_concrete() || true ) {
318          omap->set_derived_oop( r, b);
319        }
320      }
321
322    } else if( t->isa_narrowoop() ) {
323      assert( !OptoReg::is_valid(_callees[reg]), "oop can't be callee save" );
324      // Check for a legal reg name in the oopMap and bailout if it is not.
325      if (!omap->legal_vm_reg_name(r)) {
326        regalloc->C->record_method_not_compilable("illegal oopMap register name");
327        continue;
328      }
329      if( mcall ) {
330          // Outgoing argument GC mask responsibility belongs to the callee,
331          // not the caller.  Inspect the inputs to the call, to see if
332          // this live-range is one of them.
333        uint cnt = mcall->tf()->domain()->cnt();
334        uint j;
335        for( j = TypeFunc::Parms; j < cnt; j++)
336          if( mcall->in(j) == def )
337            break;            // reaching def is an argument oop
338        if( j < cnt )         // arg oops dont go in GC map
339          continue;           // Continue on to the next register
340      }
341      omap->set_narrowoop(r);
342    } else if( OptoReg::is_valid(_callees[reg])) { // callee-save?
343      // It's a callee-save value
344      assert( dup_check[_callees[reg]]==0, "trying to callee save same reg twice" );
345      debug_only( dup_check[_callees[reg]]=1; )
346      VMReg callee = OptoReg::as_VMReg(OptoReg::Name(_callees[reg]));
347      if ( callee->is_concrete() || true ) {
348        omap->set_callee_saved( r, callee);
349      }
350
351    } else {
352      // Other - some reaching non-oop value
353      omap->set_value( r);
354#ifdef ASSERT
355      if( t->isa_rawptr() && C->cfg()->_raw_oops.member(def) ) {
356        def->dump();
357        n->dump();
358        assert(false, "there should be a oop in OopMap instead of a live raw oop at safepoint");
359      }
360#endif
361    }
362
363  }
364
365#ifdef ASSERT
366  /* Nice, Intel-only assert
367  int cnt_callee_saves=0;
368  int reg2 = 0;
369  while (OptoReg::is_reg(reg2)) {
370    if( dup_check[reg2] != 0) cnt_callee_saves++;
371    assert( cnt_callee_saves==3 || cnt_callee_saves==5, "missed some callee-save" );
372    reg2++;
373  }
374  */
375#endif
376
377#ifdef ASSERT
378  for( OopMapStream oms1(omap, OopMapValue::derived_oop_value); !oms1.is_done(); oms1.next()) {
379    OopMapValue omv1 = oms1.current();
380    bool found = false;
381    for( OopMapStream oms2(omap,OopMapValue::oop_value); !oms2.is_done(); oms2.next()) {
382      if( omv1.content_reg() == oms2.current().reg() ) {
383        found = true;
384        break;
385      }
386    }
387    assert( found, "derived with no base in oopmap" );
388  }
389#endif
390
391  return omap;
392}
393
394// Compute backwards liveness on registers
395static void do_liveness(PhaseRegAlloc* regalloc, PhaseCFG* cfg, Block_List* worklist, int max_reg_ints, Arena* A, Dict* safehash) {
396  int* live = NEW_ARENA_ARRAY(A, int, (cfg->number_of_blocks() + 1) * max_reg_ints);
397  int* tmp_live = &live[cfg->number_of_blocks() * max_reg_ints];
398  Node* root = cfg->get_root_node();
399  // On CISC platforms, get the node representing the stack pointer  that regalloc
400  // used for spills
401  Node *fp = NodeSentinel;
402  if (UseCISCSpill && root->req() > 1) {
403    fp = root->in(1)->in(TypeFunc::FramePtr);
404  }
405  memset(live, 0, cfg->number_of_blocks() * (max_reg_ints << LogBytesPerInt));
406  // Push preds onto worklist
407  for (uint i = 1; i < root->req(); i++) {
408    Block* block = cfg->get_block_for_node(root->in(i));
409    worklist->push(block);
410  }
411
412  // ZKM.jar includes tiny infinite loops which are unreached from below.
413  // If we missed any blocks, we'll retry here after pushing all missed
414  // blocks on the worklist.  Normally this outer loop never trips more
415  // than once.
416  while (1) {
417
418    while( worklist->size() ) { // Standard worklist algorithm
419      Block *b = worklist->rpop();
420
421      // Copy first successor into my tmp_live space
422      int s0num = b->_succs[0]->_pre_order;
423      int *t = &live[s0num*max_reg_ints];
424      for( int i=0; i<max_reg_ints; i++ )
425        tmp_live[i] = t[i];
426
427      // OR in the remaining live registers
428      for( uint j=1; j<b->_num_succs; j++ ) {
429        uint sjnum = b->_succs[j]->_pre_order;
430        int *t = &live[sjnum*max_reg_ints];
431        for( int i=0; i<max_reg_ints; i++ )
432          tmp_live[i] |= t[i];
433      }
434
435      // Now walk tmp_live up the block backwards, computing live
436      for( int k=b->number_of_nodes()-1; k>=0; k-- ) {
437        Node *n = b->get_node(k);
438        // KILL def'd bits
439        int first = regalloc->get_reg_first(n);
440        int second = regalloc->get_reg_second(n);
441        if( OptoReg::is_valid(first) ) clr_live_bit(tmp_live,first);
442        if( OptoReg::is_valid(second) ) clr_live_bit(tmp_live,second);
443
444        MachNode *m = n->is_Mach() ? n->as_Mach() : NULL;
445
446        // Check if m is potentially a CISC alternate instruction (i.e, possibly
447        // synthesized by RegAlloc from a conventional instruction and a
448        // spilled input)
449        bool is_cisc_alternate = false;
450        if (UseCISCSpill && m) {
451          is_cisc_alternate = m->is_cisc_alternate();
452        }
453
454        // GEN use'd bits
455        for( uint l=1; l<n->req(); l++ ) {
456          Node *def = n->in(l);
457          assert(def != 0, "input edge required");
458          int first = regalloc->get_reg_first(def);
459          int second = regalloc->get_reg_second(def);
460          if( OptoReg::is_valid(first) ) set_live_bit(tmp_live,first);
461          if( OptoReg::is_valid(second) ) set_live_bit(tmp_live,second);
462          // If we use the stack pointer in a cisc-alternative instruction,
463          // check for use as a memory operand.  Then reconstruct the RegName
464          // for this stack location, and set the appropriate bit in the
465          // live vector 4987749.
466          if (is_cisc_alternate && def == fp) {
467            const TypePtr *adr_type = NULL;
468            intptr_t offset;
469            const Node* base = m->get_base_and_disp(offset, adr_type);
470            if (base == NodeSentinel) {
471              // Machnode has multiple memory inputs. We are unable to reason
472              // with these, but are presuming (with trepidation) that not any of
473              // them are oops. This can be fixed by making get_base_and_disp()
474              // look at a specific input instead of all inputs.
475              assert(!def->bottom_type()->isa_oop_ptr(), "expecting non-oop mem input");
476            } else if (base != fp || offset == Type::OffsetBot) {
477              // Do nothing: the fp operand is either not from a memory use
478              // (base == NULL) OR the fp is used in a non-memory context
479              // (base is some other register) OR the offset is not constant,
480              // so it is not a stack slot.
481            } else {
482              assert(offset >= 0, "unexpected negative offset");
483              offset -= (offset % jintSize);  // count the whole word
484              int stack_reg = regalloc->offset2reg(offset);
485              if (OptoReg::is_stack(stack_reg)) {
486                set_live_bit(tmp_live, stack_reg);
487              } else {
488                assert(false, "stack_reg not on stack?");
489              }
490            }
491          }
492        }
493
494        if( n->jvms() ) {       // Record liveness at safepoint
495
496          // This placement of this stanza means inputs to calls are
497          // considered live at the callsite's OopMap.  Argument oops are
498          // hence live, but NOT included in the oopmap.  See cutout in
499          // build_oop_map.  Debug oops are live (and in OopMap).
500          int *n_live = NEW_ARENA_ARRAY(A, int, max_reg_ints);
501          for( int l=0; l<max_reg_ints; l++ )
502            n_live[l] = tmp_live[l];
503          safehash->Insert(n,n_live);
504        }
505
506      }
507
508      // Now at block top, see if we have any changes.  If so, propagate
509      // to prior blocks.
510      int *old_live = &live[b->_pre_order*max_reg_ints];
511      int l;
512      for( l=0; l<max_reg_ints; l++ )
513        if( tmp_live[l] != old_live[l] )
514          break;
515      if( l<max_reg_ints ) {     // Change!
516        // Copy in new value
517        for( l=0; l<max_reg_ints; l++ )
518          old_live[l] = tmp_live[l];
519        // Push preds onto worklist
520        for (l = 1; l < (int)b->num_preds(); l++) {
521          Block* block = cfg->get_block_for_node(b->pred(l));
522          worklist->push(block);
523        }
524      }
525    }
526
527    // Scan for any missing safepoints.  Happens to infinite loops
528    // ala ZKM.jar
529    uint i;
530    for (i = 1; i < cfg->number_of_blocks(); i++) {
531      Block* block = cfg->get_block(i);
532      uint j;
533      for (j = 1; j < block->number_of_nodes(); j++) {
534        if (block->get_node(j)->jvms() && (*safehash)[block->get_node(j)] == NULL) {
535           break;
536        }
537      }
538      if (j < block->number_of_nodes()) {
539        break;
540      }
541    }
542    if (i == cfg->number_of_blocks()) {
543      break;                    // Got 'em all
544    }
545#ifndef PRODUCT
546    if( PrintOpto && Verbose )
547      tty->print_cr("retripping live calc");
548#endif
549    // Force the issue (expensively): recheck everybody
550    for (i = 1; i < cfg->number_of_blocks(); i++) {
551      worklist->push(cfg->get_block(i));
552    }
553  }
554}
555
556// Collect GC mask info - where are all the OOPs?
557void Compile::BuildOopMaps() {
558  NOT_PRODUCT( TracePhase t3("bldOopMaps", &_t_buildOopMaps, TimeCompiler); )
559  // Can't resource-mark because I need to leave all those OopMaps around,
560  // or else I need to resource-mark some arena other than the default.
561  // ResourceMark rm;              // Reclaim all OopFlows when done
562  int max_reg = _regalloc->_max_reg; // Current array extent
563
564  Arena *A = Thread::current()->resource_area();
565  Block_List worklist;          // Worklist of pending blocks
566
567  int max_reg_ints = round_to(max_reg, BitsPerInt)>>LogBitsPerInt;
568  Dict *safehash = NULL;        // Used for assert only
569  // Compute a backwards liveness per register.  Needs a bitarray of
570  // #blocks x (#registers, rounded up to ints)
571  safehash = new Dict(cmpkey,hashkey,A);
572  do_liveness( _regalloc, _cfg, &worklist, max_reg_ints, A, safehash );
573  OopFlow *free_list = NULL;    // Free, unused
574
575  // Array mapping blocks to completed oopflows
576  OopFlow **flows = NEW_ARENA_ARRAY(A, OopFlow*, _cfg->number_of_blocks());
577  memset( flows, 0, _cfg->number_of_blocks() * sizeof(OopFlow*) );
578
579
580  // Do the first block 'by hand' to prime the worklist
581  Block *entry = _cfg->get_block(1);
582  OopFlow *rootflow = OopFlow::make(A,max_reg,this);
583  // Initialize to 'bottom' (not 'top')
584  memset( rootflow->_callees, OptoReg::Bad, max_reg*sizeof(short) );
585  memset( rootflow->_defs   ,            0, max_reg*sizeof(Node*) );
586  flows[entry->_pre_order] = rootflow;
587
588  // Do the first block 'by hand' to prime the worklist
589  rootflow->_b = entry;
590  rootflow->compute_reach( _regalloc, max_reg, safehash );
591  for( uint i=0; i<entry->_num_succs; i++ )
592    worklist.push(entry->_succs[i]);
593
594  // Now worklist contains blocks which have some, but perhaps not all,
595  // predecessors visited.
596  while( worklist.size() ) {
597    // Scan for a block with all predecessors visited, or any randoms slob
598    // otherwise.  All-preds-visited order allows me to recycle OopFlow
599    // structures rapidly and cut down on the memory footprint.
600    // Note: not all predecessors might be visited yet (must happen for
601    // irreducible loops).  This is OK, since every live value must have the
602    // SAME reaching def for the block, so any reaching def is OK.
603    uint i;
604
605    Block *b = worklist.pop();
606    // Ignore root block
607    if (b == _cfg->get_root_block()) {
608      continue;
609    }
610    // Block is already done?  Happens if block has several predecessors,
611    // he can get on the worklist more than once.
612    if( flows[b->_pre_order] ) continue;
613
614    // If this block has a visited predecessor AND that predecessor has this
615    // last block as his only undone child, we can move the OopFlow from the
616    // pred to this block.  Otherwise we have to grab a new OopFlow.
617    OopFlow *flow = NULL;       // Flag for finding optimized flow
618    Block *pred = (Block*)0xdeadbeef;
619    // Scan this block's preds to find a done predecessor
620    for (uint j = 1; j < b->num_preds(); j++) {
621      Block* p = _cfg->get_block_for_node(b->pred(j));
622      OopFlow *p_flow = flows[p->_pre_order];
623      if( p_flow ) {            // Predecessor is done
624        assert( p_flow->_b == p, "cross check" );
625        pred = p;               // Record some predecessor
626        // If all successors of p are done except for 'b', then we can carry
627        // p_flow forward to 'b' without copying, otherwise we have to draw
628        // from the free_list and clone data.
629        uint k;
630        for( k=0; k<p->_num_succs; k++ )
631          if( !flows[p->_succs[k]->_pre_order] &&
632              p->_succs[k] != b )
633            break;
634
635        // Either carry-forward the now-unused OopFlow for b's use
636        // or draw a new one from the free list
637        if( k==p->_num_succs ) {
638          flow = p_flow;
639          break;                // Found an ideal pred, use him
640        }
641      }
642    }
643
644    if( flow ) {
645      // We have an OopFlow that's the last-use of a predecessor.
646      // Carry it forward.
647    } else {                    // Draw a new OopFlow from the freelist
648      if( !free_list )
649        free_list = OopFlow::make(A,max_reg,C);
650      flow = free_list;
651      assert( flow->_b == NULL, "oopFlow is not free" );
652      free_list = flow->_next;
653      flow->_next = NULL;
654
655      // Copy/clone over the data
656      flow->clone(flows[pred->_pre_order], max_reg);
657    }
658
659    // Mark flow for block.  Blocks can only be flowed over once,
660    // because after the first time they are guarded from entering
661    // this code again.
662    assert( flow->_b == pred, "have some prior flow" );
663    flow->_b = NULL;
664
665    // Now push flow forward
666    flows[b->_pre_order] = flow;// Mark flow for this block
667    flow->_b = b;
668    flow->compute_reach( _regalloc, max_reg, safehash );
669
670    // Now push children onto worklist
671    for( i=0; i<b->_num_succs; i++ )
672      worklist.push(b->_succs[i]);
673
674  }
675}
676