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