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