1 /*
2  * Copyright (c) 1997, 2018, 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 "interpreter/bytecodeStream.hpp"
27 #include "logging/log.hpp"
28 #include "logging/logStream.hpp"
29 #include "memory/allocation.inline.hpp"
30 #include "oops/generateOopMap.hpp"
31 #include "oops/oop.inline.hpp"
32 #include "oops/symbol.hpp"
33 #include "runtime/handles.inline.hpp"
34 #include "runtime/java.hpp"
35 #include "runtime/os.hpp"
36 #include "runtime/relocator.hpp"
37 #include "runtime/timerTrace.hpp"
38 #include "utilities/bitMap.inline.hpp"
39 #include "utilities/ostream.hpp"
40 
41 //
42 //
43 // Compute stack layouts for each instruction in method.
44 //
45 //  Problems:
46 //  - What to do about jsr with different types of local vars?
47 //  Need maps that are conditional on jsr path?
48 //  - Jsr and exceptions should be done more efficiently (the retAddr stuff)
49 //
50 //  Alternative:
51 //  - Could extend verifier to provide this information.
52 //    For: one fewer abstract interpreter to maintain. Against: the verifier
53 //    solves a bigger problem so slower (undesirable to force verification of
54 //    everything?).
55 //
56 //  Algorithm:
57 //    Partition bytecodes into basic blocks
58 //    For each basic block: store entry state (vars, stack). For instructions
59 //    inside basic blocks we do not store any state (instead we recompute it
60 //    from state produced by previous instruction).
61 //
62 //    Perform abstract interpretation of bytecodes over this lattice:
63 //
64 //                _--'#'--_
65 //               /  /  \   \
66 //             /   /     \   \
67 //            /    |     |     \
68 //          'r'   'v'   'p'   ' '
69 //           \     |     |     /
70 //            \    \     /    /
71 //              \   \   /    /
72 //                -- '@' --
73 //
74 //    '#'  top, result of conflict merge
75 //    'r'  reference type
76 //    'v'  value type
77 //    'p'  pc type for jsr/ret
78 //    ' '  uninitialized; never occurs on operand stack in Java
79 //    '@'  bottom/unexecuted; initial state each bytecode.
80 //
81 //    Basic block headers are the only merge points. We use this iteration to
82 //    compute the information:
83 //
84 //    find basic blocks;
85 //    initialize them with uninitialized state;
86 //    initialize first BB according to method signature;
87 //    mark first BB changed
88 //    while (some BB is changed) do {
89 //      perform abstract interpration of all bytecodes in BB;
90 //      merge exit state of BB into entry state of all successor BBs,
91 //      noting if any of these change;
92 //    }
93 //
94 //  One additional complication is necessary. The jsr instruction pushes
95 //  a return PC on the stack (a 'p' type in the abstract interpretation).
96 //  To be able to process "ret" bytecodes, we keep track of these return
97 //  PC's in a 'retAddrs' structure in abstract interpreter context (when
98 //  processing a "ret" bytecodes, it is not sufficient to know that it gets
99 //  an argument of the right type 'p'; we need to know which address it
100 //  returns to).
101 //
102 // (Note this comment is borrowed form the original author of the algorithm)
103 
104 // ComputeCallStack
105 //
106 // Specialization of SignatureIterator - compute the effects of a call
107 //
108 class ComputeCallStack : public SignatureIterator {
109   CellTypeState *_effect;
110   int _idx;
111 
112   void setup();
set(CellTypeState state)113   void set(CellTypeState state)         { _effect[_idx++] = state; }
length()114   int  length()                         { return _idx; };
115 
do_bool()116   virtual void do_bool  ()              { set(CellTypeState::value); };
do_char()117   virtual void do_char  ()              { set(CellTypeState::value); };
do_float()118   virtual void do_float ()              { set(CellTypeState::value); };
do_byte()119   virtual void do_byte  ()              { set(CellTypeState::value); };
do_short()120   virtual void do_short ()              { set(CellTypeState::value); };
do_int()121   virtual void do_int   ()              { set(CellTypeState::value); };
do_void()122   virtual void do_void  ()              { set(CellTypeState::bottom);};
do_object(int begin,int end)123   virtual void do_object(int begin, int end)  { set(CellTypeState::ref); };
do_array(int begin,int end)124   virtual void do_array (int begin, int end)  { set(CellTypeState::ref); };
125 
do_double()126   void do_double()                      { set(CellTypeState::value);
127                                           set(CellTypeState::value); }
do_long()128   void do_long  ()                      { set(CellTypeState::value);
129                                            set(CellTypeState::value); }
130 
131 public:
ComputeCallStack(Symbol * signature)132   ComputeCallStack(Symbol* signature) : SignatureIterator(signature) {};
133 
134   // Compute methods
compute_for_parameters(bool is_static,CellTypeState * effect)135   int compute_for_parameters(bool is_static, CellTypeState *effect) {
136     _idx    = 0;
137     _effect = effect;
138 
139     if (!is_static)
140       effect[_idx++] = CellTypeState::ref;
141 
142     iterate_parameters();
143 
144     return length();
145   };
146 
compute_for_returntype(CellTypeState * effect)147   int compute_for_returntype(CellTypeState *effect) {
148     _idx    = 0;
149     _effect = effect;
150     iterate_returntype();
151     set(CellTypeState::bottom);  // Always terminate with a bottom state, so ppush works
152 
153     return length();
154   }
155 };
156 
157 //=========================================================================================
158 // ComputeEntryStack
159 //
160 // Specialization of SignatureIterator - in order to set up first stack frame
161 //
162 class ComputeEntryStack : public SignatureIterator {
163   CellTypeState *_effect;
164   int _idx;
165 
166   void setup();
set(CellTypeState state)167   void set(CellTypeState state)         { _effect[_idx++] = state; }
length()168   int  length()                         { return _idx; };
169 
do_bool()170   virtual void do_bool  ()              { set(CellTypeState::value); };
do_char()171   virtual void do_char  ()              { set(CellTypeState::value); };
do_float()172   virtual void do_float ()              { set(CellTypeState::value); };
do_byte()173   virtual void do_byte  ()              { set(CellTypeState::value); };
do_short()174   virtual void do_short ()              { set(CellTypeState::value); };
do_int()175   virtual void do_int   ()              { set(CellTypeState::value); };
do_void()176   virtual void do_void  ()              { set(CellTypeState::bottom);};
do_object(int begin,int end)177   virtual void do_object(int begin, int end)  { set(CellTypeState::make_slot_ref(_idx)); }
do_array(int begin,int end)178   virtual void do_array (int begin, int end)  { set(CellTypeState::make_slot_ref(_idx)); }
179 
do_double()180   void do_double()                      { set(CellTypeState::value);
181                                           set(CellTypeState::value); }
do_long()182   void do_long  ()                      { set(CellTypeState::value);
183                                           set(CellTypeState::value); }
184 
185 public:
ComputeEntryStack(Symbol * signature)186   ComputeEntryStack(Symbol* signature) : SignatureIterator(signature) {};
187 
188   // Compute methods
compute_for_parameters(bool is_static,CellTypeState * effect)189   int compute_for_parameters(bool is_static, CellTypeState *effect) {
190     _idx    = 0;
191     _effect = effect;
192 
193     if (!is_static)
194       effect[_idx++] = CellTypeState::make_slot_ref(0);
195 
196     iterate_parameters();
197 
198     return length();
199   };
200 
compute_for_returntype(CellTypeState * effect)201   int compute_for_returntype(CellTypeState *effect) {
202     _idx    = 0;
203     _effect = effect;
204     iterate_returntype();
205     set(CellTypeState::bottom);  // Always terminate with a bottom state, so ppush works
206 
207     return length();
208   }
209 };
210 
211 //=====================================================================================
212 //
213 // Implementation of RetTable/RetTableEntry
214 //
215 // Contains function to itereate through all bytecodes
216 // and find all return entry points
217 //
218 int RetTable::_init_nof_entries = 10;
219 int RetTableEntry::_init_nof_jsrs = 5;
220 
RetTableEntry(int target,RetTableEntry * next)221 RetTableEntry::RetTableEntry(int target, RetTableEntry *next) {
222   _target_bci = target;
223   _jsrs = new GrowableArray<intptr_t>(_init_nof_jsrs);
224   _next = next;
225 }
226 
add_delta(int bci,int delta)227 void RetTableEntry::add_delta(int bci, int delta) {
228   if (_target_bci > bci) _target_bci += delta;
229 
230   for (int k = 0; k < _jsrs->length(); k++) {
231     int jsr = _jsrs->at(k);
232     if (jsr > bci) _jsrs->at_put(k, jsr+delta);
233   }
234 }
235 
compute_ret_table(const methodHandle & method)236 void RetTable::compute_ret_table(const methodHandle& method) {
237   BytecodeStream i(method);
238   Bytecodes::Code bytecode;
239 
240   while( (bytecode = i.next()) >= 0) {
241     switch (bytecode) {
242       case Bytecodes::_jsr:
243         add_jsr(i.next_bci(), i.dest());
244         break;
245       case Bytecodes::_jsr_w:
246         add_jsr(i.next_bci(), i.dest_w());
247         break;
248       default:
249         break;
250     }
251   }
252 }
253 
add_jsr(int return_bci,int target_bci)254 void RetTable::add_jsr(int return_bci, int target_bci) {
255   RetTableEntry* entry = _first;
256 
257   // Scan table for entry
258   for (;entry && entry->target_bci() != target_bci; entry = entry->next());
259 
260   if (!entry) {
261     // Allocate new entry and put in list
262     entry = new RetTableEntry(target_bci, _first);
263     _first = entry;
264   }
265 
266   // Now "entry" is set.  Make sure that the entry is initialized
267   // and has room for the new jsr.
268   entry->add_jsr(return_bci);
269 }
270 
find_jsrs_for_target(int targBci)271 RetTableEntry* RetTable::find_jsrs_for_target(int targBci) {
272   RetTableEntry *cur = _first;
273 
274   while(cur) {
275     assert(cur->target_bci() != -1, "sanity check");
276     if (cur->target_bci() == targBci)  return cur;
277     cur = cur->next();
278   }
279   ShouldNotReachHere();
280   return NULL;
281 }
282 
283 // The instruction at bci is changing size by "delta".  Update the return map.
update_ret_table(int bci,int delta)284 void RetTable::update_ret_table(int bci, int delta) {
285   RetTableEntry *cur = _first;
286   while(cur) {
287     cur->add_delta(bci, delta);
288     cur = cur->next();
289   }
290 }
291 
292 //
293 // Celltype state
294 //
295 
296 CellTypeState CellTypeState::bottom      = CellTypeState::make_bottom();
297 CellTypeState CellTypeState::uninit      = CellTypeState::make_any(uninit_value);
298 CellTypeState CellTypeState::ref         = CellTypeState::make_any(ref_conflict);
299 CellTypeState CellTypeState::value       = CellTypeState::make_any(val_value);
300 CellTypeState CellTypeState::refUninit   = CellTypeState::make_any(ref_conflict | uninit_value);
301 CellTypeState CellTypeState::top         = CellTypeState::make_top();
302 CellTypeState CellTypeState::addr        = CellTypeState::make_any(addr_conflict);
303 
304 // Commonly used constants
305 static CellTypeState epsilonCTS[1] = { CellTypeState::bottom };
306 static CellTypeState   refCTS   = CellTypeState::ref;
307 static CellTypeState   valCTS   = CellTypeState::value;
308 static CellTypeState    vCTS[2] = { CellTypeState::value, CellTypeState::bottom };
309 static CellTypeState    rCTS[2] = { CellTypeState::ref,   CellTypeState::bottom };
310 static CellTypeState   rrCTS[3] = { CellTypeState::ref,   CellTypeState::ref,   CellTypeState::bottom };
311 static CellTypeState   vrCTS[3] = { CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
312 static CellTypeState   vvCTS[3] = { CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
313 static CellTypeState  rvrCTS[4] = { CellTypeState::ref,   CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
314 static CellTypeState  vvrCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
315 static CellTypeState  vvvCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
316 static CellTypeState vvvrCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
317 static CellTypeState vvvvCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
318 
to_char() const319 char CellTypeState::to_char() const {
320   if (can_be_reference()) {
321     if (can_be_value() || can_be_address())
322       return '#';    // Conflict that needs to be rewritten
323     else
324       return 'r';
325   } else if (can_be_value())
326     return 'v';
327   else if (can_be_address())
328     return 'p';
329   else if (can_be_uninit())
330     return ' ';
331   else
332     return '@';
333 }
334 
335 
336 // Print a detailed CellTypeState.  Indicate all bits that are set.  If
337 // the CellTypeState represents an address or a reference, print the
338 // value of the additional information.
print(outputStream * os)339 void CellTypeState::print(outputStream *os) {
340   if (can_be_address()) {
341     os->print("(p");
342   } else {
343     os->print("( ");
344   }
345   if (can_be_reference()) {
346     os->print("r");
347   } else {
348     os->print(" ");
349   }
350   if (can_be_value()) {
351     os->print("v");
352   } else {
353     os->print(" ");
354   }
355   if (can_be_uninit()) {
356     os->print("u|");
357   } else {
358     os->print(" |");
359   }
360   if (is_info_top()) {
361     os->print("Top)");
362   } else if (is_info_bottom()) {
363     os->print("Bot)");
364   } else {
365     if (is_reference()) {
366       int info = get_info();
367       int data = info & ~(ref_not_lock_bit | ref_slot_bit);
368       if (info & ref_not_lock_bit) {
369         // Not a monitor lock reference.
370         if (info & ref_slot_bit) {
371           // slot
372           os->print("slot%d)", data);
373         } else {
374           // line
375           os->print("line%d)", data);
376         }
377       } else {
378         // lock
379         os->print("lock%d)", data);
380       }
381     } else {
382       os->print("%d)", get_info());
383     }
384   }
385 }
386 
387 //
388 // Basicblock handling methods
389 //
390 
initialize_bb()391 void GenerateOopMap::initialize_bb() {
392   _gc_points = 0;
393   _bb_count  = 0;
394   _bb_hdr_bits.reinitialize(method()->code_size());
395 }
396 
bb_mark_fct(GenerateOopMap * c,int bci,int * data)397 void GenerateOopMap::bb_mark_fct(GenerateOopMap *c, int bci, int *data) {
398   assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
399   if (c->is_bb_header(bci))
400      return;
401 
402   if (TraceNewOopMapGeneration) {
403      tty->print_cr("Basicblock#%d begins at: %d", c->_bb_count, bci);
404   }
405   c->set_bbmark_bit(bci);
406   c->_bb_count++;
407 }
408 
409 
mark_bbheaders_and_count_gc_points()410 void GenerateOopMap::mark_bbheaders_and_count_gc_points() {
411   initialize_bb();
412 
413   bool fellThrough = false;  // False to get first BB marked.
414 
415   // First mark all exception handlers as start of a basic-block
416   ExceptionTable excps(method());
417   for(int i = 0; i < excps.length(); i ++) {
418     bb_mark_fct(this, excps.handler_pc(i), NULL);
419   }
420 
421   // Then iterate through the code
422   BytecodeStream bcs(_method);
423   Bytecodes::Code bytecode;
424 
425   while( (bytecode = bcs.next()) >= 0) {
426     int bci = bcs.bci();
427 
428     if (!fellThrough)
429         bb_mark_fct(this, bci, NULL);
430 
431     fellThrough = jump_targets_do(&bcs, &GenerateOopMap::bb_mark_fct, NULL);
432 
433      /* We will also mark successors of jsr's as basic block headers. */
434     switch (bytecode) {
435       case Bytecodes::_jsr:
436         assert(!fellThrough, "should not happen");
437         bb_mark_fct(this, bci + Bytecodes::length_for(bytecode), NULL);
438         break;
439       case Bytecodes::_jsr_w:
440         assert(!fellThrough, "should not happen");
441         bb_mark_fct(this, bci + Bytecodes::length_for(bytecode), NULL);
442         break;
443       default:
444         break;
445     }
446 
447     if (possible_gc_point(&bcs))
448       _gc_points++;
449   }
450 }
451 
set_bbmark_bit(int bci)452 void GenerateOopMap::set_bbmark_bit(int bci) {
453   _bb_hdr_bits.at_put(bci, true);
454 }
455 
reachable_basicblock(GenerateOopMap * c,int bci,int * data)456 void GenerateOopMap::reachable_basicblock(GenerateOopMap *c, int bci, int *data) {
457   assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
458   BasicBlock* bb = c->get_basic_block_at(bci);
459   if (bb->is_dead()) {
460     bb->mark_as_alive();
461     *data = 1; // Mark basicblock as changed
462   }
463 }
464 
465 
mark_reachable_code()466 void GenerateOopMap::mark_reachable_code() {
467   int change = 1; // int to get function pointers to work
468 
469   // Mark entry basic block as alive and all exception handlers
470   _basic_blocks[0].mark_as_alive();
471   ExceptionTable excps(method());
472   for(int i = 0; i < excps.length(); i++) {
473     BasicBlock *bb = get_basic_block_at(excps.handler_pc(i));
474     // If block is not already alive (due to multiple exception handlers to same bb), then
475     // make it alive
476     if (bb->is_dead()) bb->mark_as_alive();
477   }
478 
479   BytecodeStream bcs(_method);
480 
481   // Iterate through all basic blocks until we reach a fixpoint
482   while (change) {
483     change = 0;
484 
485     for (int i = 0; i < _bb_count; i++) {
486       BasicBlock *bb = &_basic_blocks[i];
487       if (bb->is_alive()) {
488         // Position bytecodestream at last bytecode in basicblock
489         bcs.set_start(bb->_end_bci);
490         bcs.next();
491         Bytecodes::Code bytecode = bcs.code();
492         int bci = bcs.bci();
493         assert(bci == bb->_end_bci, "wrong bci");
494 
495         bool fell_through = jump_targets_do(&bcs, &GenerateOopMap::reachable_basicblock, &change);
496 
497         // We will also mark successors of jsr's as alive.
498         switch (bytecode) {
499           case Bytecodes::_jsr:
500           case Bytecodes::_jsr_w:
501             assert(!fell_through, "should not happen");
502             reachable_basicblock(this, bci + Bytecodes::length_for(bytecode), &change);
503             break;
504           default:
505             break;
506         }
507         if (fell_through) {
508           // Mark successor as alive
509           if (bb[1].is_dead()) {
510             bb[1].mark_as_alive();
511             change = 1;
512           }
513         }
514       }
515     }
516   }
517 }
518 
519 /* If the current instruction in "c" has no effect on control flow,
520    returns "true".  Otherwise, calls "jmpFct" one or more times, with
521    "c", an appropriate "pcDelta", and "data" as arguments, then
522    returns "false".  There is one exception: if the current
523    instruction is a "ret", returns "false" without calling "jmpFct".
524    Arrangements for tracking the control flow of a "ret" must be made
525    externally. */
jump_targets_do(BytecodeStream * bcs,jmpFct_t jmpFct,int * data)526 bool GenerateOopMap::jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int *data) {
527   int bci = bcs->bci();
528 
529   switch (bcs->code()) {
530     case Bytecodes::_ifeq:
531     case Bytecodes::_ifne:
532     case Bytecodes::_iflt:
533     case Bytecodes::_ifge:
534     case Bytecodes::_ifgt:
535     case Bytecodes::_ifle:
536     case Bytecodes::_if_icmpeq:
537     case Bytecodes::_if_icmpne:
538     case Bytecodes::_if_icmplt:
539     case Bytecodes::_if_icmpge:
540     case Bytecodes::_if_icmpgt:
541     case Bytecodes::_if_icmple:
542     case Bytecodes::_if_acmpeq:
543     case Bytecodes::_if_acmpne:
544     case Bytecodes::_ifnull:
545     case Bytecodes::_ifnonnull:
546       (*jmpFct)(this, bcs->dest(), data);
547       (*jmpFct)(this, bci + 3, data);
548       break;
549 
550     case Bytecodes::_goto:
551       (*jmpFct)(this, bcs->dest(), data);
552       break;
553     case Bytecodes::_goto_w:
554       (*jmpFct)(this, bcs->dest_w(), data);
555       break;
556     case Bytecodes::_tableswitch:
557       { Bytecode_tableswitch tableswitch(method(), bcs->bcp());
558         int len = tableswitch.length();
559 
560         (*jmpFct)(this, bci + tableswitch.default_offset(), data); /* Default. jump address */
561         while (--len >= 0) {
562           (*jmpFct)(this, bci + tableswitch.dest_offset_at(len), data);
563         }
564         break;
565       }
566 
567     case Bytecodes::_lookupswitch:
568       { Bytecode_lookupswitch lookupswitch(method(), bcs->bcp());
569         int npairs = lookupswitch.number_of_pairs();
570         (*jmpFct)(this, bci + lookupswitch.default_offset(), data); /* Default. */
571         while(--npairs >= 0) {
572           LookupswitchPair pair = lookupswitch.pair_at(npairs);
573           (*jmpFct)(this, bci + pair.offset(), data);
574         }
575         break;
576       }
577     case Bytecodes::_jsr:
578       assert(bcs->is_wide()==false, "sanity check");
579       (*jmpFct)(this, bcs->dest(), data);
580 
581 
582 
583       break;
584     case Bytecodes::_jsr_w:
585       (*jmpFct)(this, bcs->dest_w(), data);
586       break;
587     case Bytecodes::_wide:
588       ShouldNotReachHere();
589       return true;
590       break;
591     case Bytecodes::_athrow:
592     case Bytecodes::_ireturn:
593     case Bytecodes::_lreturn:
594     case Bytecodes::_freturn:
595     case Bytecodes::_dreturn:
596     case Bytecodes::_areturn:
597     case Bytecodes::_return:
598     case Bytecodes::_ret:
599       break;
600     default:
601       return true;
602   }
603   return false;
604 }
605 
606 /* Requires "pc" to be the head of a basic block; returns that basic
607    block. */
get_basic_block_at(int bci) const608 BasicBlock *GenerateOopMap::get_basic_block_at(int bci) const {
609   BasicBlock* bb = get_basic_block_containing(bci);
610   assert(bb->_bci == bci, "should have found BB");
611   return bb;
612 }
613 
614 // Requires "pc" to be the start of an instruction; returns the basic
615 //   block containing that instruction. */
get_basic_block_containing(int bci) const616 BasicBlock  *GenerateOopMap::get_basic_block_containing(int bci) const {
617   BasicBlock *bbs = _basic_blocks;
618   int lo = 0, hi = _bb_count - 1;
619 
620   while (lo <= hi) {
621     int m = (lo + hi) / 2;
622     int mbci = bbs[m]._bci;
623     int nbci;
624 
625     if ( m == _bb_count-1) {
626       assert( bci >= mbci && bci < method()->code_size(), "sanity check failed");
627       return bbs+m;
628     } else {
629       nbci = bbs[m+1]._bci;
630     }
631 
632     if ( mbci <= bci && bci < nbci) {
633       return bbs+m;
634     } else if (mbci < bci) {
635       lo = m + 1;
636     } else {
637       assert(mbci > bci, "sanity check");
638       hi = m - 1;
639     }
640   }
641 
642   fatal("should have found BB");
643   return NULL;
644 }
645 
restore_state(BasicBlock * bb)646 void GenerateOopMap::restore_state(BasicBlock *bb)
647 {
648   memcpy(_state, bb->_state, _state_len*sizeof(CellTypeState));
649   _stack_top = bb->_stack_top;
650   _monitor_top = bb->_monitor_top;
651 }
652 
next_bb_start_pc(BasicBlock * bb)653 int GenerateOopMap::next_bb_start_pc(BasicBlock *bb) {
654  int bbNum = bb - _basic_blocks + 1;
655  if (bbNum == _bb_count)
656     return method()->code_size();
657 
658  return _basic_blocks[bbNum]._bci;
659 }
660 
661 //
662 // CellType handling methods
663 //
664 
665 // Allocate memory and throw LinkageError if failure.
666 #define ALLOC_RESOURCE_ARRAY(var, type, count) \
667   var = NEW_RESOURCE_ARRAY_RETURN_NULL(type, count);              \
668   if (var == NULL) {                                              \
669     report_error("Cannot reserve enough memory to analyze this method"); \
670     return;                                                       \
671   }
672 
673 
init_state()674 void GenerateOopMap::init_state() {
675   _state_len     = _max_locals + _max_stack + _max_monitors;
676   ALLOC_RESOURCE_ARRAY(_state, CellTypeState, _state_len);
677   memset(_state, 0, _state_len * sizeof(CellTypeState));
678   int count = MAX3(_max_locals, _max_stack, _max_monitors) + 1/*for null terminator char */;
679   ALLOC_RESOURCE_ARRAY(_state_vec_buf, char, count);
680 }
681 
make_context_uninitialized()682 void GenerateOopMap::make_context_uninitialized() {
683   CellTypeState* vs = vars();
684 
685   for (int i = 0; i < _max_locals; i++)
686       vs[i] = CellTypeState::uninit;
687 
688   _stack_top = 0;
689   _monitor_top = 0;
690 }
691 
methodsig_to_effect(Symbol * signature,bool is_static,CellTypeState * effect)692 int GenerateOopMap::methodsig_to_effect(Symbol* signature, bool is_static, CellTypeState* effect) {
693   ComputeEntryStack ces(signature);
694   return ces.compute_for_parameters(is_static, effect);
695 }
696 
697 // Return result of merging cts1 and cts2.
merge(CellTypeState cts,int slot) const698 CellTypeState CellTypeState::merge(CellTypeState cts, int slot) const {
699   CellTypeState result;
700 
701   assert(!is_bottom() && !cts.is_bottom(),
702          "merge of bottom values is handled elsewhere");
703 
704   result._state = _state | cts._state;
705 
706   // If the top bit is set, we don't need to do any more work.
707   if (!result.is_info_top()) {
708     assert((result.can_be_address() || result.can_be_reference()),
709            "only addresses and references have non-top info");
710 
711     if (!equal(cts)) {
712       // The two values being merged are different.  Raise to top.
713       if (result.is_reference()) {
714         result = CellTypeState::make_slot_ref(slot);
715       } else {
716         result._state |= info_conflict;
717       }
718     }
719   }
720   assert(result.is_valid_state(), "checking that CTS merge maintains legal state");
721 
722   return result;
723 }
724 
725 // Merge the variable state for locals and stack from cts into bbts.
merge_local_state_vectors(CellTypeState * cts,CellTypeState * bbts)726 bool GenerateOopMap::merge_local_state_vectors(CellTypeState* cts,
727                                                CellTypeState* bbts) {
728   int i;
729   int len = _max_locals + _stack_top;
730   bool change = false;
731 
732   for (i = len - 1; i >= 0; i--) {
733     CellTypeState v = cts[i].merge(bbts[i], i);
734     change = change || !v.equal(bbts[i]);
735     bbts[i] = v;
736   }
737 
738   return change;
739 }
740 
741 // Merge the monitor stack state from cts into bbts.
merge_monitor_state_vectors(CellTypeState * cts,CellTypeState * bbts)742 bool GenerateOopMap::merge_monitor_state_vectors(CellTypeState* cts,
743                                                  CellTypeState* bbts) {
744   bool change = false;
745   if (_max_monitors > 0 && _monitor_top != bad_monitors) {
746     // If there are no monitors in the program, or there has been
747     // a monitor matching error before this point in the program,
748     // then we do not merge in the monitor state.
749 
750     int base = _max_locals + _max_stack;
751     int len = base + _monitor_top;
752     for (int i = len - 1; i >= base; i--) {
753       CellTypeState v = cts[i].merge(bbts[i], i);
754 
755       // Can we prove that, when there has been a change, it will already
756       // have been detected at this point?  That would make this equal
757       // check here unnecessary.
758       change = change || !v.equal(bbts[i]);
759       bbts[i] = v;
760     }
761   }
762 
763   return change;
764 }
765 
copy_state(CellTypeState * dst,CellTypeState * src)766 void GenerateOopMap::copy_state(CellTypeState *dst, CellTypeState *src) {
767   int len = _max_locals + _stack_top;
768   for (int i = 0; i < len; i++) {
769     if (src[i].is_nonlock_reference()) {
770       dst[i] = CellTypeState::make_slot_ref(i);
771     } else {
772       dst[i] = src[i];
773     }
774   }
775   if (_max_monitors > 0 && _monitor_top != bad_monitors) {
776     int base = _max_locals + _max_stack;
777     len = base + _monitor_top;
778     for (int i = base; i < len; i++) {
779       dst[i] = src[i];
780     }
781   }
782 }
783 
784 
785 // Merge the states for the current block and the next.  As long as a
786 // block is reachable the locals and stack must be merged.  If the
787 // stack heights don't match then this is a verification error and
788 // it's impossible to interpret the code.  Simultaneously monitor
789 // states are being check to see if they nest statically.  If monitor
790 // depths match up then their states are merged.  Otherwise the
791 // mismatch is simply recorded and interpretation continues since
792 // monitor matching is purely informational and doesn't say anything
793 // about the correctness of the code.
merge_state_into_bb(BasicBlock * bb)794 void GenerateOopMap::merge_state_into_bb(BasicBlock *bb) {
795   guarantee(bb != NULL, "null basicblock");
796   assert(bb->is_alive(), "merging state into a dead basicblock");
797 
798   if (_stack_top == bb->_stack_top) {
799     // always merge local state even if monitors don't match.
800     if (merge_local_state_vectors(_state, bb->_state)) {
801       bb->set_changed(true);
802     }
803     if (_monitor_top == bb->_monitor_top) {
804       // monitors still match so continue merging monitor states.
805       if (merge_monitor_state_vectors(_state, bb->_state)) {
806         bb->set_changed(true);
807       }
808     } else {
809       if (log_is_enabled(Info, monitormismatch)) {
810         report_monitor_mismatch("monitor stack height merge conflict");
811       }
812       // When the monitor stacks are not matched, we set _monitor_top to
813       // bad_monitors.  This signals that, from here on, the monitor stack cannot
814       // be trusted.  In particular, monitorexit bytecodes may throw
815       // exceptions.  We mark this block as changed so that the change
816       // propagates properly.
817       bb->_monitor_top = bad_monitors;
818       bb->set_changed(true);
819       _monitor_safe = false;
820     }
821   } else if (!bb->is_reachable()) {
822     // First time we look at this  BB
823     copy_state(bb->_state, _state);
824     bb->_stack_top = _stack_top;
825     bb->_monitor_top = _monitor_top;
826     bb->set_changed(true);
827   } else {
828     verify_error("stack height conflict: %d vs. %d",  _stack_top, bb->_stack_top);
829   }
830 }
831 
merge_state(GenerateOopMap * gom,int bci,int * data)832 void GenerateOopMap::merge_state(GenerateOopMap *gom, int bci, int* data) {
833    gom->merge_state_into_bb(gom->get_basic_block_at(bci));
834 }
835 
set_var(int localNo,CellTypeState cts)836 void GenerateOopMap::set_var(int localNo, CellTypeState cts) {
837   assert(cts.is_reference() || cts.is_value() || cts.is_address(),
838          "wrong celltypestate");
839   if (localNo < 0 || localNo > _max_locals) {
840     verify_error("variable write error: r%d", localNo);
841     return;
842   }
843   vars()[localNo] = cts;
844 }
845 
get_var(int localNo)846 CellTypeState GenerateOopMap::get_var(int localNo) {
847   assert(localNo < _max_locals + _nof_refval_conflicts, "variable read error");
848   if (localNo < 0 || localNo > _max_locals) {
849     verify_error("variable read error: r%d", localNo);
850     return valCTS; // just to pick something;
851   }
852   return vars()[localNo];
853 }
854 
pop()855 CellTypeState GenerateOopMap::pop() {
856   if ( _stack_top <= 0) {
857     verify_error("stack underflow");
858     return valCTS; // just to pick something
859   }
860   return  stack()[--_stack_top];
861 }
862 
push(CellTypeState cts)863 void GenerateOopMap::push(CellTypeState cts) {
864   if ( _stack_top >= _max_stack) {
865     verify_error("stack overflow");
866     return;
867   }
868   stack()[_stack_top++] = cts;
869 }
870 
monitor_pop()871 CellTypeState GenerateOopMap::monitor_pop() {
872   assert(_monitor_top != bad_monitors, "monitor_pop called on error monitor stack");
873   if (_monitor_top == 0) {
874     // We have detected a pop of an empty monitor stack.
875     _monitor_safe = false;
876      _monitor_top = bad_monitors;
877 
878     if (log_is_enabled(Info, monitormismatch)) {
879       report_monitor_mismatch("monitor stack underflow");
880     }
881     return CellTypeState::ref; // just to keep the analysis going.
882   }
883   return  monitors()[--_monitor_top];
884 }
885 
monitor_push(CellTypeState cts)886 void GenerateOopMap::monitor_push(CellTypeState cts) {
887   assert(_monitor_top != bad_monitors, "monitor_push called on error monitor stack");
888   if (_monitor_top >= _max_monitors) {
889     // Some monitorenter is being executed more than once.
890     // This means that the monitor stack cannot be simulated.
891     _monitor_safe = false;
892     _monitor_top = bad_monitors;
893 
894     if (log_is_enabled(Info, monitormismatch)) {
895       report_monitor_mismatch("monitor stack overflow");
896     }
897     return;
898   }
899   monitors()[_monitor_top++] = cts;
900 }
901 
902 //
903 // Interpretation handling methods
904 //
905 
do_interpretation()906 void GenerateOopMap::do_interpretation()
907 {
908   // "i" is just for debugging, so we can detect cases where this loop is
909   // iterated more than once.
910   int i = 0;
911   do {
912 #ifndef PRODUCT
913     if (TraceNewOopMapGeneration) {
914       tty->print("\n\nIteration #%d of do_interpretation loop, method:\n", i);
915       method()->print_name(tty);
916       tty->print("\n\n");
917     }
918 #endif
919     _conflict = false;
920     _monitor_safe = true;
921     // init_state is now called from init_basic_blocks.  The length of a
922     // state vector cannot be determined until we have made a pass through
923     // the bytecodes counting the possible monitor entries.
924     if (!_got_error) init_basic_blocks();
925     if (!_got_error) setup_method_entry_state();
926     if (!_got_error) interp_all();
927     if (!_got_error) rewrite_refval_conflicts();
928     i++;
929   } while (_conflict && !_got_error);
930 }
931 
init_basic_blocks()932 void GenerateOopMap::init_basic_blocks() {
933   // Note: Could consider reserving only the needed space for each BB's state
934   // (entry stack may not be of maximal height for every basic block).
935   // But cumbersome since we don't know the stack heights yet.  (Nor the
936   // monitor stack heights...)
937 
938   ALLOC_RESOURCE_ARRAY(_basic_blocks, BasicBlock, _bb_count);
939 
940   // Make a pass through the bytecodes.  Count the number of monitorenters.
941   // This can be used an upper bound on the monitor stack depth in programs
942   // which obey stack discipline with their monitor usage.  Initialize the
943   // known information about basic blocks.
944   BytecodeStream j(_method);
945   Bytecodes::Code bytecode;
946 
947   int bbNo = 0;
948   int monitor_count = 0;
949   int prev_bci = -1;
950   while( (bytecode = j.next()) >= 0) {
951     if (j.code() == Bytecodes::_monitorenter) {
952       monitor_count++;
953     }
954 
955     int bci = j.bci();
956     if (is_bb_header(bci)) {
957       // Initialize the basicblock structure
958       BasicBlock *bb   = _basic_blocks + bbNo;
959       bb->_bci         = bci;
960       bb->_max_locals  = _max_locals;
961       bb->_max_stack   = _max_stack;
962       bb->set_changed(false);
963       bb->_stack_top   = BasicBlock::_dead_basic_block; // Initialize all basicblocks are dead.
964       bb->_monitor_top = bad_monitors;
965 
966       if (bbNo > 0) {
967         _basic_blocks[bbNo - 1]._end_bci = prev_bci;
968       }
969 
970       bbNo++;
971     }
972     // Remember prevous bci.
973     prev_bci = bci;
974   }
975   // Set
976   _basic_blocks[bbNo-1]._end_bci = prev_bci;
977 
978 
979   // Check that the correct number of basicblocks was found
980   if (bbNo !=_bb_count) {
981     if (bbNo < _bb_count) {
982       verify_error("jump into the middle of instruction?");
983       return;
984     } else {
985       verify_error("extra basic blocks - should not happen?");
986       return;
987     }
988   }
989 
990   _max_monitors = monitor_count;
991 
992   // Now that we have a bound on the depth of the monitor stack, we can
993   // initialize the CellTypeState-related information.
994   init_state();
995 
996   // We allocate space for all state-vectors for all basicblocks in one huge
997   // chunk.  Then in the next part of the code, we set a pointer in each
998   // _basic_block that points to each piece.
999 
1000   // The product of bbNo and _state_len can get large if there are lots of
1001   // basic blocks and stack/locals/monitors.  Need to check to make sure
1002   // we don't overflow the capacity of a pointer.
1003   if ((unsigned)bbNo > UINTPTR_MAX / sizeof(CellTypeState) / _state_len) {
1004     report_error("The amount of memory required to analyze this method "
1005                  "exceeds addressable range");
1006     return;
1007   }
1008 
1009   CellTypeState *basicBlockState;
1010   ALLOC_RESOURCE_ARRAY(basicBlockState, CellTypeState, bbNo * _state_len);
1011   memset(basicBlockState, 0, bbNo * _state_len * sizeof(CellTypeState));
1012 
1013   // Make a pass over the basicblocks and assign their state vectors.
1014   for (int blockNum=0; blockNum < bbNo; blockNum++) {
1015     BasicBlock *bb = _basic_blocks + blockNum;
1016     bb->_state = basicBlockState + blockNum * _state_len;
1017 
1018 #ifdef ASSERT
1019     if (blockNum + 1 < bbNo) {
1020       address bcp = _method->bcp_from(bb->_end_bci);
1021       int bc_len = Bytecodes::java_length_at(_method(), bcp);
1022       assert(bb->_end_bci + bc_len == bb[1]._bci, "unmatched bci info in basicblock");
1023     }
1024 #endif
1025   }
1026 #ifdef ASSERT
1027   { BasicBlock *bb = &_basic_blocks[bbNo-1];
1028     address bcp = _method->bcp_from(bb->_end_bci);
1029     int bc_len = Bytecodes::java_length_at(_method(), bcp);
1030     assert(bb->_end_bci + bc_len == _method->code_size(), "wrong end bci");
1031   }
1032 #endif
1033 
1034   // Mark all alive blocks
1035   mark_reachable_code();
1036 }
1037 
setup_method_entry_state()1038 void GenerateOopMap::setup_method_entry_state() {
1039 
1040     // Initialize all locals to 'uninit' and set stack-height to 0
1041     make_context_uninitialized();
1042 
1043     // Initialize CellState type of arguments
1044     methodsig_to_effect(method()->signature(), method()->is_static(), vars());
1045 
1046     // If some references must be pre-assigned to null, then set that up
1047     initialize_vars();
1048 
1049     // This is the start state
1050     merge_state_into_bb(&_basic_blocks[0]);
1051 
1052     assert(_basic_blocks[0].changed(), "we are not getting off the ground");
1053 }
1054 
1055 // The instruction at bci is changing size by "delta".  Update the basic blocks.
update_basic_blocks(int bci,int delta,int new_method_size)1056 void GenerateOopMap::update_basic_blocks(int bci, int delta,
1057                                          int new_method_size) {
1058   assert(new_method_size >= method()->code_size() + delta,
1059          "new method size is too small");
1060 
1061   _bb_hdr_bits.reinitialize(new_method_size);
1062 
1063   for(int k = 0; k < _bb_count; k++) {
1064     if (_basic_blocks[k]._bci > bci) {
1065       _basic_blocks[k]._bci     += delta;
1066       _basic_blocks[k]._end_bci += delta;
1067     }
1068     _bb_hdr_bits.at_put(_basic_blocks[k]._bci, true);
1069   }
1070 }
1071 
1072 //
1073 // Initvars handling
1074 //
1075 
initialize_vars()1076 void GenerateOopMap::initialize_vars() {
1077   for (int k = 0; k < _init_vars->length(); k++)
1078     _state[_init_vars->at(k)] = CellTypeState::make_slot_ref(k);
1079 }
1080 
add_to_ref_init_set(int localNo)1081 void GenerateOopMap::add_to_ref_init_set(int localNo) {
1082 
1083   if (TraceNewOopMapGeneration)
1084     tty->print_cr("Added init vars: %d", localNo);
1085 
1086   // Is it already in the set?
1087   if (_init_vars->contains(localNo) )
1088     return;
1089 
1090    _init_vars->append(localNo);
1091 }
1092 
1093 //
1094 // Interpreration code
1095 //
1096 
interp_all()1097 void GenerateOopMap::interp_all() {
1098   bool change = true;
1099 
1100   while (change && !_got_error) {
1101     change = false;
1102     for (int i = 0; i < _bb_count && !_got_error; i++) {
1103       BasicBlock *bb = &_basic_blocks[i];
1104       if (bb->changed()) {
1105          if (_got_error) return;
1106          change = true;
1107          bb->set_changed(false);
1108          interp_bb(bb);
1109       }
1110     }
1111   }
1112 }
1113 
interp_bb(BasicBlock * bb)1114 void GenerateOopMap::interp_bb(BasicBlock *bb) {
1115 
1116   // We do not want to do anything in case the basic-block has not been initialized. This
1117   // will happen in the case where there is dead-code hang around in a method.
1118   assert(bb->is_reachable(), "should be reachable or deadcode exist");
1119   restore_state(bb);
1120 
1121   BytecodeStream itr(_method);
1122 
1123   // Set iterator interval to be the current basicblock
1124   int lim_bci = next_bb_start_pc(bb);
1125   itr.set_interval(bb->_bci, lim_bci);
1126   assert(lim_bci != bb->_bci, "must be at least one instruction in a basicblock");
1127   itr.next(); // read first instruction
1128 
1129   // Iterates through all bytecodes except the last in a basic block.
1130   // We handle the last one special, since there is controlflow change.
1131   while(itr.next_bci() < lim_bci && !_got_error) {
1132     if (_has_exceptions || _monitor_top != 0) {
1133       // We do not need to interpret the results of exceptional
1134       // continuation from this instruction when the method has no
1135       // exception handlers and the monitor stack is currently
1136       // empty.
1137       do_exception_edge(&itr);
1138     }
1139     interp1(&itr);
1140     itr.next();
1141   }
1142 
1143   // Handle last instruction.
1144   if (!_got_error) {
1145     assert(itr.next_bci() == lim_bci, "must point to end");
1146     if (_has_exceptions || _monitor_top != 0) {
1147       do_exception_edge(&itr);
1148     }
1149     interp1(&itr);
1150 
1151     bool fall_through = jump_targets_do(&itr, GenerateOopMap::merge_state, NULL);
1152     if (_got_error)  return;
1153 
1154     if (itr.code() == Bytecodes::_ret) {
1155       assert(!fall_through, "cannot be set if ret instruction");
1156       // Automatically handles 'wide' ret indicies
1157       ret_jump_targets_do(&itr, GenerateOopMap::merge_state, itr.get_index(), NULL);
1158     } else if (fall_through) {
1159      // Hit end of BB, but the instr. was a fall-through instruction,
1160      // so perform transition as if the BB ended in a "jump".
1161      if (lim_bci != bb[1]._bci) {
1162        verify_error("bytecodes fell through last instruction");
1163        return;
1164      }
1165      merge_state_into_bb(bb + 1);
1166     }
1167   }
1168 }
1169 
do_exception_edge(BytecodeStream * itr)1170 void GenerateOopMap::do_exception_edge(BytecodeStream* itr) {
1171   // Only check exception edge, if bytecode can trap
1172   if (!Bytecodes::can_trap(itr->code())) return;
1173   switch (itr->code()) {
1174     case Bytecodes::_aload_0:
1175       // These bytecodes can trap for rewriting.  We need to assume that
1176       // they do not throw exceptions to make the monitor analysis work.
1177       return;
1178 
1179     case Bytecodes::_ireturn:
1180     case Bytecodes::_lreturn:
1181     case Bytecodes::_freturn:
1182     case Bytecodes::_dreturn:
1183     case Bytecodes::_areturn:
1184     case Bytecodes::_return:
1185       // If the monitor stack height is not zero when we leave the method,
1186       // then we are either exiting with a non-empty stack or we have
1187       // found monitor trouble earlier in our analysis.  In either case,
1188       // assume an exception could be taken here.
1189       if (_monitor_top == 0) {
1190         return;
1191       }
1192       break;
1193 
1194     case Bytecodes::_monitorexit:
1195       // If the monitor stack height is bad_monitors, then we have detected a
1196       // monitor matching problem earlier in the analysis.  If the
1197       // monitor stack height is 0, we are about to pop a monitor
1198       // off of an empty stack.  In either case, the bytecode
1199       // could throw an exception.
1200       if (_monitor_top != bad_monitors && _monitor_top != 0) {
1201         return;
1202       }
1203       break;
1204 
1205     default:
1206       break;
1207   }
1208 
1209   if (_has_exceptions) {
1210     int bci = itr->bci();
1211     ExceptionTable exct(method());
1212     for(int i = 0; i< exct.length(); i++) {
1213       int start_pc   = exct.start_pc(i);
1214       int end_pc     = exct.end_pc(i);
1215       int handler_pc = exct.handler_pc(i);
1216       int catch_type = exct.catch_type_index(i);
1217 
1218       if (start_pc <= bci && bci < end_pc) {
1219         BasicBlock *excBB = get_basic_block_at(handler_pc);
1220         guarantee(excBB != NULL, "no basic block for exception");
1221         CellTypeState *excStk = excBB->stack();
1222         CellTypeState *cOpStck = stack();
1223         CellTypeState cOpStck_0 = cOpStck[0];
1224         int cOpStackTop = _stack_top;
1225 
1226         // Exception stacks are always the same.
1227         assert(method()->max_stack() > 0, "sanity check");
1228 
1229         // We remembered the size and first element of "cOpStck"
1230         // above; now we temporarily set them to the appropriate
1231         // values for an exception handler. */
1232         cOpStck[0] = CellTypeState::make_slot_ref(_max_locals);
1233         _stack_top = 1;
1234 
1235         merge_state_into_bb(excBB);
1236 
1237         // Now undo the temporary change.
1238         cOpStck[0] = cOpStck_0;
1239         _stack_top = cOpStackTop;
1240 
1241         // If this is a "catch all" handler, then we do not need to
1242         // consider any additional handlers.
1243         if (catch_type == 0) {
1244           return;
1245         }
1246       }
1247     }
1248   }
1249 
1250   // It is possible that none of the exception handlers would have caught
1251   // the exception.  In this case, we will exit the method.  We must
1252   // ensure that the monitor stack is empty in this case.
1253   if (_monitor_top == 0) {
1254     return;
1255   }
1256 
1257   // We pessimistically assume that this exception can escape the
1258   // method. (It is possible that it will always be caught, but
1259   // we don't care to analyse the types of the catch clauses.)
1260 
1261   // We don't set _monitor_top to bad_monitors because there are no successors
1262   // to this exceptional exit.
1263 
1264   if (log_is_enabled(Info, monitormismatch) && _monitor_safe) {
1265     // We check _monitor_safe so that we only report the first mismatched
1266     // exceptional exit.
1267     report_monitor_mismatch("non-empty monitor stack at exceptional exit");
1268   }
1269   _monitor_safe = false;
1270 
1271 }
1272 
report_monitor_mismatch(const char * msg)1273 void GenerateOopMap::report_monitor_mismatch(const char *msg) {
1274   ResourceMark rm;
1275   LogStream ls(Log(monitormismatch)::info());
1276   ls.print("Monitor mismatch in method ");
1277   method()->print_short_name(&ls);
1278   ls.print_cr(": %s", msg);
1279 }
1280 
print_states(outputStream * os,CellTypeState * vec,int num)1281 void GenerateOopMap::print_states(outputStream *os,
1282                                   CellTypeState* vec, int num) {
1283   for (int i = 0; i < num; i++) {
1284     vec[i].print(tty);
1285   }
1286 }
1287 
1288 // Print the state values at the current bytecode.
print_current_state(outputStream * os,BytecodeStream * currentBC,bool detailed)1289 void GenerateOopMap::print_current_state(outputStream   *os,
1290                                          BytecodeStream *currentBC,
1291                                          bool            detailed) {
1292   if (detailed) {
1293     os->print("     %4d vars     = ", currentBC->bci());
1294     print_states(os, vars(), _max_locals);
1295     os->print("    %s", Bytecodes::name(currentBC->code()));
1296   } else {
1297     os->print("    %4d  vars = '%s' ", currentBC->bci(),  state_vec_to_string(vars(), _max_locals));
1298     os->print("     stack = '%s' ", state_vec_to_string(stack(), _stack_top));
1299     if (_monitor_top != bad_monitors) {
1300       os->print("  monitors = '%s'  \t%s", state_vec_to_string(monitors(), _monitor_top), Bytecodes::name(currentBC->code()));
1301     } else {
1302       os->print("  [bad monitor stack]");
1303     }
1304   }
1305 
1306   switch(currentBC->code()) {
1307     case Bytecodes::_invokevirtual:
1308     case Bytecodes::_invokespecial:
1309     case Bytecodes::_invokestatic:
1310     case Bytecodes::_invokedynamic:
1311     case Bytecodes::_invokeinterface: {
1312       int idx = currentBC->has_index_u4() ? currentBC->get_index_u4() : currentBC->get_index_u2_cpcache();
1313       ConstantPool* cp      = method()->constants();
1314       int nameAndTypeIdx    = cp->name_and_type_ref_index_at(idx);
1315       int signatureIdx      = cp->signature_ref_index_at(nameAndTypeIdx);
1316       Symbol* signature     = cp->symbol_at(signatureIdx);
1317       os->print("%s", signature->as_C_string());
1318     }
1319     default:
1320       break;
1321   }
1322 
1323   if (detailed) {
1324     os->cr();
1325     os->print("          stack    = ");
1326     print_states(os, stack(), _stack_top);
1327     os->cr();
1328     if (_monitor_top != bad_monitors) {
1329       os->print("          monitors = ");
1330       print_states(os, monitors(), _monitor_top);
1331     } else {
1332       os->print("          [bad monitor stack]");
1333     }
1334   }
1335 
1336   os->cr();
1337 }
1338 
1339 // Sets the current state to be the state after executing the
1340 // current instruction, starting in the current state.
interp1(BytecodeStream * itr)1341 void GenerateOopMap::interp1(BytecodeStream *itr) {
1342   if (TraceNewOopMapGeneration) {
1343     print_current_state(tty, itr, TraceNewOopMapGenerationDetailed);
1344   }
1345 
1346   // Should we report the results? Result is reported *before* the instruction at the current bci is executed.
1347   // However, not for calls. For calls we do not want to include the arguments, so we postpone the reporting until
1348   // they have been popped (in method ppl).
1349   if (_report_result == true) {
1350     switch(itr->code()) {
1351       case Bytecodes::_invokevirtual:
1352       case Bytecodes::_invokespecial:
1353       case Bytecodes::_invokestatic:
1354       case Bytecodes::_invokedynamic:
1355       case Bytecodes::_invokeinterface:
1356         _itr_send = itr;
1357         _report_result_for_send = true;
1358         break;
1359       default:
1360        fill_stackmap_for_opcodes(itr, vars(), stack(), _stack_top);
1361        break;
1362     }
1363   }
1364 
1365   // abstract interpretation of current opcode
1366   switch(itr->code()) {
1367     case Bytecodes::_nop:                                           break;
1368     case Bytecodes::_goto:                                          break;
1369     case Bytecodes::_goto_w:                                        break;
1370     case Bytecodes::_iinc:                                          break;
1371     case Bytecodes::_return:            do_return_monitor_check();
1372                                         break;
1373 
1374     case Bytecodes::_aconst_null:
1375     case Bytecodes::_new:               ppush1(CellTypeState::make_line_ref(itr->bci()));
1376                                         break;
1377 
1378     case Bytecodes::_iconst_m1:
1379     case Bytecodes::_iconst_0:
1380     case Bytecodes::_iconst_1:
1381     case Bytecodes::_iconst_2:
1382     case Bytecodes::_iconst_3:
1383     case Bytecodes::_iconst_4:
1384     case Bytecodes::_iconst_5:
1385     case Bytecodes::_fconst_0:
1386     case Bytecodes::_fconst_1:
1387     case Bytecodes::_fconst_2:
1388     case Bytecodes::_bipush:
1389     case Bytecodes::_sipush:            ppush1(valCTS);             break;
1390 
1391     case Bytecodes::_lconst_0:
1392     case Bytecodes::_lconst_1:
1393     case Bytecodes::_dconst_0:
1394     case Bytecodes::_dconst_1:          ppush(vvCTS);               break;
1395 
1396     case Bytecodes::_ldc2_w:            ppush(vvCTS);               break;
1397 
1398     case Bytecodes::_ldc:               // fall through:
1399     case Bytecodes::_ldc_w:             do_ldc(itr->bci());         break;
1400 
1401     case Bytecodes::_iload:
1402     case Bytecodes::_fload:             ppload(vCTS, itr->get_index()); break;
1403 
1404     case Bytecodes::_lload:
1405     case Bytecodes::_dload:             ppload(vvCTS,itr->get_index()); break;
1406 
1407     case Bytecodes::_aload:             ppload(rCTS, itr->get_index()); break;
1408 
1409     case Bytecodes::_iload_0:
1410     case Bytecodes::_fload_0:           ppload(vCTS, 0);            break;
1411     case Bytecodes::_iload_1:
1412     case Bytecodes::_fload_1:           ppload(vCTS, 1);            break;
1413     case Bytecodes::_iload_2:
1414     case Bytecodes::_fload_2:           ppload(vCTS, 2);            break;
1415     case Bytecodes::_iload_3:
1416     case Bytecodes::_fload_3:           ppload(vCTS, 3);            break;
1417 
1418     case Bytecodes::_lload_0:
1419     case Bytecodes::_dload_0:           ppload(vvCTS, 0);           break;
1420     case Bytecodes::_lload_1:
1421     case Bytecodes::_dload_1:           ppload(vvCTS, 1);           break;
1422     case Bytecodes::_lload_2:
1423     case Bytecodes::_dload_2:           ppload(vvCTS, 2);           break;
1424     case Bytecodes::_lload_3:
1425     case Bytecodes::_dload_3:           ppload(vvCTS, 3);           break;
1426 
1427     case Bytecodes::_aload_0:           ppload(rCTS, 0);            break;
1428     case Bytecodes::_aload_1:           ppload(rCTS, 1);            break;
1429     case Bytecodes::_aload_2:           ppload(rCTS, 2);            break;
1430     case Bytecodes::_aload_3:           ppload(rCTS, 3);            break;
1431 
1432     case Bytecodes::_iaload:
1433     case Bytecodes::_faload:
1434     case Bytecodes::_baload:
1435     case Bytecodes::_caload:
1436     case Bytecodes::_saload:            pp(vrCTS, vCTS); break;
1437 
1438     case Bytecodes::_laload:            pp(vrCTS, vvCTS);  break;
1439     case Bytecodes::_daload:            pp(vrCTS, vvCTS); break;
1440 
1441     case Bytecodes::_aaload:            pp_new_ref(vrCTS, itr->bci()); break;
1442 
1443     case Bytecodes::_istore:
1444     case Bytecodes::_fstore:            ppstore(vCTS, itr->get_index()); break;
1445 
1446     case Bytecodes::_lstore:
1447     case Bytecodes::_dstore:            ppstore(vvCTS, itr->get_index()); break;
1448 
1449     case Bytecodes::_astore:            do_astore(itr->get_index());     break;
1450 
1451     case Bytecodes::_istore_0:
1452     case Bytecodes::_fstore_0:          ppstore(vCTS, 0);           break;
1453     case Bytecodes::_istore_1:
1454     case Bytecodes::_fstore_1:          ppstore(vCTS, 1);           break;
1455     case Bytecodes::_istore_2:
1456     case Bytecodes::_fstore_2:          ppstore(vCTS, 2);           break;
1457     case Bytecodes::_istore_3:
1458     case Bytecodes::_fstore_3:          ppstore(vCTS, 3);           break;
1459 
1460     case Bytecodes::_lstore_0:
1461     case Bytecodes::_dstore_0:          ppstore(vvCTS, 0);          break;
1462     case Bytecodes::_lstore_1:
1463     case Bytecodes::_dstore_1:          ppstore(vvCTS, 1);          break;
1464     case Bytecodes::_lstore_2:
1465     case Bytecodes::_dstore_2:          ppstore(vvCTS, 2);          break;
1466     case Bytecodes::_lstore_3:
1467     case Bytecodes::_dstore_3:          ppstore(vvCTS, 3);          break;
1468 
1469     case Bytecodes::_astore_0:          do_astore(0);               break;
1470     case Bytecodes::_astore_1:          do_astore(1);               break;
1471     case Bytecodes::_astore_2:          do_astore(2);               break;
1472     case Bytecodes::_astore_3:          do_astore(3);               break;
1473 
1474     case Bytecodes::_iastore:
1475     case Bytecodes::_fastore:
1476     case Bytecodes::_bastore:
1477     case Bytecodes::_castore:
1478     case Bytecodes::_sastore:           ppop(vvrCTS);               break;
1479     case Bytecodes::_lastore:
1480     case Bytecodes::_dastore:           ppop(vvvrCTS);              break;
1481     case Bytecodes::_aastore:           ppop(rvrCTS);               break;
1482 
1483     case Bytecodes::_pop:               ppop_any(1);                break;
1484     case Bytecodes::_pop2:              ppop_any(2);                break;
1485 
1486     case Bytecodes::_dup:               ppdupswap(1, "11");         break;
1487     case Bytecodes::_dup_x1:            ppdupswap(2, "121");        break;
1488     case Bytecodes::_dup_x2:            ppdupswap(3, "1321");       break;
1489     case Bytecodes::_dup2:              ppdupswap(2, "2121");       break;
1490     case Bytecodes::_dup2_x1:           ppdupswap(3, "21321");      break;
1491     case Bytecodes::_dup2_x2:           ppdupswap(4, "214321");     break;
1492     case Bytecodes::_swap:              ppdupswap(2, "12");         break;
1493 
1494     case Bytecodes::_iadd:
1495     case Bytecodes::_fadd:
1496     case Bytecodes::_isub:
1497     case Bytecodes::_fsub:
1498     case Bytecodes::_imul:
1499     case Bytecodes::_fmul:
1500     case Bytecodes::_idiv:
1501     case Bytecodes::_fdiv:
1502     case Bytecodes::_irem:
1503     case Bytecodes::_frem:
1504     case Bytecodes::_ishl:
1505     case Bytecodes::_ishr:
1506     case Bytecodes::_iushr:
1507     case Bytecodes::_iand:
1508     case Bytecodes::_ior:
1509     case Bytecodes::_ixor:
1510     case Bytecodes::_l2f:
1511     case Bytecodes::_l2i:
1512     case Bytecodes::_d2f:
1513     case Bytecodes::_d2i:
1514     case Bytecodes::_fcmpl:
1515     case Bytecodes::_fcmpg:             pp(vvCTS, vCTS); break;
1516 
1517     case Bytecodes::_ladd:
1518     case Bytecodes::_dadd:
1519     case Bytecodes::_lsub:
1520     case Bytecodes::_dsub:
1521     case Bytecodes::_lmul:
1522     case Bytecodes::_dmul:
1523     case Bytecodes::_ldiv:
1524     case Bytecodes::_ddiv:
1525     case Bytecodes::_lrem:
1526     case Bytecodes::_drem:
1527     case Bytecodes::_land:
1528     case Bytecodes::_lor:
1529     case Bytecodes::_lxor:              pp(vvvvCTS, vvCTS); break;
1530 
1531     case Bytecodes::_ineg:
1532     case Bytecodes::_fneg:
1533     case Bytecodes::_i2f:
1534     case Bytecodes::_f2i:
1535     case Bytecodes::_i2c:
1536     case Bytecodes::_i2s:
1537     case Bytecodes::_i2b:               pp(vCTS, vCTS); break;
1538 
1539     case Bytecodes::_lneg:
1540     case Bytecodes::_dneg:
1541     case Bytecodes::_l2d:
1542     case Bytecodes::_d2l:               pp(vvCTS, vvCTS); break;
1543 
1544     case Bytecodes::_lshl:
1545     case Bytecodes::_lshr:
1546     case Bytecodes::_lushr:             pp(vvvCTS, vvCTS); break;
1547 
1548     case Bytecodes::_i2l:
1549     case Bytecodes::_i2d:
1550     case Bytecodes::_f2l:
1551     case Bytecodes::_f2d:               pp(vCTS, vvCTS); break;
1552 
1553     case Bytecodes::_lcmp:              pp(vvvvCTS, vCTS); break;
1554     case Bytecodes::_dcmpl:
1555     case Bytecodes::_dcmpg:             pp(vvvvCTS, vCTS); break;
1556 
1557     case Bytecodes::_ifeq:
1558     case Bytecodes::_ifne:
1559     case Bytecodes::_iflt:
1560     case Bytecodes::_ifge:
1561     case Bytecodes::_ifgt:
1562     case Bytecodes::_ifle:
1563     case Bytecodes::_tableswitch:       ppop1(valCTS);
1564                                         break;
1565     case Bytecodes::_ireturn:
1566     case Bytecodes::_freturn:           do_return_monitor_check();
1567                                         ppop1(valCTS);
1568                                         break;
1569     case Bytecodes::_if_icmpeq:
1570     case Bytecodes::_if_icmpne:
1571     case Bytecodes::_if_icmplt:
1572     case Bytecodes::_if_icmpge:
1573     case Bytecodes::_if_icmpgt:
1574     case Bytecodes::_if_icmple:         ppop(vvCTS);
1575                                         break;
1576 
1577     case Bytecodes::_lreturn:           do_return_monitor_check();
1578                                         ppop(vvCTS);
1579                                         break;
1580 
1581     case Bytecodes::_dreturn:           do_return_monitor_check();
1582                                         ppop(vvCTS);
1583                                         break;
1584 
1585     case Bytecodes::_if_acmpeq:
1586     case Bytecodes::_if_acmpne:         ppop(rrCTS);                 break;
1587 
1588     case Bytecodes::_jsr:               do_jsr(itr->dest());         break;
1589     case Bytecodes::_jsr_w:             do_jsr(itr->dest_w());       break;
1590 
1591     case Bytecodes::_getstatic:         do_field(true,  true,  itr->get_index_u2_cpcache(), itr->bci()); break;
1592     case Bytecodes::_putstatic:         do_field(false, true,  itr->get_index_u2_cpcache(), itr->bci()); break;
1593     case Bytecodes::_getfield:          do_field(true,  false, itr->get_index_u2_cpcache(), itr->bci()); break;
1594     case Bytecodes::_putfield:          do_field(false, false, itr->get_index_u2_cpcache(), itr->bci()); break;
1595 
1596     case Bytecodes::_invokevirtual:
1597     case Bytecodes::_invokespecial:     do_method(false, false, itr->get_index_u2_cpcache(), itr->bci()); break;
1598     case Bytecodes::_invokestatic:      do_method(true,  false, itr->get_index_u2_cpcache(), itr->bci()); break;
1599     case Bytecodes::_invokedynamic:     do_method(true,  false, itr->get_index_u4(),         itr->bci()); break;
1600     case Bytecodes::_invokeinterface:   do_method(false, true,  itr->get_index_u2_cpcache(), itr->bci()); break;
1601     case Bytecodes::_newarray:
1602     case Bytecodes::_anewarray:         pp_new_ref(vCTS, itr->bci()); break;
1603     case Bytecodes::_checkcast:         do_checkcast(); break;
1604     case Bytecodes::_arraylength:
1605     case Bytecodes::_instanceof:        pp(rCTS, vCTS); break;
1606     case Bytecodes::_monitorenter:      do_monitorenter(itr->bci()); break;
1607     case Bytecodes::_monitorexit:       do_monitorexit(itr->bci()); break;
1608 
1609     case Bytecodes::_athrow:            // handled by do_exception_edge() BUT ...
1610                                         // vlh(apple): do_exception_edge() does not get
1611                                         // called if method has no exception handlers
1612                                         if ((!_has_exceptions) && (_monitor_top > 0)) {
1613                                           _monitor_safe = false;
1614                                         }
1615                                         break;
1616 
1617     case Bytecodes::_areturn:           do_return_monitor_check();
1618                                         ppop1(refCTS);
1619                                         break;
1620     case Bytecodes::_ifnull:
1621     case Bytecodes::_ifnonnull:         ppop1(refCTS); break;
1622     case Bytecodes::_multianewarray:    do_multianewarray(*(itr->bcp()+3), itr->bci()); break;
1623 
1624     case Bytecodes::_wide:              fatal("Iterator should skip this bytecode"); break;
1625     case Bytecodes::_ret:                                           break;
1626 
1627     // Java opcodes
1628     case Bytecodes::_lookupswitch:      ppop1(valCTS);             break;
1629 
1630     default:
1631          tty->print("unexpected opcode: %d\n", itr->code());
1632          ShouldNotReachHere();
1633     break;
1634   }
1635 }
1636 
check_type(CellTypeState expected,CellTypeState actual)1637 void GenerateOopMap::check_type(CellTypeState expected, CellTypeState actual) {
1638   if (!expected.equal_kind(actual)) {
1639     verify_error("wrong type on stack (found: %c expected: %c)", actual.to_char(), expected.to_char());
1640   }
1641 }
1642 
ppstore(CellTypeState * in,int loc_no)1643 void GenerateOopMap::ppstore(CellTypeState *in, int loc_no) {
1644   while(!(*in).is_bottom()) {
1645     CellTypeState expected =*in++;
1646     CellTypeState actual   = pop();
1647     check_type(expected, actual);
1648     assert(loc_no >= 0, "sanity check");
1649     set_var(loc_no++, actual);
1650   }
1651 }
1652 
ppload(CellTypeState * out,int loc_no)1653 void GenerateOopMap::ppload(CellTypeState *out, int loc_no) {
1654   while(!(*out).is_bottom()) {
1655     CellTypeState out1 = *out++;
1656     CellTypeState vcts = get_var(loc_no);
1657     assert(out1.can_be_reference() || out1.can_be_value(),
1658            "can only load refs. and values.");
1659     if (out1.is_reference()) {
1660       assert(loc_no>=0, "sanity check");
1661       if (!vcts.is_reference()) {
1662         // We were asked to push a reference, but the type of the
1663         // variable can be something else
1664         _conflict = true;
1665         if (vcts.can_be_uninit()) {
1666           // It is a ref-uninit conflict (at least). If there are other
1667           // problems, we'll get them in the next round
1668           add_to_ref_init_set(loc_no);
1669           vcts = out1;
1670         } else {
1671           // It wasn't a ref-uninit conflict. So must be a
1672           // ref-val or ref-pc conflict. Split the variable.
1673           record_refval_conflict(loc_no);
1674           vcts = out1;
1675         }
1676         push(out1); // recover...
1677       } else {
1678         push(vcts); // preserve reference.
1679       }
1680       // Otherwise it is a conflict, but one that verification would
1681       // have caught if illegal. In particular, it can't be a topCTS
1682       // resulting from mergeing two difference pcCTS's since the verifier
1683       // would have rejected any use of such a merge.
1684     } else {
1685       push(out1); // handle val/init conflict
1686     }
1687     loc_no++;
1688   }
1689 }
1690 
ppdupswap(int poplen,const char * out)1691 void GenerateOopMap::ppdupswap(int poplen, const char *out) {
1692   CellTypeState actual[5];
1693   assert(poplen < 5, "this must be less than length of actual vector");
1694 
1695   // Pop all arguments.
1696   for (int i = 0; i < poplen; i++) {
1697     actual[i] = pop();
1698   }
1699   // Field _state is uninitialized when calling push.
1700   for (int i = poplen; i < 5; i++) {
1701     actual[i] = CellTypeState::uninit;
1702   }
1703 
1704   // put them back
1705   char push_ch = *out++;
1706   while (push_ch != '\0') {
1707     int idx = push_ch - '1';
1708     assert(idx >= 0 && idx < poplen, "wrong arguments");
1709     push(actual[idx]);
1710     push_ch = *out++;
1711   }
1712 }
1713 
ppop1(CellTypeState out)1714 void GenerateOopMap::ppop1(CellTypeState out) {
1715   CellTypeState actual = pop();
1716   check_type(out, actual);
1717 }
1718 
ppop(CellTypeState * out)1719 void GenerateOopMap::ppop(CellTypeState *out) {
1720   while (!(*out).is_bottom()) {
1721     ppop1(*out++);
1722   }
1723 }
1724 
ppush1(CellTypeState in)1725 void GenerateOopMap::ppush1(CellTypeState in) {
1726   assert(in.is_reference() | in.is_value(), "sanity check");
1727   push(in);
1728 }
1729 
ppush(CellTypeState * in)1730 void GenerateOopMap::ppush(CellTypeState *in) {
1731   while (!(*in).is_bottom()) {
1732     ppush1(*in++);
1733   }
1734 }
1735 
pp(CellTypeState * in,CellTypeState * out)1736 void GenerateOopMap::pp(CellTypeState *in, CellTypeState *out) {
1737   ppop(in);
1738   ppush(out);
1739 }
1740 
pp_new_ref(CellTypeState * in,int bci)1741 void GenerateOopMap::pp_new_ref(CellTypeState *in, int bci) {
1742   ppop(in);
1743   ppush1(CellTypeState::make_line_ref(bci));
1744 }
1745 
ppop_any(int poplen)1746 void GenerateOopMap::ppop_any(int poplen) {
1747   if (_stack_top >= poplen) {
1748     _stack_top -= poplen;
1749   } else {
1750     verify_error("stack underflow");
1751   }
1752 }
1753 
1754 // Replace all occurences of the state 'match' with the state 'replace'
1755 // in our current state vector.
replace_all_CTS_matches(CellTypeState match,CellTypeState replace)1756 void GenerateOopMap::replace_all_CTS_matches(CellTypeState match,
1757                                              CellTypeState replace) {
1758   int i;
1759   int len = _max_locals + _stack_top;
1760   bool change = false;
1761 
1762   for (i = len - 1; i >= 0; i--) {
1763     if (match.equal(_state[i])) {
1764       _state[i] = replace;
1765     }
1766   }
1767 
1768   if (_monitor_top > 0) {
1769     int base = _max_locals + _max_stack;
1770     len = base + _monitor_top;
1771     for (i = len - 1; i >= base; i--) {
1772       if (match.equal(_state[i])) {
1773         _state[i] = replace;
1774       }
1775     }
1776   }
1777 }
1778 
do_checkcast()1779 void GenerateOopMap::do_checkcast() {
1780   CellTypeState actual = pop();
1781   check_type(refCTS, actual);
1782   push(actual);
1783 }
1784 
do_monitorenter(int bci)1785 void GenerateOopMap::do_monitorenter(int bci) {
1786   CellTypeState actual = pop();
1787   if (_monitor_top == bad_monitors) {
1788     return;
1789   }
1790 
1791   // Bail out when we get repeated locks on an identical monitor.  This case
1792   // isn't too hard to handle and can be made to work if supporting nested
1793   // redundant synchronized statements becomes a priority.
1794   //
1795   // See also "Note" in do_monitorexit(), below.
1796   if (actual.is_lock_reference()) {
1797     _monitor_top = bad_monitors;
1798     _monitor_safe = false;
1799 
1800     if (log_is_enabled(Info, monitormismatch)) {
1801       report_monitor_mismatch("nested redundant lock -- bailout...");
1802     }
1803     return;
1804   }
1805 
1806   CellTypeState lock = CellTypeState::make_lock_ref(bci);
1807   check_type(refCTS, actual);
1808   if (!actual.is_info_top()) {
1809     replace_all_CTS_matches(actual, lock);
1810     monitor_push(lock);
1811   }
1812 }
1813 
do_monitorexit(int bci)1814 void GenerateOopMap::do_monitorexit(int bci) {
1815   CellTypeState actual = pop();
1816   if (_monitor_top == bad_monitors) {
1817     return;
1818   }
1819   check_type(refCTS, actual);
1820   CellTypeState expected = monitor_pop();
1821   if (!actual.is_lock_reference() || !expected.equal(actual)) {
1822     // The monitor we are exiting is not verifiably the one
1823     // on the top of our monitor stack.  This causes a monitor
1824     // mismatch.
1825     _monitor_top = bad_monitors;
1826     _monitor_safe = false;
1827 
1828     // We need to mark this basic block as changed so that
1829     // this monitorexit will be visited again.  We need to
1830     // do this to ensure that we have accounted for the
1831     // possibility that this bytecode will throw an
1832     // exception.
1833     BasicBlock* bb = get_basic_block_containing(bci);
1834     guarantee(bb != NULL, "no basic block for bci");
1835     bb->set_changed(true);
1836     bb->_monitor_top = bad_monitors;
1837 
1838     if (log_is_enabled(Info, monitormismatch)) {
1839       report_monitor_mismatch("improper monitor pair");
1840     }
1841   } else {
1842     // This code is a fix for the case where we have repeated
1843     // locking of the same object in straightline code.  We clear
1844     // out the lock when it is popped from the monitor stack
1845     // and replace it with an unobtrusive reference value that can
1846     // be locked again.
1847     //
1848     // Note: when generateOopMap is fixed to properly handle repeated,
1849     //       nested, redundant locks on the same object, then this
1850     //       fix will need to be removed at that time.
1851     replace_all_CTS_matches(actual, CellTypeState::make_line_ref(bci));
1852   }
1853 }
1854 
do_return_monitor_check()1855 void GenerateOopMap::do_return_monitor_check() {
1856   if (_monitor_top > 0) {
1857     // The monitor stack must be empty when we leave the method
1858     // for the monitors to be properly matched.
1859     _monitor_safe = false;
1860 
1861     // Since there are no successors to the *return bytecode, it
1862     // isn't necessary to set _monitor_top to bad_monitors.
1863 
1864     if (log_is_enabled(Info, monitormismatch)) {
1865       report_monitor_mismatch("non-empty monitor stack at return");
1866     }
1867   }
1868 }
1869 
do_jsr(int targ_bci)1870 void GenerateOopMap::do_jsr(int targ_bci) {
1871   push(CellTypeState::make_addr(targ_bci));
1872 }
1873 
1874 
1875 
do_ldc(int bci)1876 void GenerateOopMap::do_ldc(int bci) {
1877   Bytecode_loadconstant ldc(method(), bci);
1878   ConstantPool* cp  = method()->constants();
1879   constantTag tag = cp->tag_at(ldc.pool_index()); // idx is index in resolved_references
1880   BasicType       bt  = ldc.result_type();
1881 #ifdef ASSERT
1882   BasicType   tag_bt = (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) ? bt : tag.basic_type();
1883   assert(bt == tag_bt, "same result");
1884 #endif
1885   CellTypeState   cts;
1886   if (is_reference_type(bt)) {  // could be T_ARRAY with condy
1887     assert(!tag.is_string_index() && !tag.is_klass_index(), "Unexpected index tag");
1888     cts = CellTypeState::make_line_ref(bci);
1889   } else {
1890     cts = valCTS;
1891   }
1892   ppush1(cts);
1893 }
1894 
do_multianewarray(int dims,int bci)1895 void GenerateOopMap::do_multianewarray(int dims, int bci) {
1896   assert(dims >= 1, "sanity check");
1897   for(int i = dims -1; i >=0; i--) {
1898     ppop1(valCTS);
1899   }
1900   ppush1(CellTypeState::make_line_ref(bci));
1901 }
1902 
do_astore(int idx)1903 void GenerateOopMap::do_astore(int idx) {
1904   CellTypeState r_or_p = pop();
1905   if (!r_or_p.is_address() && !r_or_p.is_reference()) {
1906     // We actually expected ref or pc, but we only report that we expected a ref. It does not
1907     // really matter (at least for now)
1908     verify_error("wrong type on stack (found: %c, expected: {pr})", r_or_p.to_char());
1909     return;
1910   }
1911   set_var(idx, r_or_p);
1912 }
1913 
1914 // Copies bottom/zero terminated CTS string from "src" into "dst".
1915 //   Does NOT terminate with a bottom. Returns the number of cells copied.
copy_cts(CellTypeState * dst,CellTypeState * src)1916 int GenerateOopMap::copy_cts(CellTypeState *dst, CellTypeState *src) {
1917   int idx = 0;
1918   while (!src[idx].is_bottom()) {
1919     dst[idx] = src[idx];
1920     idx++;
1921   }
1922   return idx;
1923 }
1924 
do_field(int is_get,int is_static,int idx,int bci)1925 void GenerateOopMap::do_field(int is_get, int is_static, int idx, int bci) {
1926   // Dig up signature for field in constant pool
1927   ConstantPool* cp     = method()->constants();
1928   int nameAndTypeIdx     = cp->name_and_type_ref_index_at(idx);
1929   int signatureIdx       = cp->signature_ref_index_at(nameAndTypeIdx);
1930   Symbol* signature      = cp->symbol_at(signatureIdx);
1931 
1932   // Parse signature (espcially simple for fields)
1933   assert(signature->utf8_length() > 0, "field signatures cannot have zero length");
1934   // The signature is UFT8 encoded, but the first char is always ASCII for signatures.
1935   char sigch = (char)*(signature->base());
1936   CellTypeState temp[4];
1937   CellTypeState *eff  = sigchar_to_effect(sigch, bci, temp);
1938 
1939   CellTypeState in[4];
1940   CellTypeState *out;
1941   int i =  0;
1942 
1943   if (is_get) {
1944     out = eff;
1945   } else {
1946     out = epsilonCTS;
1947     i   = copy_cts(in, eff);
1948   }
1949   if (!is_static) in[i++] = CellTypeState::ref;
1950   in[i] = CellTypeState::bottom;
1951   assert(i<=3, "sanity check");
1952   pp(in, out);
1953 }
1954 
do_method(int is_static,int is_interface,int idx,int bci)1955 void GenerateOopMap::do_method(int is_static, int is_interface, int idx, int bci) {
1956  // Dig up signature for field in constant pool
1957   ConstantPool* cp  = _method->constants();
1958   Symbol* signature   = cp->signature_ref_at(idx);
1959 
1960   // Parse method signature
1961   CellTypeState out[4];
1962   CellTypeState in[MAXARGSIZE+1];   // Includes result
1963   ComputeCallStack cse(signature);
1964 
1965   // Compute return type
1966   int res_length=  cse.compute_for_returntype(out);
1967 
1968   // Temporary hack.
1969   if (out[0].equal(CellTypeState::ref) && out[1].equal(CellTypeState::bottom)) {
1970     out[0] = CellTypeState::make_line_ref(bci);
1971   }
1972 
1973   assert(res_length<=4, "max value should be vv");
1974 
1975   // Compute arguments
1976   int arg_length = cse.compute_for_parameters(is_static != 0, in);
1977   assert(arg_length<=MAXARGSIZE, "too many locals");
1978 
1979   // Pop arguments
1980   for (int i = arg_length - 1; i >= 0; i--) ppop1(in[i]);// Do args in reverse order.
1981 
1982   // Report results
1983   if (_report_result_for_send == true) {
1984      fill_stackmap_for_opcodes(_itr_send, vars(), stack(), _stack_top);
1985      _report_result_for_send = false;
1986   }
1987 
1988   // Push return address
1989   ppush(out);
1990 }
1991 
1992 // This is used to parse the signature for fields, since they are very simple...
sigchar_to_effect(char sigch,int bci,CellTypeState * out)1993 CellTypeState *GenerateOopMap::sigchar_to_effect(char sigch, int bci, CellTypeState *out) {
1994   // Object and array
1995   if (sigch=='L' || sigch=='[') {
1996     out[0] = CellTypeState::make_line_ref(bci);
1997     out[1] = CellTypeState::bottom;
1998     return out;
1999   }
2000   if (sigch == 'J' || sigch == 'D' ) return vvCTS;  // Long and Double
2001   if (sigch == 'V' ) return epsilonCTS;             // Void
2002   return vCTS;                                      // Otherwise
2003 }
2004 
2005 long GenerateOopMap::_total_byte_count = 0;
2006 elapsedTimer GenerateOopMap::_total_oopmap_time;
2007 
2008 // This function assumes "bcs" is at a "ret" instruction and that the vars
2009 // state is valid for that instruction. Furthermore, the ret instruction
2010 // must be the last instruction in "bb" (we store information about the
2011 // "ret" in "bb").
ret_jump_targets_do(BytecodeStream * bcs,jmpFct_t jmpFct,int varNo,int * data)2012 void GenerateOopMap::ret_jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int varNo, int *data) {
2013   CellTypeState ra = vars()[varNo];
2014   if (!ra.is_good_address()) {
2015     verify_error("ret returns from two jsr subroutines?");
2016     return;
2017   }
2018   int target = ra.get_info();
2019 
2020   RetTableEntry* rtEnt = _rt.find_jsrs_for_target(target);
2021   int bci = bcs->bci();
2022   for (int i = 0; i < rtEnt->nof_jsrs(); i++) {
2023     int target_bci = rtEnt->jsrs(i);
2024     // Make sure a jrtRet does not set the changed bit for dead basicblock.
2025     BasicBlock* jsr_bb    = get_basic_block_containing(target_bci - 1);
2026     debug_only(BasicBlock* target_bb = &jsr_bb[1];)
2027     assert(target_bb  == get_basic_block_at(target_bci), "wrong calc. of successor basicblock");
2028     bool alive = jsr_bb->is_alive();
2029     if (TraceNewOopMapGeneration) {
2030       tty->print("pc = %d, ret -> %d alive: %s\n", bci, target_bci, alive ? "true" : "false");
2031     }
2032     if (alive) jmpFct(this, target_bci, data);
2033   }
2034 }
2035 
2036 //
2037 // Debug method
2038 //
state_vec_to_string(CellTypeState * vec,int len)2039 char* GenerateOopMap::state_vec_to_string(CellTypeState* vec, int len) {
2040 #ifdef ASSERT
2041   int checklen = MAX3(_max_locals, _max_stack, _max_monitors) + 1;
2042   assert(len < checklen, "state_vec_buf overflow");
2043 #endif
2044   for (int i = 0; i < len; i++) _state_vec_buf[i] = vec[i].to_char();
2045   _state_vec_buf[len] = 0;
2046   return _state_vec_buf;
2047 }
2048 
print_time()2049 void GenerateOopMap::print_time() {
2050   tty->print_cr ("Accumulated oopmap times:");
2051   tty->print_cr ("---------------------------");
2052   tty->print_cr ("  Total : %3.3f sec.", GenerateOopMap::_total_oopmap_time.seconds());
2053   tty->print_cr ("  (%3.0f bytecodes per sec) ",
2054   GenerateOopMap::_total_byte_count / GenerateOopMap::_total_oopmap_time.seconds());
2055 }
2056 
2057 //
2058 //  ============ Main Entry Point ===========
2059 //
GenerateOopMap(const methodHandle & method)2060 GenerateOopMap::GenerateOopMap(const methodHandle& method) {
2061   // We have to initialize all variables here, that can be queried directly
2062   _method = method;
2063   _max_locals=0;
2064   _init_vars = NULL;
2065 
2066 #ifndef PRODUCT
2067   // If we are doing a detailed trace, include the regular trace information.
2068   if (TraceNewOopMapGenerationDetailed) {
2069     TraceNewOopMapGeneration = true;
2070   }
2071 #endif
2072 }
2073 
compute_map(TRAPS)2074 void GenerateOopMap::compute_map(TRAPS) {
2075 #ifndef PRODUCT
2076   if (TimeOopMap2) {
2077     method()->print_short_name(tty);
2078     tty->print("  ");
2079   }
2080   if (TimeOopMap) {
2081     _total_byte_count += method()->code_size();
2082   }
2083 #endif
2084   TraceTime t_single("oopmap time", TimeOopMap2);
2085   TraceTime t_all(NULL, &_total_oopmap_time, TimeOopMap);
2086 
2087   // Initialize values
2088   _got_error      = false;
2089   _conflict       = false;
2090   _max_locals     = method()->max_locals();
2091   _max_stack      = method()->max_stack();
2092   _has_exceptions = (method()->has_exception_handler());
2093   _nof_refval_conflicts = 0;
2094   _init_vars      = new GrowableArray<intptr_t>(5);  // There are seldom more than 5 init_vars
2095   _report_result  = false;
2096   _report_result_for_send = false;
2097   _new_var_map    = NULL;
2098   _ret_adr_tos    = new GrowableArray<intptr_t>(5);  // 5 seems like a good number;
2099   _did_rewriting  = false;
2100   _did_relocation = false;
2101 
2102   if (TraceNewOopMapGeneration) {
2103     tty->print("Method name: %s\n", method()->name()->as_C_string());
2104     if (Verbose) {
2105       _method->print_codes();
2106       tty->print_cr("Exception table:");
2107       ExceptionTable excps(method());
2108       for(int i = 0; i < excps.length(); i ++) {
2109         tty->print_cr("[%d - %d] -> %d",
2110                       excps.start_pc(i), excps.end_pc(i), excps.handler_pc(i));
2111       }
2112     }
2113   }
2114 
2115   // if no code - do nothing
2116   // compiler needs info
2117   if (method()->code_size() == 0 || _max_locals + method()->max_stack() == 0) {
2118     fill_stackmap_prolog(0);
2119     fill_stackmap_epilog();
2120     return;
2121   }
2122   // Step 1: Compute all jump targets and their return value
2123   if (!_got_error)
2124     _rt.compute_ret_table(_method);
2125 
2126   // Step 2: Find all basic blocks and count GC points
2127   if (!_got_error)
2128     mark_bbheaders_and_count_gc_points();
2129 
2130   // Step 3: Calculate stack maps
2131   if (!_got_error)
2132     do_interpretation();
2133 
2134   // Step 4:Return results
2135   if (!_got_error && report_results())
2136      report_result();
2137 
2138   if (_got_error) {
2139     THROW_HANDLE(_exception);
2140   }
2141 }
2142 
2143 // Error handling methods
2144 // These methods create an exception for the current thread which is thrown
2145 // at the bottom of the call stack, when it returns to compute_map().  The
2146 // _got_error flag controls execution.  NOT TODO: The VM exception propagation
2147 // mechanism using TRAPS/CHECKs could be used here instead but it would need
2148 // to be added as a parameter to every function and checked for every call.
2149 // The tons of extra code it would generate didn't seem worth the change.
2150 //
error_work(const char * format,va_list ap)2151 void GenerateOopMap::error_work(const char *format, va_list ap) {
2152   _got_error = true;
2153   char msg_buffer[512];
2154   os::vsnprintf(msg_buffer, sizeof(msg_buffer), format, ap);
2155   // Append method name
2156   char msg_buffer2[512];
2157   os::snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg_buffer, method()->name()->as_C_string());
2158   if (Thread::current()->can_call_java()) {
2159     _exception = Exceptions::new_exception(Thread::current(),
2160                   vmSymbols::java_lang_LinkageError(), msg_buffer2);
2161   } else {
2162     // We cannot instantiate an exception object from a compiler thread.
2163     // Exit the VM with a useful error message.
2164     fatal("%s", msg_buffer2);
2165   }
2166 }
2167 
report_error(const char * format,...)2168 void GenerateOopMap::report_error(const char *format, ...) {
2169   va_list ap;
2170   va_start(ap, format);
2171   error_work(format, ap);
2172 }
2173 
verify_error(const char * format,...)2174 void GenerateOopMap::verify_error(const char *format, ...) {
2175   // We do not distinguish between different types of errors for verification
2176   // errors.  Let the verifier give a better message.
2177   report_error("Illegal class file encountered. Try running with -Xverify:all");
2178 }
2179 
2180 //
2181 // Report result opcodes
2182 //
report_result()2183 void GenerateOopMap::report_result() {
2184 
2185   if (TraceNewOopMapGeneration) tty->print_cr("Report result pass");
2186 
2187   // We now want to report the result of the parse
2188   _report_result = true;
2189 
2190   // Prolog code
2191   fill_stackmap_prolog(_gc_points);
2192 
2193    // Mark everything changed, then do one interpretation pass.
2194   for (int i = 0; i<_bb_count; i++) {
2195     if (_basic_blocks[i].is_reachable()) {
2196       _basic_blocks[i].set_changed(true);
2197       interp_bb(&_basic_blocks[i]);
2198     }
2199   }
2200 
2201   // Note: Since we are skipping dead-code when we are reporting results, then
2202   // the no. of encountered gc-points might be fewer than the previously number
2203   // we have counted. (dead-code is a pain - it should be removed before we get here)
2204   fill_stackmap_epilog();
2205 
2206   // Report initvars
2207   fill_init_vars(_init_vars);
2208 
2209   _report_result = false;
2210 }
2211 
result_for_basicblock(int bci)2212 void GenerateOopMap::result_for_basicblock(int bci) {
2213  if (TraceNewOopMapGeneration) tty->print_cr("Report result pass for basicblock");
2214 
2215   // We now want to report the result of the parse
2216   _report_result = true;
2217 
2218   // Find basicblock and report results
2219   BasicBlock* bb = get_basic_block_containing(bci);
2220   guarantee(bb != NULL, "no basic block for bci");
2221   assert(bb->is_reachable(), "getting result from unreachable basicblock");
2222   bb->set_changed(true);
2223   interp_bb(bb);
2224 }
2225 
2226 //
2227 // Conflict handling code
2228 //
2229 
record_refval_conflict(int varNo)2230 void GenerateOopMap::record_refval_conflict(int varNo) {
2231   assert(varNo>=0 && varNo< _max_locals, "index out of range");
2232 
2233   if (TraceOopMapRewrites) {
2234      tty->print("### Conflict detected (local no: %d)\n", varNo);
2235   }
2236 
2237   if (!_new_var_map) {
2238     _new_var_map = NEW_RESOURCE_ARRAY(int, _max_locals);
2239     for (int k = 0; k < _max_locals; k++)  _new_var_map[k] = k;
2240   }
2241 
2242   if ( _new_var_map[varNo] == varNo) {
2243     // Check if max. number of locals has been reached
2244     if (_max_locals + _nof_refval_conflicts >= MAX_LOCAL_VARS) {
2245       report_error("Rewriting exceeded local variable limit");
2246       return;
2247     }
2248     _new_var_map[varNo] = _max_locals + _nof_refval_conflicts;
2249     _nof_refval_conflicts++;
2250   }
2251 }
2252 
rewrite_refval_conflicts()2253 void GenerateOopMap::rewrite_refval_conflicts()
2254 {
2255   // We can get here two ways: Either a rewrite conflict was detected, or
2256   // an uninitialize reference was detected. In the second case, we do not
2257   // do any rewriting, we just want to recompute the reference set with the
2258   // new information
2259 
2260   int nof_conflicts = 0;              // Used for debugging only
2261 
2262   if ( _nof_refval_conflicts == 0 )
2263      return;
2264 
2265   // Check if rewrites are allowed in this parse.
2266   if (!allow_rewrites() && !IgnoreRewrites) {
2267     fatal("Rewriting method not allowed at this stage");
2268   }
2269 
2270 
2271   // This following flag is to tempoary supress rewrites. The locals that might conflict will
2272   // all be set to contain values. This is UNSAFE - however, until the rewriting has been completely
2273   // tested it is nice to have.
2274   if (IgnoreRewrites) {
2275     if (Verbose) {
2276        tty->print("rewrites suppressed for local no. ");
2277        for (int l = 0; l < _max_locals; l++) {
2278          if (_new_var_map[l] != l) {
2279            tty->print("%d ", l);
2280            vars()[l] = CellTypeState::value;
2281          }
2282        }
2283        tty->cr();
2284     }
2285 
2286     // That was that...
2287     _new_var_map = NULL;
2288     _nof_refval_conflicts = 0;
2289     _conflict = false;
2290 
2291     return;
2292   }
2293 
2294   // Tracing flag
2295   _did_rewriting = true;
2296 
2297   if (TraceOopMapRewrites) {
2298     tty->print_cr("ref/value conflict for method %s - bytecodes are getting rewritten", method()->name()->as_C_string());
2299     method()->print();
2300     method()->print_codes();
2301   }
2302 
2303   assert(_new_var_map!=NULL, "nothing to rewrite");
2304   assert(_conflict==true, "We should not be here");
2305 
2306   compute_ret_adr_at_TOS();
2307   if (!_got_error) {
2308     for (int k = 0; k < _max_locals && !_got_error; k++) {
2309       if (_new_var_map[k] != k) {
2310         if (TraceOopMapRewrites) {
2311           tty->print_cr("Rewriting: %d -> %d", k, _new_var_map[k]);
2312         }
2313         rewrite_refval_conflict(k, _new_var_map[k]);
2314         if (_got_error) return;
2315         nof_conflicts++;
2316       }
2317     }
2318   }
2319 
2320   assert(nof_conflicts == _nof_refval_conflicts, "sanity check");
2321 
2322   // Adjust the number of locals
2323   method()->set_max_locals(_max_locals+_nof_refval_conflicts);
2324   _max_locals += _nof_refval_conflicts;
2325 
2326   // That was that...
2327   _new_var_map = NULL;
2328   _nof_refval_conflicts = 0;
2329 }
2330 
rewrite_refval_conflict(int from,int to)2331 void GenerateOopMap::rewrite_refval_conflict(int from, int to) {
2332   bool startOver;
2333   do {
2334     // Make sure that the BytecodeStream is constructed in the loop, since
2335     // during rewriting a new method oop is going to be used, and the next time
2336     // around we want to use that.
2337     BytecodeStream bcs(_method);
2338     startOver = false;
2339 
2340     while( !startOver && !_got_error &&
2341            // test bcs in case method changed and it became invalid
2342            bcs.next() >=0) {
2343       startOver = rewrite_refval_conflict_inst(&bcs, from, to);
2344     }
2345   } while (startOver && !_got_error);
2346 }
2347 
2348 /* If the current instruction is one that uses local variable "from"
2349    in a ref way, change it to use "to". There's a subtle reason why we
2350    renumber the ref uses and not the non-ref uses: non-ref uses may be
2351    2 slots wide (double, long) which would necessitate keeping track of
2352    whether we should add one or two variables to the method. If the change
2353    affected the width of some instruction, returns "TRUE"; otherwise, returns "FALSE".
2354    Another reason for moving ref's value is for solving (addr, ref) conflicts, which
2355    both uses aload/astore methods.
2356 */
rewrite_refval_conflict_inst(BytecodeStream * itr,int from,int to)2357 bool GenerateOopMap::rewrite_refval_conflict_inst(BytecodeStream *itr, int from, int to) {
2358   Bytecodes::Code bc = itr->code();
2359   int index;
2360   int bci = itr->bci();
2361 
2362   if (is_aload(itr, &index) && index == from) {
2363     if (TraceOopMapRewrites) {
2364       tty->print_cr("Rewriting aload at bci: %d", bci);
2365     }
2366     return rewrite_load_or_store(itr, Bytecodes::_aload, Bytecodes::_aload_0, to);
2367   }
2368 
2369   if (is_astore(itr, &index) && index == from) {
2370     if (!stack_top_holds_ret_addr(bci)) {
2371       if (TraceOopMapRewrites) {
2372         tty->print_cr("Rewriting astore at bci: %d", bci);
2373       }
2374       return rewrite_load_or_store(itr, Bytecodes::_astore, Bytecodes::_astore_0, to);
2375     } else {
2376       if (TraceOopMapRewrites) {
2377         tty->print_cr("Supress rewriting of astore at bci: %d", bci);
2378       }
2379     }
2380   }
2381 
2382   return false;
2383 }
2384 
2385 // The argument to this method is:
2386 // bc : Current bytecode
2387 // bcN : either _aload or _astore
2388 // bc0 : either _aload_0 or _astore_0
rewrite_load_or_store(BytecodeStream * bcs,Bytecodes::Code bcN,Bytecodes::Code bc0,unsigned int varNo)2389 bool GenerateOopMap::rewrite_load_or_store(BytecodeStream *bcs, Bytecodes::Code bcN, Bytecodes::Code bc0, unsigned int varNo) {
2390   assert(bcN == Bytecodes::_astore   || bcN == Bytecodes::_aload,   "wrong argument (bcN)");
2391   assert(bc0 == Bytecodes::_astore_0 || bc0 == Bytecodes::_aload_0, "wrong argument (bc0)");
2392   int ilen = Bytecodes::length_at(_method(), bcs->bcp());
2393   int newIlen;
2394 
2395   if (ilen == 4) {
2396     // Original instruction was wide; keep it wide for simplicity
2397     newIlen = 4;
2398   } else if (varNo < 4)
2399      newIlen = 1;
2400   else if (varNo >= 256)
2401      newIlen = 4;
2402   else
2403      newIlen = 2;
2404 
2405   // If we need to relocate in order to patch the byte, we
2406   // do the patching in a temp. buffer, that is passed to the reloc.
2407   // The patching of the bytecode stream is then done by the Relocator.
2408   // This is neccesary, since relocating the instruction at a certain bci, might
2409   // also relocate that instruction, e.g., if a _goto before it gets widen to a _goto_w.
2410   // Hence, we do not know which bci to patch after relocation.
2411 
2412   assert(newIlen <= 4, "sanity check");
2413   u_char inst_buffer[4]; // Max. instruction size is 4.
2414   address bcp;
2415 
2416   if (newIlen != ilen) {
2417     // Relocation needed do patching in temp. buffer
2418     bcp = (address)inst_buffer;
2419   } else {
2420     bcp = _method->bcp_from(bcs->bci());
2421   }
2422 
2423   // Patch either directly in Method* or in temp. buffer
2424   if (newIlen == 1) {
2425     assert(varNo < 4, "varNo too large");
2426     *bcp = bc0 + varNo;
2427   } else if (newIlen == 2) {
2428     assert(varNo < 256, "2-byte index needed!");
2429     *(bcp + 0) = bcN;
2430     *(bcp + 1) = varNo;
2431   } else {
2432     assert(newIlen == 4, "Wrong instruction length");
2433     *(bcp + 0) = Bytecodes::_wide;
2434     *(bcp + 1) = bcN;
2435     Bytes::put_Java_u2(bcp+2, varNo);
2436   }
2437 
2438   if (newIlen != ilen) {
2439     expand_current_instr(bcs->bci(), ilen, newIlen, inst_buffer);
2440   }
2441 
2442 
2443   return (newIlen != ilen);
2444 }
2445 
2446 class RelocCallback : public RelocatorListener {
2447  private:
2448   GenerateOopMap* _gom;
2449  public:
RelocCallback(GenerateOopMap * gom)2450    RelocCallback(GenerateOopMap* gom) { _gom = gom; };
2451 
2452   // Callback method
relocated(int bci,int delta,int new_code_length)2453   virtual void relocated(int bci, int delta, int new_code_length) {
2454     _gom->update_basic_blocks  (bci, delta, new_code_length);
2455     _gom->update_ret_adr_at_TOS(bci, delta);
2456     _gom->_rt.update_ret_table (bci, delta);
2457   }
2458 };
2459 
2460 // Returns true if expanding was succesful. Otherwise, reports an error and
2461 // returns false.
expand_current_instr(int bci,int ilen,int newIlen,u_char inst_buffer[])2462 void GenerateOopMap::expand_current_instr(int bci, int ilen, int newIlen, u_char inst_buffer[]) {
2463   Thread *THREAD = Thread::current();  // Could really have TRAPS argument.
2464   RelocCallback rcb(this);
2465   Relocator rc(_method, &rcb);
2466   methodHandle m= rc.insert_space_at(bci, newIlen, inst_buffer, THREAD);
2467   if (m.is_null() || HAS_PENDING_EXCEPTION) {
2468     report_error("could not rewrite method - exception occurred or bytecode buffer overflow");
2469     return;
2470   }
2471 
2472   // Relocator returns a new method oop.
2473   _did_relocation = true;
2474   _method = m;
2475 }
2476 
2477 
is_astore(BytecodeStream * itr,int * index)2478 bool GenerateOopMap::is_astore(BytecodeStream *itr, int *index) {
2479   Bytecodes::Code bc = itr->code();
2480   switch(bc) {
2481     case Bytecodes::_astore_0:
2482     case Bytecodes::_astore_1:
2483     case Bytecodes::_astore_2:
2484     case Bytecodes::_astore_3:
2485       *index = bc - Bytecodes::_astore_0;
2486       return true;
2487     case Bytecodes::_astore:
2488       *index = itr->get_index();
2489       return true;
2490     default:
2491       return false;
2492   }
2493 }
2494 
is_aload(BytecodeStream * itr,int * index)2495 bool GenerateOopMap::is_aload(BytecodeStream *itr, int *index) {
2496   Bytecodes::Code bc = itr->code();
2497   switch(bc) {
2498     case Bytecodes::_aload_0:
2499     case Bytecodes::_aload_1:
2500     case Bytecodes::_aload_2:
2501     case Bytecodes::_aload_3:
2502       *index = bc - Bytecodes::_aload_0;
2503       return true;
2504 
2505     case Bytecodes::_aload:
2506       *index = itr->get_index();
2507       return true;
2508 
2509     default:
2510       return false;
2511   }
2512 }
2513 
2514 
2515 // Return true iff the top of the operand stack holds a return address at
2516 // the current instruction
stack_top_holds_ret_addr(int bci)2517 bool GenerateOopMap::stack_top_holds_ret_addr(int bci) {
2518   for(int i = 0; i < _ret_adr_tos->length(); i++) {
2519     if (_ret_adr_tos->at(i) == bci)
2520       return true;
2521   }
2522 
2523   return false;
2524 }
2525 
compute_ret_adr_at_TOS()2526 void GenerateOopMap::compute_ret_adr_at_TOS() {
2527   assert(_ret_adr_tos != NULL, "must be initialized");
2528   _ret_adr_tos->clear();
2529 
2530   for (int i = 0; i < bb_count(); i++) {
2531     BasicBlock* bb = &_basic_blocks[i];
2532 
2533     // Make sure to only check basicblocks that are reachable
2534     if (bb->is_reachable()) {
2535 
2536       // For each Basic block we check all instructions
2537       BytecodeStream bcs(_method);
2538       bcs.set_interval(bb->_bci, next_bb_start_pc(bb));
2539 
2540       restore_state(bb);
2541 
2542       while (bcs.next()>=0 && !_got_error) {
2543         // TDT: should this be is_good_address() ?
2544         if (_stack_top > 0 && stack()[_stack_top-1].is_address()) {
2545           _ret_adr_tos->append(bcs.bci());
2546           if (TraceNewOopMapGeneration) {
2547             tty->print_cr("Ret_adr TOS at bci: %d", bcs.bci());
2548           }
2549         }
2550         interp1(&bcs);
2551       }
2552     }
2553   }
2554 }
2555 
update_ret_adr_at_TOS(int bci,int delta)2556 void GenerateOopMap::update_ret_adr_at_TOS(int bci, int delta) {
2557   for(int i = 0; i < _ret_adr_tos->length(); i++) {
2558     int v = _ret_adr_tos->at(i);
2559     if (v > bci)  _ret_adr_tos->at_put(i, v + delta);
2560   }
2561 }
2562 
2563 // ===================================================================
2564 
2565 #ifndef PRODUCT
2566 int ResolveOopMapConflicts::_nof_invocations  = 0;
2567 int ResolveOopMapConflicts::_nof_rewrites     = 0;
2568 int ResolveOopMapConflicts::_nof_relocations  = 0;
2569 #endif
2570 
do_potential_rewrite(TRAPS)2571 methodHandle ResolveOopMapConflicts::do_potential_rewrite(TRAPS) {
2572   compute_map(CHECK_(methodHandle()));
2573 
2574 #ifndef PRODUCT
2575   // Tracking and statistics
2576   if (PrintRewrites) {
2577     _nof_invocations++;
2578     if (did_rewriting()) {
2579       _nof_rewrites++;
2580       if (did_relocation()) _nof_relocations++;
2581       tty->print("Method was rewritten %s: ", (did_relocation()) ? "and relocated" : "");
2582       method()->print_value(); tty->cr();
2583       tty->print_cr("Cand.: %d rewrts: %d (%d%%) reloc.: %d (%d%%)",
2584           _nof_invocations,
2585           _nof_rewrites,    (_nof_rewrites    * 100) / _nof_invocations,
2586           _nof_relocations, (_nof_relocations * 100) / _nof_invocations);
2587     }
2588   }
2589 #endif
2590   return methodHandle(THREAD, method());
2591 }
2592