Tue, 08 Aug 2017 15:57:29 +0800
merge
1 /*
2 * Copyright (c) 2005, 2013, 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 */
25 /*
26 * This file has been modified by Loongson Technology in 2015. These
27 * modifications are Copyright (c) 2015 Loongson Technology, and are made
28 * available on the same license terms set forth above.
29 */
31 #include "precompiled.hpp"
32 #include "c1/c1_CFGPrinter.hpp"
33 #include "c1/c1_CodeStubs.hpp"
34 #include "c1/c1_Compilation.hpp"
35 #include "c1/c1_FrameMap.hpp"
36 #include "c1/c1_IR.hpp"
37 #include "c1/c1_LIRGenerator.hpp"
38 #include "c1/c1_LinearScan.hpp"
39 #include "c1/c1_ValueStack.hpp"
40 #include "utilities/bitMap.inline.hpp"
41 #ifdef TARGET_ARCH_x86
42 # include "vmreg_x86.inline.hpp"
43 #endif
44 #ifdef TARGET_ARCH_mips
45 # include "vmreg_mips.inline.hpp"
46 #endif
47 #ifdef TARGET_ARCH_sparc
48 # include "vmreg_sparc.inline.hpp"
49 #endif
50 #ifdef TARGET_ARCH_zero
51 # include "vmreg_zero.inline.hpp"
52 #endif
53 #ifdef TARGET_ARCH_arm
54 # include "vmreg_arm.inline.hpp"
55 #endif
56 #ifdef TARGET_ARCH_ppc
57 # include "vmreg_ppc.inline.hpp"
58 #endif
61 #ifndef PRODUCT
63 static LinearScanStatistic _stat_before_alloc;
64 static LinearScanStatistic _stat_after_asign;
65 static LinearScanStatistic _stat_final;
67 static LinearScanTimers _total_timer;
69 // helper macro for short definition of timer
70 #define TIME_LINEAR_SCAN(timer_name) TraceTime _block_timer("", _total_timer.timer(LinearScanTimers::timer_name), TimeLinearScan || TimeEachLinearScan, Verbose);
72 // helper macro for short definition of trace-output inside code
73 #define TRACE_LINEAR_SCAN(level, code) \
74 if (TraceLinearScanLevel >= level) { \
75 code; \
76 }
78 #else
80 #define TIME_LINEAR_SCAN(timer_name)
81 #define TRACE_LINEAR_SCAN(level, code)
83 #endif
85 // Map BasicType to spill size in 32-bit words, matching VMReg's notion of words
86 #ifdef _LP64
87 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 0, 2, 1, 2, 1, -1};
88 #else
89 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, -1, 1, 1, -1};
90 #endif
93 // Implementation of LinearScan
95 LinearScan::LinearScan(IR* ir, LIRGenerator* gen, FrameMap* frame_map)
96 : _compilation(ir->compilation())
97 , _ir(ir)
98 , _gen(gen)
99 , _frame_map(frame_map)
100 , _num_virtual_regs(gen->max_virtual_register_number())
101 , _has_fpu_registers(false)
102 , _num_calls(-1)
103 , _max_spills(0)
104 , _unused_spill_slot(-1)
105 , _intervals(0) // initialized later with correct length
106 , _new_intervals_from_allocation(new IntervalList())
107 , _sorted_intervals(NULL)
108 , _needs_full_resort(false)
109 , _lir_ops(0) // initialized later with correct length
110 , _block_of_op(0) // initialized later with correct length
111 , _has_info(0)
112 , _has_call(0)
113 , _scope_value_cache(0) // initialized later with correct length
114 , _interval_in_loop(0, 0) // initialized later with correct length
115 , _cached_blocks(*ir->linear_scan_order())
116 #ifdef X86
117 , _fpu_stack_allocator(NULL)
118 #endif
119 {
120 assert(this->ir() != NULL, "check if valid");
121 assert(this->compilation() != NULL, "check if valid");
122 assert(this->gen() != NULL, "check if valid");
123 assert(this->frame_map() != NULL, "check if valid");
124 }
127 // ********** functions for converting LIR-Operands to register numbers
128 //
129 // Emulate a flat register file comprising physical integer registers,
130 // physical floating-point registers and virtual registers, in that order.
131 // Virtual registers already have appropriate numbers, since V0 is
132 // the number of physical registers.
133 // Returns -1 for hi word if opr is a single word operand.
134 //
135 // Note: the inverse operation (calculating an operand for register numbers)
136 // is done in calc_operand_for_interval()
138 int LinearScan::reg_num(LIR_Opr opr) {
139 assert(opr->is_register(), "should not call this otherwise");
141 if (opr->is_virtual_register()) {
142 assert(opr->vreg_number() >= nof_regs, "found a virtual register with a fixed-register number");
143 return opr->vreg_number();
144 } else if (opr->is_single_cpu()) {
145 return opr->cpu_regnr();
146 } else if (opr->is_double_cpu()) {
147 return opr->cpu_regnrLo();
148 #ifdef X86
149 } else if (opr->is_single_xmm()) {
150 return opr->fpu_regnr() + pd_first_xmm_reg;
151 } else if (opr->is_double_xmm()) {
152 return opr->fpu_regnrLo() + pd_first_xmm_reg;
153 #endif
154 } else if (opr->is_single_fpu()) {
155 return opr->fpu_regnr() + pd_first_fpu_reg;
156 } else if (opr->is_double_fpu()) {
157 return opr->fpu_regnrLo() + pd_first_fpu_reg;
158 } else {
159 ShouldNotReachHere();
160 return -1;
161 }
162 }
164 int LinearScan::reg_numHi(LIR_Opr opr) {
165 assert(opr->is_register(), "should not call this otherwise");
167 if (opr->is_virtual_register()) {
168 return -1;
169 } else if (opr->is_single_cpu()) {
170 return -1;
171 } else if (opr->is_double_cpu()) {
172 return opr->cpu_regnrHi();
173 #ifdef X86
174 } else if (opr->is_single_xmm()) {
175 return -1;
176 } else if (opr->is_double_xmm()) {
177 return -1;
178 #endif
179 } else if (opr->is_single_fpu()) {
180 return -1;
181 } else if (opr->is_double_fpu()) {
182 return opr->fpu_regnrHi() + pd_first_fpu_reg;
183 } else {
184 ShouldNotReachHere();
185 return -1;
186 }
187 }
190 // ********** functions for classification of intervals
192 bool LinearScan::is_precolored_interval(const Interval* i) {
193 return i->reg_num() < LinearScan::nof_regs;
194 }
196 bool LinearScan::is_virtual_interval(const Interval* i) {
197 return i->reg_num() >= LIR_OprDesc::vreg_base;
198 }
200 bool LinearScan::is_precolored_cpu_interval(const Interval* i) {
201 return i->reg_num() < LinearScan::nof_cpu_regs;
202 }
204 bool LinearScan::is_virtual_cpu_interval(const Interval* i) {
205 #if defined(__SOFTFP__) || defined(E500V2)
206 return i->reg_num() >= LIR_OprDesc::vreg_base;
207 #else
208 return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() != T_FLOAT && i->type() != T_DOUBLE);
209 #endif // __SOFTFP__ or E500V2
210 }
212 bool LinearScan::is_precolored_fpu_interval(const Interval* i) {
213 return i->reg_num() >= LinearScan::nof_cpu_regs && i->reg_num() < LinearScan::nof_regs;
214 }
216 bool LinearScan::is_virtual_fpu_interval(const Interval* i) {
217 #if defined(__SOFTFP__) || defined(E500V2)
218 return false;
219 #else
220 return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() == T_FLOAT || i->type() == T_DOUBLE);
221 #endif // __SOFTFP__ or E500V2
222 }
224 bool LinearScan::is_in_fpu_register(const Interval* i) {
225 // fixed intervals not needed for FPU stack allocation
226 return i->reg_num() >= nof_regs && pd_first_fpu_reg <= i->assigned_reg() && i->assigned_reg() <= pd_last_fpu_reg;
227 }
229 bool LinearScan::is_oop_interval(const Interval* i) {
230 // fixed intervals never contain oops
231 return i->reg_num() >= nof_regs && i->type() == T_OBJECT;
232 }
235 // ********** General helper functions
237 // compute next unused stack index that can be used for spilling
238 int LinearScan::allocate_spill_slot(bool double_word) {
239 int spill_slot;
240 if (double_word) {
241 if ((_max_spills & 1) == 1) {
242 // alignment of double-word values
243 // the hole because of the alignment is filled with the next single-word value
244 assert(_unused_spill_slot == -1, "wasting a spill slot");
245 _unused_spill_slot = _max_spills;
246 _max_spills++;
247 }
248 spill_slot = _max_spills;
249 _max_spills += 2;
251 } else if (_unused_spill_slot != -1) {
252 // re-use hole that was the result of a previous double-word alignment
253 spill_slot = _unused_spill_slot;
254 _unused_spill_slot = -1;
256 } else {
257 spill_slot = _max_spills;
258 _max_spills++;
259 }
261 int result = spill_slot + LinearScan::nof_regs + frame_map()->argcount();
263 // the class OopMapValue uses only 11 bits for storing the name of the
264 // oop location. So a stack slot bigger than 2^11 leads to an overflow
265 // that is not reported in product builds. Prevent this by checking the
266 // spill slot here (altough this value and the later used location name
267 // are slightly different)
268 if (result > 2000) {
269 bailout("too many stack slots used");
270 }
272 return result;
273 }
275 void LinearScan::assign_spill_slot(Interval* it) {
276 // assign the canonical spill slot of the parent (if a part of the interval
277 // is already spilled) or allocate a new spill slot
278 if (it->canonical_spill_slot() >= 0) {
279 it->assign_reg(it->canonical_spill_slot());
280 } else {
281 int spill = allocate_spill_slot(type2spill_size[it->type()] == 2);
282 it->set_canonical_spill_slot(spill);
283 it->assign_reg(spill);
284 }
285 }
287 void LinearScan::propagate_spill_slots() {
288 if (!frame_map()->finalize_frame(max_spills())) {
289 bailout("frame too large");
290 }
291 }
293 // create a new interval with a predefined reg_num
294 // (only used for parent intervals that are created during the building phase)
295 Interval* LinearScan::create_interval(int reg_num) {
296 assert(_intervals.at(reg_num) == NULL, "overwriting exisiting interval");
298 Interval* interval = new Interval(reg_num);
299 _intervals.at_put(reg_num, interval);
301 // assign register number for precolored intervals
302 if (reg_num < LIR_OprDesc::vreg_base) {
303 interval->assign_reg(reg_num);
304 }
305 return interval;
306 }
308 // assign a new reg_num to the interval and append it to the list of intervals
309 // (only used for child intervals that are created during register allocation)
310 void LinearScan::append_interval(Interval* it) {
311 it->set_reg_num(_intervals.length());
312 _intervals.append(it);
313 _new_intervals_from_allocation->append(it);
314 }
316 // copy the vreg-flags if an interval is split
317 void LinearScan::copy_register_flags(Interval* from, Interval* to) {
318 if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::byte_reg)) {
319 gen()->set_vreg_flag(to->reg_num(), LIRGenerator::byte_reg);
320 }
321 if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::callee_saved)) {
322 gen()->set_vreg_flag(to->reg_num(), LIRGenerator::callee_saved);
323 }
325 // Note: do not copy the must_start_in_memory flag because it is not necessary for child
326 // intervals (only the very beginning of the interval must be in memory)
327 }
330 // ********** spill move optimization
331 // eliminate moves from register to stack if stack slot is known to be correct
333 // called during building of intervals
334 void LinearScan::change_spill_definition_pos(Interval* interval, int def_pos) {
335 assert(interval->is_split_parent(), "can only be called for split parents");
337 switch (interval->spill_state()) {
338 case noDefinitionFound:
339 assert(interval->spill_definition_pos() == -1, "must no be set before");
340 interval->set_spill_definition_pos(def_pos);
341 interval->set_spill_state(oneDefinitionFound);
342 break;
344 case oneDefinitionFound:
345 assert(def_pos <= interval->spill_definition_pos(), "positions are processed in reverse order when intervals are created");
346 if (def_pos < interval->spill_definition_pos() - 2) {
347 // second definition found, so no spill optimization possible for this interval
348 interval->set_spill_state(noOptimization);
349 } else {
350 // two consecutive definitions (because of two-operand LIR form)
351 assert(block_of_op_with_id(def_pos) == block_of_op_with_id(interval->spill_definition_pos()), "block must be equal");
352 }
353 break;
355 case noOptimization:
356 // nothing to do
357 break;
359 default:
360 assert(false, "other states not allowed at this time");
361 }
362 }
364 // called during register allocation
365 void LinearScan::change_spill_state(Interval* interval, int spill_pos) {
366 switch (interval->spill_state()) {
367 case oneDefinitionFound: {
368 int def_loop_depth = block_of_op_with_id(interval->spill_definition_pos())->loop_depth();
369 int spill_loop_depth = block_of_op_with_id(spill_pos)->loop_depth();
371 if (def_loop_depth < spill_loop_depth) {
372 // the loop depth of the spilling position is higher then the loop depth
373 // at the definition of the interval -> move write to memory out of loop
374 // by storing at definitin of the interval
375 interval->set_spill_state(storeAtDefinition);
376 } else {
377 // the interval is currently spilled only once, so for now there is no
378 // reason to store the interval at the definition
379 interval->set_spill_state(oneMoveInserted);
380 }
381 break;
382 }
384 case oneMoveInserted: {
385 // the interval is spilled more then once, so it is better to store it to
386 // memory at the definition
387 interval->set_spill_state(storeAtDefinition);
388 break;
389 }
391 case storeAtDefinition:
392 case startInMemory:
393 case noOptimization:
394 case noDefinitionFound:
395 // nothing to do
396 break;
398 default:
399 assert(false, "other states not allowed at this time");
400 }
401 }
404 bool LinearScan::must_store_at_definition(const Interval* i) {
405 return i->is_split_parent() && i->spill_state() == storeAtDefinition;
406 }
408 // called once before asignment of register numbers
409 void LinearScan::eliminate_spill_moves() {
410 TIME_LINEAR_SCAN(timer_eliminate_spill_moves);
411 TRACE_LINEAR_SCAN(3, tty->print_cr("***** Eliminating unnecessary spill moves"));
413 // collect all intervals that must be stored after their definion.
414 // the list is sorted by Interval::spill_definition_pos
415 Interval* interval;
416 Interval* temp_list;
417 create_unhandled_lists(&interval, &temp_list, must_store_at_definition, NULL);
419 #ifdef ASSERT
420 Interval* prev = NULL;
421 Interval* temp = interval;
422 while (temp != Interval::end()) {
423 assert(temp->spill_definition_pos() > 0, "invalid spill definition pos");
424 if (prev != NULL) {
425 assert(temp->from() >= prev->from(), "intervals not sorted");
426 assert(temp->spill_definition_pos() >= prev->spill_definition_pos(), "when intervals are sorted by from, then they must also be sorted by spill_definition_pos");
427 }
429 assert(temp->canonical_spill_slot() >= LinearScan::nof_regs, "interval has no spill slot assigned");
430 assert(temp->spill_definition_pos() >= temp->from(), "invalid order");
431 assert(temp->spill_definition_pos() <= temp->from() + 2, "only intervals defined once at their start-pos can be optimized");
433 TRACE_LINEAR_SCAN(4, tty->print_cr("interval %d (from %d to %d) must be stored at %d", temp->reg_num(), temp->from(), temp->to(), temp->spill_definition_pos()));
435 temp = temp->next();
436 }
437 #endif
439 LIR_InsertionBuffer insertion_buffer;
440 int num_blocks = block_count();
441 for (int i = 0; i < num_blocks; i++) {
442 BlockBegin* block = block_at(i);
443 LIR_OpList* instructions = block->lir()->instructions_list();
444 int num_inst = instructions->length();
445 bool has_new = false;
447 // iterate all instructions of the block. skip the first because it is always a label
448 for (int j = 1; j < num_inst; j++) {
449 LIR_Op* op = instructions->at(j);
450 int op_id = op->id();
452 if (op_id == -1) {
453 // remove move from register to stack if the stack slot is guaranteed to be correct.
454 // only moves that have been inserted by LinearScan can be removed.
455 assert(op->code() == lir_move, "only moves can have a op_id of -1");
456 assert(op->as_Op1() != NULL, "move must be LIR_Op1");
457 assert(op->as_Op1()->result_opr()->is_virtual(), "LinearScan inserts only moves to virtual registers");
459 LIR_Op1* op1 = (LIR_Op1*)op;
460 Interval* interval = interval_at(op1->result_opr()->vreg_number());
462 if (interval->assigned_reg() >= LinearScan::nof_regs && interval->always_in_memory()) {
463 // move target is a stack slot that is always correct, so eliminate instruction
464 TRACE_LINEAR_SCAN(4, tty->print_cr("eliminating move from interval %d to %d", op1->in_opr()->vreg_number(), op1->result_opr()->vreg_number()));
465 instructions->at_put(j, NULL); // NULL-instructions are deleted by assign_reg_num
466 }
468 } else {
469 // insert move from register to stack just after the beginning of the interval
470 assert(interval == Interval::end() || interval->spill_definition_pos() >= op_id, "invalid order");
471 assert(interval == Interval::end() || (interval->is_split_parent() && interval->spill_state() == storeAtDefinition), "invalid interval");
473 while (interval != Interval::end() && interval->spill_definition_pos() == op_id) {
474 if (!has_new) {
475 // prepare insertion buffer (appended when all instructions of the block are processed)
476 insertion_buffer.init(block->lir());
477 has_new = true;
478 }
480 LIR_Opr from_opr = operand_for_interval(interval);
481 LIR_Opr to_opr = canonical_spill_opr(interval);
482 assert(from_opr->is_fixed_cpu() || from_opr->is_fixed_fpu(), "from operand must be a register");
483 assert(to_opr->is_stack(), "to operand must be a stack slot");
485 insertion_buffer.move(j, from_opr, to_opr);
486 TRACE_LINEAR_SCAN(4, tty->print_cr("inserting move after definition of interval %d to stack slot %d at op_id %d", interval->reg_num(), interval->canonical_spill_slot() - LinearScan::nof_regs, op_id));
488 interval = interval->next();
489 }
490 }
491 } // end of instruction iteration
493 if (has_new) {
494 block->lir()->append(&insertion_buffer);
495 }
496 } // end of block iteration
498 assert(interval == Interval::end(), "missed an interval");
499 }
502 // ********** Phase 1: number all instructions in all blocks
503 // Compute depth-first and linear scan block orders, and number LIR_Op nodes for linear scan.
505 void LinearScan::number_instructions() {
506 {
507 // dummy-timer to measure the cost of the timer itself
508 // (this time is then subtracted from all other timers to get the real value)
509 TIME_LINEAR_SCAN(timer_do_nothing);
510 }
511 TIME_LINEAR_SCAN(timer_number_instructions);
513 // Assign IDs to LIR nodes and build a mapping, lir_ops, from ID to LIR_Op node.
514 int num_blocks = block_count();
515 int num_instructions = 0;
516 int i;
517 for (i = 0; i < num_blocks; i++) {
518 num_instructions += block_at(i)->lir()->instructions_list()->length();
519 }
521 // initialize with correct length
522 _lir_ops = LIR_OpArray(num_instructions);
523 _block_of_op = BlockBeginArray(num_instructions);
525 int op_id = 0;
526 int idx = 0;
528 for (i = 0; i < num_blocks; i++) {
529 BlockBegin* block = block_at(i);
530 block->set_first_lir_instruction_id(op_id);
531 LIR_OpList* instructions = block->lir()->instructions_list();
533 int num_inst = instructions->length();
534 for (int j = 0; j < num_inst; j++) {
535 LIR_Op* op = instructions->at(j);
536 op->set_id(op_id);
538 _lir_ops.at_put(idx, op);
539 _block_of_op.at_put(idx, block);
540 assert(lir_op_with_id(op_id) == op, "must match");
542 idx++;
543 op_id += 2; // numbering of lir_ops by two
544 }
545 block->set_last_lir_instruction_id(op_id - 2);
546 }
547 assert(idx == num_instructions, "must match");
548 assert(idx * 2 == op_id, "must match");
550 _has_call = BitMap(num_instructions); _has_call.clear();
551 _has_info = BitMap(num_instructions); _has_info.clear();
552 }
555 // ********** Phase 2: compute local live sets separately for each block
556 // (sets live_gen and live_kill for each block)
558 void LinearScan::set_live_gen_kill(Value value, LIR_Op* op, BitMap& live_gen, BitMap& live_kill) {
559 LIR_Opr opr = value->operand();
560 Constant* con = value->as_Constant();
562 // check some asumptions about debug information
563 assert(!value->type()->is_illegal(), "if this local is used by the interpreter it shouldn't be of indeterminate type");
564 assert(con == NULL || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "asumption: Constant instructions have only constant operands");
565 assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");
567 if ((con == NULL || con->is_pinned()) && opr->is_register()) {
568 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
569 int reg = opr->vreg_number();
570 if (!live_kill.at(reg)) {
571 live_gen.set_bit(reg);
572 TRACE_LINEAR_SCAN(4, tty->print_cr(" Setting live_gen for value %c%d, LIR op_id %d, register number %d", value->type()->tchar(), value->id(), op->id(), reg));
573 }
574 }
575 }
578 void LinearScan::compute_local_live_sets() {
579 TIME_LINEAR_SCAN(timer_compute_local_live_sets);
581 int num_blocks = block_count();
582 int live_size = live_set_size();
583 bool local_has_fpu_registers = false;
584 int local_num_calls = 0;
585 LIR_OpVisitState visitor;
587 BitMap2D local_interval_in_loop = BitMap2D(_num_virtual_regs, num_loops());
588 local_interval_in_loop.clear();
590 // iterate all blocks
591 for (int i = 0; i < num_blocks; i++) {
592 BlockBegin* block = block_at(i);
594 BitMap live_gen(live_size); live_gen.clear();
595 BitMap live_kill(live_size); live_kill.clear();
597 if (block->is_set(BlockBegin::exception_entry_flag)) {
598 // Phi functions at the begin of an exception handler are
599 // implicitly defined (= killed) at the beginning of the block.
600 for_each_phi_fun(block, phi,
601 live_kill.set_bit(phi->operand()->vreg_number())
602 );
603 }
605 LIR_OpList* instructions = block->lir()->instructions_list();
606 int num_inst = instructions->length();
608 // iterate all instructions of the block. skip the first because it is always a label
609 assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
610 for (int j = 1; j < num_inst; j++) {
611 LIR_Op* op = instructions->at(j);
613 // visit operation to collect all operands
614 visitor.visit(op);
616 if (visitor.has_call()) {
617 _has_call.set_bit(op->id() >> 1);
618 local_num_calls++;
619 }
620 if (visitor.info_count() > 0) {
621 _has_info.set_bit(op->id() >> 1);
622 }
624 // iterate input operands of instruction
625 int k, n, reg;
626 n = visitor.opr_count(LIR_OpVisitState::inputMode);
627 for (k = 0; k < n; k++) {
628 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
629 assert(opr->is_register(), "visitor should only return register operands");
631 if (opr->is_virtual_register()) {
632 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
633 reg = opr->vreg_number();
634 if (!live_kill.at(reg)) {
635 live_gen.set_bit(reg);
636 TRACE_LINEAR_SCAN(4, tty->print_cr(" Setting live_gen for register %d at instruction %d", reg, op->id()));
637 }
638 if (block->loop_index() >= 0) {
639 local_interval_in_loop.set_bit(reg, block->loop_index());
640 }
641 local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
642 }
644 #ifdef ASSERT
645 // fixed intervals are never live at block boundaries, so
646 // they need not be processed in live sets.
647 // this is checked by these assertions to be sure about it.
648 // the entry block may have incoming values in registers, which is ok.
649 if (!opr->is_virtual_register() && block != ir()->start()) {
650 reg = reg_num(opr);
651 if (is_processed_reg_num(reg)) {
652 assert(live_kill.at(reg), "using fixed register that is not defined in this block");
653 }
654 reg = reg_numHi(opr);
655 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
656 assert(live_kill.at(reg), "using fixed register that is not defined in this block");
657 }
658 }
659 #endif
660 }
662 // Add uses of live locals from interpreter's point of view for proper debug information generation
663 n = visitor.info_count();
664 for (k = 0; k < n; k++) {
665 CodeEmitInfo* info = visitor.info_at(k);
666 ValueStack* stack = info->stack();
667 for_each_state_value(stack, value,
668 set_live_gen_kill(value, op, live_gen, live_kill)
669 );
670 }
672 // iterate temp operands of instruction
673 n = visitor.opr_count(LIR_OpVisitState::tempMode);
674 for (k = 0; k < n; k++) {
675 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
676 assert(opr->is_register(), "visitor should only return register operands");
678 if (opr->is_virtual_register()) {
679 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
680 reg = opr->vreg_number();
681 live_kill.set_bit(reg);
682 if (block->loop_index() >= 0) {
683 local_interval_in_loop.set_bit(reg, block->loop_index());
684 }
685 local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
686 }
688 #ifdef ASSERT
689 // fixed intervals are never live at block boundaries, so
690 // they need not be processed in live sets
691 // process them only in debug mode so that this can be checked
692 if (!opr->is_virtual_register()) {
693 reg = reg_num(opr);
694 if (is_processed_reg_num(reg)) {
695 live_kill.set_bit(reg_num(opr));
696 }
697 reg = reg_numHi(opr);
698 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
699 live_kill.set_bit(reg);
700 }
701 }
702 #endif
703 }
705 // iterate output operands of instruction
706 n = visitor.opr_count(LIR_OpVisitState::outputMode);
707 for (k = 0; k < n; k++) {
708 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
709 assert(opr->is_register(), "visitor should only return register operands");
711 if (opr->is_virtual_register()) {
712 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
713 reg = opr->vreg_number();
714 live_kill.set_bit(reg);
715 if (block->loop_index() >= 0) {
716 local_interval_in_loop.set_bit(reg, block->loop_index());
717 }
718 local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
719 }
721 #ifdef ASSERT
722 // fixed intervals are never live at block boundaries, so
723 // they need not be processed in live sets
724 // process them only in debug mode so that this can be checked
725 if (!opr->is_virtual_register()) {
726 reg = reg_num(opr);
727 if (is_processed_reg_num(reg)) {
728 live_kill.set_bit(reg_num(opr));
729 }
730 reg = reg_numHi(opr);
731 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
732 live_kill.set_bit(reg);
733 }
734 }
735 #endif
736 }
737 } // end of instruction iteration
739 block->set_live_gen (live_gen);
740 block->set_live_kill(live_kill);
741 block->set_live_in (BitMap(live_size)); block->live_in().clear();
742 block->set_live_out (BitMap(live_size)); block->live_out().clear();
744 TRACE_LINEAR_SCAN(4, tty->print("live_gen B%d ", block->block_id()); print_bitmap(block->live_gen()));
745 TRACE_LINEAR_SCAN(4, tty->print("live_kill B%d ", block->block_id()); print_bitmap(block->live_kill()));
746 } // end of block iteration
748 // propagate local calculated information into LinearScan object
749 _has_fpu_registers = local_has_fpu_registers;
750 compilation()->set_has_fpu_code(local_has_fpu_registers);
752 _num_calls = local_num_calls;
753 _interval_in_loop = local_interval_in_loop;
754 }
757 // ********** Phase 3: perform a backward dataflow analysis to compute global live sets
758 // (sets live_in and live_out for each block)
760 void LinearScan::compute_global_live_sets() {
761 TIME_LINEAR_SCAN(timer_compute_global_live_sets);
763 int num_blocks = block_count();
764 bool change_occurred;
765 bool change_occurred_in_block;
766 int iteration_count = 0;
767 BitMap live_out(live_set_size()); live_out.clear(); // scratch set for calculations
769 // Perform a backward dataflow analysis to compute live_out and live_in for each block.
770 // The loop is executed until a fixpoint is reached (no changes in an iteration)
771 // Exception handlers must be processed because not all live values are
772 // present in the state array, e.g. because of global value numbering
773 do {
774 change_occurred = false;
776 // iterate all blocks in reverse order
777 for (int i = num_blocks - 1; i >= 0; i--) {
778 BlockBegin* block = block_at(i);
780 change_occurred_in_block = false;
782 // live_out(block) is the union of live_in(sux), for successors sux of block
783 int n = block->number_of_sux();
784 int e = block->number_of_exception_handlers();
785 if (n + e > 0) {
786 // block has successors
787 if (n > 0) {
788 live_out.set_from(block->sux_at(0)->live_in());
789 for (int j = 1; j < n; j++) {
790 live_out.set_union(block->sux_at(j)->live_in());
791 }
792 } else {
793 live_out.clear();
794 }
795 for (int j = 0; j < e; j++) {
796 live_out.set_union(block->exception_handler_at(j)->live_in());
797 }
799 if (!block->live_out().is_same(live_out)) {
800 // A change occurred. Swap the old and new live out sets to avoid copying.
801 BitMap temp = block->live_out();
802 block->set_live_out(live_out);
803 live_out = temp;
805 change_occurred = true;
806 change_occurred_in_block = true;
807 }
808 }
810 if (iteration_count == 0 || change_occurred_in_block) {
811 // live_in(block) is the union of live_gen(block) with (live_out(block) & !live_kill(block))
812 // note: live_in has to be computed only in first iteration or if live_out has changed!
813 BitMap live_in = block->live_in();
814 live_in.set_from(block->live_out());
815 live_in.set_difference(block->live_kill());
816 live_in.set_union(block->live_gen());
817 }
819 #ifndef PRODUCT
820 if (TraceLinearScanLevel >= 4) {
821 char c = ' ';
822 if (iteration_count == 0 || change_occurred_in_block) {
823 c = '*';
824 }
825 tty->print("(%d) live_in%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_in());
826 tty->print("(%d) live_out%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_out());
827 }
828 #endif
829 }
830 iteration_count++;
832 if (change_occurred && iteration_count > 50) {
833 BAILOUT("too many iterations in compute_global_live_sets");
834 }
835 } while (change_occurred);
838 #ifdef ASSERT
839 // check that fixed intervals are not live at block boundaries
840 // (live set must be empty at fixed intervals)
841 for (int i = 0; i < num_blocks; i++) {
842 BlockBegin* block = block_at(i);
843 for (int j = 0; j < LIR_OprDesc::vreg_base; j++) {
844 assert(block->live_in().at(j) == false, "live_in set of fixed register must be empty");
845 assert(block->live_out().at(j) == false, "live_out set of fixed register must be empty");
846 assert(block->live_gen().at(j) == false, "live_gen set of fixed register must be empty");
847 }
848 }
849 #endif
851 // check that the live_in set of the first block is empty
852 BitMap live_in_args(ir()->start()->live_in().size());
853 live_in_args.clear();
854 if (!ir()->start()->live_in().is_same(live_in_args)) {
855 #ifdef ASSERT
856 tty->print_cr("Error: live_in set of first block must be empty (when this fails, virtual registers are used before they are defined)");
857 tty->print_cr("affected registers:");
858 print_bitmap(ir()->start()->live_in());
860 // print some additional information to simplify debugging
861 for (unsigned int i = 0; i < ir()->start()->live_in().size(); i++) {
862 if (ir()->start()->live_in().at(i)) {
863 Instruction* instr = gen()->instruction_for_vreg(i);
864 tty->print_cr("* vreg %d (HIR instruction %c%d)", i, instr == NULL ? ' ' : instr->type()->tchar(), instr == NULL ? 0 : instr->id());
866 for (int j = 0; j < num_blocks; j++) {
867 BlockBegin* block = block_at(j);
868 if (block->live_gen().at(i)) {
869 tty->print_cr(" used in block B%d", block->block_id());
870 }
871 if (block->live_kill().at(i)) {
872 tty->print_cr(" defined in block B%d", block->block_id());
873 }
874 }
875 }
876 }
878 #endif
879 // when this fails, virtual registers are used before they are defined.
880 assert(false, "live_in set of first block must be empty");
881 // bailout of if this occurs in product mode.
882 bailout("live_in set of first block not empty");
883 }
884 }
887 // ********** Phase 4: build intervals
888 // (fills the list _intervals)
890 void LinearScan::add_use(Value value, int from, int to, IntervalUseKind use_kind) {
891 assert(!value->type()->is_illegal(), "if this value is used by the interpreter it shouldn't be of indeterminate type");
892 LIR_Opr opr = value->operand();
893 Constant* con = value->as_Constant();
895 if ((con == NULL || con->is_pinned()) && opr->is_register()) {
896 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
897 add_use(opr, from, to, use_kind);
898 }
899 }
902 void LinearScan::add_def(LIR_Opr opr, int def_pos, IntervalUseKind use_kind) {
903 TRACE_LINEAR_SCAN(2, tty->print(" def "); opr->print(tty); tty->print_cr(" def_pos %d (%d)", def_pos, use_kind));
904 assert(opr->is_register(), "should not be called otherwise");
906 if (opr->is_virtual_register()) {
907 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
908 add_def(opr->vreg_number(), def_pos, use_kind, opr->type_register());
910 } else {
911 int reg = reg_num(opr);
912 if (is_processed_reg_num(reg)) {
913 add_def(reg, def_pos, use_kind, opr->type_register());
914 }
915 reg = reg_numHi(opr);
916 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
917 add_def(reg, def_pos, use_kind, opr->type_register());
918 }
919 }
920 }
922 void LinearScan::add_use(LIR_Opr opr, int from, int to, IntervalUseKind use_kind) {
923 TRACE_LINEAR_SCAN(2, tty->print(" use "); opr->print(tty); tty->print_cr(" from %d to %d (%d)", from, to, use_kind));
924 assert(opr->is_register(), "should not be called otherwise");
926 if (opr->is_virtual_register()) {
927 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
928 add_use(opr->vreg_number(), from, to, use_kind, opr->type_register());
930 } else {
931 int reg = reg_num(opr);
932 if (is_processed_reg_num(reg)) {
933 add_use(reg, from, to, use_kind, opr->type_register());
934 }
935 reg = reg_numHi(opr);
936 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
937 add_use(reg, from, to, use_kind, opr->type_register());
938 }
939 }
940 }
942 void LinearScan::add_temp(LIR_Opr opr, int temp_pos, IntervalUseKind use_kind) {
943 TRACE_LINEAR_SCAN(2, tty->print(" temp "); opr->print(tty); tty->print_cr(" temp_pos %d (%d)", temp_pos, use_kind));
944 assert(opr->is_register(), "should not be called otherwise");
946 if (opr->is_virtual_register()) {
947 assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
948 add_temp(opr->vreg_number(), temp_pos, use_kind, opr->type_register());
950 } else {
951 int reg = reg_num(opr);
952 if (is_processed_reg_num(reg)) {
953 add_temp(reg, temp_pos, use_kind, opr->type_register());
954 }
955 reg = reg_numHi(opr);
956 if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
957 add_temp(reg, temp_pos, use_kind, opr->type_register());
958 }
959 }
960 }
963 void LinearScan::add_def(int reg_num, int def_pos, IntervalUseKind use_kind, BasicType type) {
964 Interval* interval = interval_at(reg_num);
965 if (interval != NULL) {
966 assert(interval->reg_num() == reg_num, "wrong interval");
968 if (type != T_ILLEGAL) {
969 interval->set_type(type);
970 }
972 Range* r = interval->first();
973 if (r->from() <= def_pos) {
974 // Update the starting point (when a range is first created for a use, its
975 // start is the beginning of the current block until a def is encountered.)
976 r->set_from(def_pos);
977 interval->add_use_pos(def_pos, use_kind);
979 } else {
980 // Dead value - make vacuous interval
981 // also add use_kind for dead intervals
982 interval->add_range(def_pos, def_pos + 1);
983 interval->add_use_pos(def_pos, use_kind);
984 TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: def of reg %d at %d occurs without use", reg_num, def_pos));
985 }
987 } else {
988 // Dead value - make vacuous interval
989 // also add use_kind for dead intervals
990 interval = create_interval(reg_num);
991 if (type != T_ILLEGAL) {
992 interval->set_type(type);
993 }
995 interval->add_range(def_pos, def_pos + 1);
996 interval->add_use_pos(def_pos, use_kind);
997 TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: dead value %d at %d in live intervals", reg_num, def_pos));
998 }
1000 change_spill_definition_pos(interval, def_pos);
1001 if (use_kind == noUse && interval->spill_state() <= startInMemory) {
1002 // detection of method-parameters and roundfp-results
1003 // TODO: move this directly to position where use-kind is computed
1004 interval->set_spill_state(startInMemory);
1005 }
1006 }
1008 void LinearScan::add_use(int reg_num, int from, int to, IntervalUseKind use_kind, BasicType type) {
1009 Interval* interval = interval_at(reg_num);
1010 if (interval == NULL) {
1011 interval = create_interval(reg_num);
1012 }
1013 assert(interval->reg_num() == reg_num, "wrong interval");
1015 if (type != T_ILLEGAL) {
1016 interval->set_type(type);
1017 }
1019 interval->add_range(from, to);
1020 interval->add_use_pos(to, use_kind);
1021 }
1023 void LinearScan::add_temp(int reg_num, int temp_pos, IntervalUseKind use_kind, BasicType type) {
1024 Interval* interval = interval_at(reg_num);
1025 if (interval == NULL) {
1026 interval = create_interval(reg_num);
1027 }
1028 assert(interval->reg_num() == reg_num, "wrong interval");
1030 if (type != T_ILLEGAL) {
1031 interval->set_type(type);
1032 }
1034 interval->add_range(temp_pos, temp_pos + 1);
1035 interval->add_use_pos(temp_pos, use_kind);
1036 }
1039 // the results of this functions are used for optimizing spilling and reloading
1040 // if the functions return shouldHaveRegister and the interval is spilled,
1041 // it is not reloaded to a register.
1042 IntervalUseKind LinearScan::use_kind_of_output_operand(LIR_Op* op, LIR_Opr opr) {
1043 if (op->code() == lir_move) {
1044 assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");
1045 LIR_Op1* move = (LIR_Op1*)op;
1046 LIR_Opr res = move->result_opr();
1047 bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
1049 if (result_in_memory) {
1050 // Begin of an interval with must_start_in_memory set.
1051 // This interval will always get a stack slot first, so return noUse.
1052 return noUse;
1054 } else if (move->in_opr()->is_stack()) {
1055 // method argument (condition must be equal to handle_method_arguments)
1056 return noUse;
1058 } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
1059 // Move from register to register
1060 if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
1061 // special handling of phi-function moves inside osr-entry blocks
1062 // input operand must have a register instead of output operand (leads to better register allocation)
1063 return shouldHaveRegister;
1064 }
1065 }
1066 }
1068 if (opr->is_virtual() &&
1069 gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::must_start_in_memory)) {
1070 // result is a stack-slot, so prevent immediate reloading
1071 return noUse;
1072 }
1074 // all other operands require a register
1075 return mustHaveRegister;
1076 }
1078 IntervalUseKind LinearScan::use_kind_of_input_operand(LIR_Op* op, LIR_Opr opr) {
1079 if (op->code() == lir_move) {
1080 assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");
1081 LIR_Op1* move = (LIR_Op1*)op;
1082 LIR_Opr res = move->result_opr();
1083 bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
1085 if (result_in_memory) {
1086 // Move to an interval with must_start_in_memory set.
1087 // To avoid moves from stack to stack (not allowed) force the input operand to a register
1088 return mustHaveRegister;
1090 } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
1091 // Move from register to register
1092 if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
1093 // special handling of phi-function moves inside osr-entry blocks
1094 // input operand must have a register instead of output operand (leads to better register allocation)
1095 return mustHaveRegister;
1096 }
1098 // The input operand is not forced to a register (moves from stack to register are allowed),
1099 // but it is faster if the input operand is in a register
1100 return shouldHaveRegister;
1101 }
1102 }
1105 #ifdef X86
1106 if (op->code() == lir_cmove) {
1107 // conditional moves can handle stack operands
1108 assert(op->result_opr()->is_register(), "result must always be in a register");
1109 return shouldHaveRegister;
1110 }
1112 // optimizations for second input operand of arithmehtic operations on Intel
1113 // this operand is allowed to be on the stack in some cases
1114 BasicType opr_type = opr->type_register();
1115 if (opr_type == T_FLOAT || opr_type == T_DOUBLE) {
1116 if ((UseSSE == 1 && opr_type == T_FLOAT) || UseSSE >= 2) {
1117 // SSE float instruction (T_DOUBLE only supported with SSE2)
1118 switch (op->code()) {
1119 case lir_cmp:
1120 case lir_add:
1121 case lir_sub:
1122 case lir_mul:
1123 case lir_div:
1124 {
1125 assert(op->as_Op2() != NULL, "must be LIR_Op2");
1126 LIR_Op2* op2 = (LIR_Op2*)op;
1127 if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
1128 assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
1129 return shouldHaveRegister;
1130 }
1131 }
1132 }
1133 } else {
1134 // FPU stack float instruction
1135 switch (op->code()) {
1136 case lir_add:
1137 case lir_sub:
1138 case lir_mul:
1139 case lir_div:
1140 {
1141 assert(op->as_Op2() != NULL, "must be LIR_Op2");
1142 LIR_Op2* op2 = (LIR_Op2*)op;
1143 if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
1144 assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
1145 return shouldHaveRegister;
1146 }
1147 }
1148 }
1149 }
1150 // We want to sometimes use logical operations on pointers, in particular in GC barriers.
1151 // Since 64bit logical operations do not current support operands on stack, we have to make sure
1152 // T_OBJECT doesn't get spilled along with T_LONG.
1153 } else if (opr_type != T_LONG LP64_ONLY(&& opr_type != T_OBJECT)) {
1154 // integer instruction (note: long operands must always be in register)
1155 switch (op->code()) {
1156 case lir_cmp:
1157 case lir_add:
1158 case lir_sub:
1159 case lir_logic_and:
1160 case lir_logic_or:
1161 case lir_logic_xor:
1162 {
1163 assert(op->as_Op2() != NULL, "must be LIR_Op2");
1164 LIR_Op2* op2 = (LIR_Op2*)op;
1165 if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
1166 assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
1167 return shouldHaveRegister;
1168 }
1169 }
1170 }
1171 }
1172 #endif // X86
1174 // all other operands require a register
1175 return mustHaveRegister;
1176 }
1179 void LinearScan::handle_method_arguments(LIR_Op* op) {
1180 // special handling for method arguments (moves from stack to virtual register):
1181 // the interval gets no register assigned, but the stack slot.
1182 // it is split before the first use by the register allocator.
1184 if (op->code() == lir_move) {
1185 assert(op->as_Op1() != NULL, "must be LIR_Op1");
1186 LIR_Op1* move = (LIR_Op1*)op;
1188 if (move->in_opr()->is_stack()) {
1189 #ifdef ASSERT
1190 int arg_size = compilation()->method()->arg_size();
1191 LIR_Opr o = move->in_opr();
1192 if (o->is_single_stack()) {
1193 assert(o->single_stack_ix() >= 0 && o->single_stack_ix() < arg_size, "out of range");
1194 } else if (o->is_double_stack()) {
1195 assert(o->double_stack_ix() >= 0 && o->double_stack_ix() < arg_size, "out of range");
1196 } else {
1197 ShouldNotReachHere();
1198 }
1200 assert(move->id() > 0, "invalid id");
1201 assert(block_of_op_with_id(move->id())->number_of_preds() == 0, "move from stack must be in first block");
1202 assert(move->result_opr()->is_virtual(), "result of move must be a virtual register");
1204 TRACE_LINEAR_SCAN(4, tty->print_cr("found move from stack slot %d to vreg %d", o->is_single_stack() ? o->single_stack_ix() : o->double_stack_ix(), reg_num(move->result_opr())));
1205 #endif
1207 Interval* interval = interval_at(reg_num(move->result_opr()));
1209 int stack_slot = LinearScan::nof_regs + (move->in_opr()->is_single_stack() ? move->in_opr()->single_stack_ix() : move->in_opr()->double_stack_ix());
1210 interval->set_canonical_spill_slot(stack_slot);
1211 interval->assign_reg(stack_slot);
1212 }
1213 }
1214 }
1216 void LinearScan::handle_doubleword_moves(LIR_Op* op) {
1217 // special handling for doubleword move from memory to register:
1218 // in this case the registers of the input address and the result
1219 // registers must not overlap -> add a temp range for the input registers
1220 if (op->code() == lir_move) {
1221 assert(op->as_Op1() != NULL, "must be LIR_Op1");
1222 LIR_Op1* move = (LIR_Op1*)op;
1224 if (move->result_opr()->is_double_cpu() && move->in_opr()->is_pointer()) {
1225 LIR_Address* address = move->in_opr()->as_address_ptr();
1226 if (address != NULL) {
1227 if (address->base()->is_valid()) {
1228 add_temp(address->base(), op->id(), noUse);
1229 }
1230 if (address->index()->is_valid()) {
1231 add_temp(address->index(), op->id(), noUse);
1232 }
1233 }
1234 }
1235 }
1236 }
1238 void LinearScan::add_register_hints(LIR_Op* op) {
1239 switch (op->code()) {
1240 case lir_move: // fall through
1241 case lir_convert: {
1242 assert(op->as_Op1() != NULL, "lir_move, lir_convert must be LIR_Op1");
1243 LIR_Op1* move = (LIR_Op1*)op;
1245 LIR_Opr move_from = move->in_opr();
1246 LIR_Opr move_to = move->result_opr();
1248 if (move_to->is_register() && move_from->is_register()) {
1249 Interval* from = interval_at(reg_num(move_from));
1250 Interval* to = interval_at(reg_num(move_to));
1251 if (from != NULL && to != NULL) {
1252 to->set_register_hint(from);
1253 TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", move->id(), from->reg_num(), to->reg_num()));
1254 }
1255 }
1256 break;
1257 }
1258 case lir_cmove: {
1259 assert(op->as_Op2() != NULL, "lir_cmove must be LIR_Op2");
1260 LIR_Op2* cmove = (LIR_Op2*)op;
1262 LIR_Opr move_from = cmove->in_opr1();
1263 LIR_Opr move_to = cmove->result_opr();
1265 if (move_to->is_register() && move_from->is_register()) {
1266 Interval* from = interval_at(reg_num(move_from));
1267 Interval* to = interval_at(reg_num(move_to));
1268 if (from != NULL && to != NULL) {
1269 to->set_register_hint(from);
1270 TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", cmove->id(), from->reg_num(), to->reg_num()));
1271 }
1272 }
1273 break;
1274 }
1275 }
1276 }
1279 void LinearScan::build_intervals() {
1280 TIME_LINEAR_SCAN(timer_build_intervals);
1282 // initialize interval list with expected number of intervals
1283 // (32 is added to have some space for split children without having to resize the list)
1284 _intervals = IntervalList(num_virtual_regs() + 32);
1285 // initialize all slots that are used by build_intervals
1286 _intervals.at_put_grow(num_virtual_regs() - 1, NULL, NULL);
1288 // create a list with all caller-save registers (cpu, fpu, xmm)
1289 // when an instruction is a call, a temp range is created for all these registers
1290 int num_caller_save_registers = 0;
1291 int caller_save_registers[LinearScan::nof_regs];
1293 int i;
1294 for (i = 0; i < FrameMap::nof_caller_save_cpu_regs(); i++) {
1295 LIR_Opr opr = FrameMap::caller_save_cpu_reg_at(i);
1296 assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
1297 assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
1298 caller_save_registers[num_caller_save_registers++] = reg_num(opr);
1299 }
1301 // temp ranges for fpu registers are only created when the method has
1302 // virtual fpu operands. Otherwise no allocation for fpu registers is
1303 // perfomed and so the temp ranges would be useless
1304 if (has_fpu_registers()) {
1305 #ifdef X86
1306 if (UseSSE < 2) {
1307 #endif
1308 for (i = 0; i < FrameMap::nof_caller_save_fpu_regs; i++) {
1309 LIR_Opr opr = FrameMap::caller_save_fpu_reg_at(i);
1310 assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
1311 assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
1312 caller_save_registers[num_caller_save_registers++] = reg_num(opr);
1313 }
1314 #ifdef X86
1315 }
1316 if (UseSSE > 0) {
1317 for (i = 0; i < FrameMap::nof_caller_save_xmm_regs; i++) {
1318 LIR_Opr opr = FrameMap::caller_save_xmm_reg_at(i);
1319 assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
1320 assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
1321 caller_save_registers[num_caller_save_registers++] = reg_num(opr);
1322 }
1323 }
1324 #endif
1325 }
1326 assert(num_caller_save_registers <= LinearScan::nof_regs, "out of bounds");
1329 LIR_OpVisitState visitor;
1331 // iterate all blocks in reverse order
1332 for (i = block_count() - 1; i >= 0; i--) {
1333 BlockBegin* block = block_at(i);
1334 LIR_OpList* instructions = block->lir()->instructions_list();
1335 int block_from = block->first_lir_instruction_id();
1336 int block_to = block->last_lir_instruction_id();
1338 assert(block_from == instructions->at(0)->id(), "must be");
1339 assert(block_to == instructions->at(instructions->length() - 1)->id(), "must be");
1341 // Update intervals for registers live at the end of this block;
1342 BitMap live = block->live_out();
1343 int size = (int)live.size();
1344 for (int number = (int)live.get_next_one_offset(0, size); number < size; number = (int)live.get_next_one_offset(number + 1, size)) {
1345 assert(live.at(number), "should not stop here otherwise");
1346 assert(number >= LIR_OprDesc::vreg_base, "fixed intervals must not be live on block bounds");
1347 TRACE_LINEAR_SCAN(2, tty->print_cr("live in %d to %d", number, block_to + 2));
1349 add_use(number, block_from, block_to + 2, noUse, T_ILLEGAL);
1351 // add special use positions for loop-end blocks when the
1352 // interval is used anywhere inside this loop. It's possible
1353 // that the block was part of a non-natural loop, so it might
1354 // have an invalid loop index.
1355 if (block->is_set(BlockBegin::linear_scan_loop_end_flag) &&
1356 block->loop_index() != -1 &&
1357 is_interval_in_loop(number, block->loop_index())) {
1358 interval_at(number)->add_use_pos(block_to + 1, loopEndMarker);
1359 }
1360 }
1362 // iterate all instructions of the block in reverse order.
1363 // skip the first instruction because it is always a label
1364 // definitions of intervals are processed before uses
1365 assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
1366 for (int j = instructions->length() - 1; j >= 1; j--) {
1367 LIR_Op* op = instructions->at(j);
1368 int op_id = op->id();
1370 // visit operation to collect all operands
1371 visitor.visit(op);
1373 // add a temp range for each register if operation destroys caller-save registers
1374 if (visitor.has_call()) {
1375 for (int k = 0; k < num_caller_save_registers; k++) {
1376 add_temp(caller_save_registers[k], op_id, noUse, T_ILLEGAL);
1377 }
1378 TRACE_LINEAR_SCAN(4, tty->print_cr("operation destroys all caller-save registers"));
1379 }
1381 // Add any platform dependent temps
1382 pd_add_temps(op);
1384 // visit definitions (output and temp operands)
1385 int k, n;
1386 n = visitor.opr_count(LIR_OpVisitState::outputMode);
1387 for (k = 0; k < n; k++) {
1388 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
1389 assert(opr->is_register(), "visitor should only return register operands");
1390 add_def(opr, op_id, use_kind_of_output_operand(op, opr));
1391 }
1393 n = visitor.opr_count(LIR_OpVisitState::tempMode);
1394 for (k = 0; k < n; k++) {
1395 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
1396 assert(opr->is_register(), "visitor should only return register operands");
1397 add_temp(opr, op_id, mustHaveRegister);
1398 }
1400 // visit uses (input operands)
1401 n = visitor.opr_count(LIR_OpVisitState::inputMode);
1402 for (k = 0; k < n; k++) {
1403 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
1404 assert(opr->is_register(), "visitor should only return register operands");
1405 add_use(opr, block_from, op_id, use_kind_of_input_operand(op, opr));
1406 }
1408 // Add uses of live locals from interpreter's point of view for proper
1409 // debug information generation
1410 // Treat these operands as temp values (if the life range is extended
1411 // to a call site, the value would be in a register at the call otherwise)
1412 n = visitor.info_count();
1413 for (k = 0; k < n; k++) {
1414 CodeEmitInfo* info = visitor.info_at(k);
1415 ValueStack* stack = info->stack();
1416 for_each_state_value(stack, value,
1417 add_use(value, block_from, op_id + 1, noUse);
1418 );
1419 }
1421 // special steps for some instructions (especially moves)
1422 handle_method_arguments(op);
1423 handle_doubleword_moves(op);
1424 add_register_hints(op);
1426 } // end of instruction iteration
1427 } // end of block iteration
1430 // add the range [0, 1[ to all fixed intervals
1431 // -> the register allocator need not handle unhandled fixed intervals
1432 for (int n = 0; n < LinearScan::nof_regs; n++) {
1433 Interval* interval = interval_at(n);
1434 if (interval != NULL) {
1435 interval->add_range(0, 1);
1436 }
1437 }
1438 }
1441 // ********** Phase 5: actual register allocation
1443 int LinearScan::interval_cmp(Interval** a, Interval** b) {
1444 if (*a != NULL) {
1445 if (*b != NULL) {
1446 return (*a)->from() - (*b)->from();
1447 } else {
1448 return -1;
1449 }
1450 } else {
1451 if (*b != NULL) {
1452 return 1;
1453 } else {
1454 return 0;
1455 }
1456 }
1457 }
1459 #ifndef PRODUCT
1460 bool LinearScan::is_sorted(IntervalArray* intervals) {
1461 int from = -1;
1462 int i, j;
1463 for (i = 0; i < intervals->length(); i ++) {
1464 Interval* it = intervals->at(i);
1465 if (it != NULL) {
1466 if (from > it->from()) {
1467 assert(false, "");
1468 return false;
1469 }
1470 from = it->from();
1471 }
1472 }
1474 // check in both directions if sorted list and unsorted list contain same intervals
1475 for (i = 0; i < interval_count(); i++) {
1476 if (interval_at(i) != NULL) {
1477 int num_found = 0;
1478 for (j = 0; j < intervals->length(); j++) {
1479 if (interval_at(i) == intervals->at(j)) {
1480 num_found++;
1481 }
1482 }
1483 assert(num_found == 1, "lists do not contain same intervals");
1484 }
1485 }
1486 for (j = 0; j < intervals->length(); j++) {
1487 int num_found = 0;
1488 for (i = 0; i < interval_count(); i++) {
1489 if (interval_at(i) == intervals->at(j)) {
1490 num_found++;
1491 }
1492 }
1493 assert(num_found == 1, "lists do not contain same intervals");
1494 }
1496 return true;
1497 }
1498 #endif
1500 void LinearScan::add_to_list(Interval** first, Interval** prev, Interval* interval) {
1501 if (*prev != NULL) {
1502 (*prev)->set_next(interval);
1503 } else {
1504 *first = interval;
1505 }
1506 *prev = interval;
1507 }
1509 void LinearScan::create_unhandled_lists(Interval** list1, Interval** list2, bool (is_list1)(const Interval* i), bool (is_list2)(const Interval* i)) {
1510 assert(is_sorted(_sorted_intervals), "interval list is not sorted");
1512 *list1 = *list2 = Interval::end();
1514 Interval* list1_prev = NULL;
1515 Interval* list2_prev = NULL;
1516 Interval* v;
1518 const int n = _sorted_intervals->length();
1519 for (int i = 0; i < n; i++) {
1520 v = _sorted_intervals->at(i);
1521 if (v == NULL) continue;
1523 if (is_list1(v)) {
1524 add_to_list(list1, &list1_prev, v);
1525 } else if (is_list2 == NULL || is_list2(v)) {
1526 add_to_list(list2, &list2_prev, v);
1527 }
1528 }
1530 if (list1_prev != NULL) list1_prev->set_next(Interval::end());
1531 if (list2_prev != NULL) list2_prev->set_next(Interval::end());
1533 assert(list1_prev == NULL || list1_prev->next() == Interval::end(), "linear list ends not with sentinel");
1534 assert(list2_prev == NULL || list2_prev->next() == Interval::end(), "linear list ends not with sentinel");
1535 }
1538 void LinearScan::sort_intervals_before_allocation() {
1539 TIME_LINEAR_SCAN(timer_sort_intervals_before);
1541 if (_needs_full_resort) {
1542 // There is no known reason why this should occur but just in case...
1543 assert(false, "should never occur");
1544 // Re-sort existing interval list because an Interval::from() has changed
1545 _sorted_intervals->sort(interval_cmp);
1546 _needs_full_resort = false;
1547 }
1549 IntervalList* unsorted_list = &_intervals;
1550 int unsorted_len = unsorted_list->length();
1551 int sorted_len = 0;
1552 int unsorted_idx;
1553 int sorted_idx = 0;
1554 int sorted_from_max = -1;
1556 // calc number of items for sorted list (sorted list must not contain NULL values)
1557 for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
1558 if (unsorted_list->at(unsorted_idx) != NULL) {
1559 sorted_len++;
1560 }
1561 }
1562 IntervalArray* sorted_list = new IntervalArray(sorted_len);
1564 // special sorting algorithm: the original interval-list is almost sorted,
1565 // only some intervals are swapped. So this is much faster than a complete QuickSort
1566 for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
1567 Interval* cur_interval = unsorted_list->at(unsorted_idx);
1569 if (cur_interval != NULL) {
1570 int cur_from = cur_interval->from();
1572 if (sorted_from_max <= cur_from) {
1573 sorted_list->at_put(sorted_idx++, cur_interval);
1574 sorted_from_max = cur_interval->from();
1575 } else {
1576 // the asumption that the intervals are already sorted failed,
1577 // so this interval must be sorted in manually
1578 int j;
1579 for (j = sorted_idx - 1; j >= 0 && cur_from < sorted_list->at(j)->from(); j--) {
1580 sorted_list->at_put(j + 1, sorted_list->at(j));
1581 }
1582 sorted_list->at_put(j + 1, cur_interval);
1583 sorted_idx++;
1584 }
1585 }
1586 }
1587 _sorted_intervals = sorted_list;
1588 assert(is_sorted(_sorted_intervals), "intervals unsorted");
1589 }
1591 void LinearScan::sort_intervals_after_allocation() {
1592 TIME_LINEAR_SCAN(timer_sort_intervals_after);
1594 if (_needs_full_resort) {
1595 // Re-sort existing interval list because an Interval::from() has changed
1596 _sorted_intervals->sort(interval_cmp);
1597 _needs_full_resort = false;
1598 }
1600 IntervalArray* old_list = _sorted_intervals;
1601 IntervalList* new_list = _new_intervals_from_allocation;
1602 int old_len = old_list->length();
1603 int new_len = new_list->length();
1605 if (new_len == 0) {
1606 // no intervals have been added during allocation, so sorted list is already up to date
1607 assert(is_sorted(_sorted_intervals), "intervals unsorted");
1608 return;
1609 }
1611 // conventional sort-algorithm for new intervals
1612 new_list->sort(interval_cmp);
1614 // merge old and new list (both already sorted) into one combined list
1615 IntervalArray* combined_list = new IntervalArray(old_len + new_len);
1616 int old_idx = 0;
1617 int new_idx = 0;
1619 while (old_idx + new_idx < old_len + new_len) {
1620 if (new_idx >= new_len || (old_idx < old_len && old_list->at(old_idx)->from() <= new_list->at(new_idx)->from())) {
1621 combined_list->at_put(old_idx + new_idx, old_list->at(old_idx));
1622 old_idx++;
1623 } else {
1624 combined_list->at_put(old_idx + new_idx, new_list->at(new_idx));
1625 new_idx++;
1626 }
1627 }
1629 _sorted_intervals = combined_list;
1630 assert(is_sorted(_sorted_intervals), "intervals unsorted");
1631 }
1634 void LinearScan::allocate_registers() {
1635 TIME_LINEAR_SCAN(timer_allocate_registers);
1637 Interval* precolored_cpu_intervals, *not_precolored_cpu_intervals;
1638 Interval* precolored_fpu_intervals, *not_precolored_fpu_intervals;
1640 create_unhandled_lists(&precolored_cpu_intervals, ¬_precolored_cpu_intervals, is_precolored_cpu_interval, is_virtual_cpu_interval);
1641 if (has_fpu_registers()) {
1642 create_unhandled_lists(&precolored_fpu_intervals, ¬_precolored_fpu_intervals, is_precolored_fpu_interval, is_virtual_fpu_interval);
1643 #ifdef ASSERT
1644 } else {
1645 // fpu register allocation is omitted because no virtual fpu registers are present
1646 // just check this again...
1647 create_unhandled_lists(&precolored_fpu_intervals, ¬_precolored_fpu_intervals, is_precolored_fpu_interval, is_virtual_fpu_interval);
1648 assert(not_precolored_fpu_intervals == Interval::end(), "missed an uncolored fpu interval");
1649 #endif
1650 }
1652 // allocate cpu registers
1653 LinearScanWalker cpu_lsw(this, precolored_cpu_intervals, not_precolored_cpu_intervals);
1654 cpu_lsw.walk();
1655 cpu_lsw.finish_allocation();
1657 if (has_fpu_registers()) {
1658 // allocate fpu registers
1659 LinearScanWalker fpu_lsw(this, precolored_fpu_intervals, not_precolored_fpu_intervals);
1660 fpu_lsw.walk();
1661 fpu_lsw.finish_allocation();
1662 }
1663 }
1666 // ********** Phase 6: resolve data flow
1667 // (insert moves at edges between blocks if intervals have been split)
1669 // wrapper for Interval::split_child_at_op_id that performs a bailout in product mode
1670 // instead of returning NULL
1671 Interval* LinearScan::split_child_at_op_id(Interval* interval, int op_id, LIR_OpVisitState::OprMode mode) {
1672 Interval* result = interval->split_child_at_op_id(op_id, mode);
1673 if (result != NULL) {
1674 return result;
1675 }
1677 assert(false, "must find an interval, but do a clean bailout in product mode");
1678 result = new Interval(LIR_OprDesc::vreg_base);
1679 result->assign_reg(0);
1680 result->set_type(T_INT);
1681 BAILOUT_("LinearScan: interval is NULL", result);
1682 }
1685 Interval* LinearScan::interval_at_block_begin(BlockBegin* block, int reg_num) {
1686 assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
1687 assert(interval_at(reg_num) != NULL, "no interval found");
1689 return split_child_at_op_id(interval_at(reg_num), block->first_lir_instruction_id(), LIR_OpVisitState::outputMode);
1690 }
1692 Interval* LinearScan::interval_at_block_end(BlockBegin* block, int reg_num) {
1693 assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
1694 assert(interval_at(reg_num) != NULL, "no interval found");
1696 return split_child_at_op_id(interval_at(reg_num), block->last_lir_instruction_id() + 1, LIR_OpVisitState::outputMode);
1697 }
1699 Interval* LinearScan::interval_at_op_id(int reg_num, int op_id) {
1700 assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
1701 assert(interval_at(reg_num) != NULL, "no interval found");
1703 return split_child_at_op_id(interval_at(reg_num), op_id, LIR_OpVisitState::inputMode);
1704 }
1707 void LinearScan::resolve_collect_mappings(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
1708 DEBUG_ONLY(move_resolver.check_empty());
1710 const int num_regs = num_virtual_regs();
1711 const int size = live_set_size();
1712 const BitMap live_at_edge = to_block->live_in();
1714 // visit all registers where the live_at_edge bit is set
1715 for (int r = (int)live_at_edge.get_next_one_offset(0, size); r < size; r = (int)live_at_edge.get_next_one_offset(r + 1, size)) {
1716 assert(r < num_regs, "live information set for not exisiting interval");
1717 assert(from_block->live_out().at(r) && to_block->live_in().at(r), "interval not live at this edge");
1719 Interval* from_interval = interval_at_block_end(from_block, r);
1720 Interval* to_interval = interval_at_block_begin(to_block, r);
1722 if (from_interval != to_interval && (from_interval->assigned_reg() != to_interval->assigned_reg() || from_interval->assigned_regHi() != to_interval->assigned_regHi())) {
1723 // need to insert move instruction
1724 move_resolver.add_mapping(from_interval, to_interval);
1725 }
1726 }
1727 }
1730 void LinearScan::resolve_find_insert_pos(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
1731 if (from_block->number_of_sux() <= 1) {
1732 TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at end of from_block B%d", from_block->block_id()));
1734 LIR_OpList* instructions = from_block->lir()->instructions_list();
1735 LIR_OpBranch* branch = instructions->last()->as_OpBranch();
1736 if (branch != NULL) {
1737 // insert moves before branch
1738 assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
1739 move_resolver.set_insert_position(from_block->lir(), instructions->length() - 2);
1740 } else {
1741 move_resolver.set_insert_position(from_block->lir(), instructions->length() - 1);
1742 }
1744 } else {
1745 TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at beginning of to_block B%d", to_block->block_id()));
1746 #ifdef ASSERT
1747 assert(from_block->lir()->instructions_list()->at(0)->as_OpLabel() != NULL, "block does not start with a label");
1749 // because the number of predecessor edges matches the number of
1750 // successor edges, blocks which are reached by switch statements
1751 // may have be more than one predecessor but it will be guaranteed
1752 // that all predecessors will be the same.
1753 for (int i = 0; i < to_block->number_of_preds(); i++) {
1754 assert(from_block == to_block->pred_at(i), "all critical edges must be broken");
1755 }
1756 #endif
1758 move_resolver.set_insert_position(to_block->lir(), 0);
1759 }
1760 }
1763 // insert necessary moves (spilling or reloading) at edges between blocks if interval has been split
1764 void LinearScan::resolve_data_flow() {
1765 TIME_LINEAR_SCAN(timer_resolve_data_flow);
1767 int num_blocks = block_count();
1768 MoveResolver move_resolver(this);
1769 BitMap block_completed(num_blocks); block_completed.clear();
1770 BitMap already_resolved(num_blocks); already_resolved.clear();
1772 int i;
1773 for (i = 0; i < num_blocks; i++) {
1774 BlockBegin* block = block_at(i);
1776 // check if block has only one predecessor and only one successor
1777 if (block->number_of_preds() == 1 && block->number_of_sux() == 1 && block->number_of_exception_handlers() == 0) {
1778 LIR_OpList* instructions = block->lir()->instructions_list();
1779 assert(instructions->at(0)->code() == lir_label, "block must start with label");
1780 assert(instructions->last()->code() == lir_branch, "block with successors must end with branch");
1781 assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block with successor must end with unconditional branch");
1783 // check if block is empty (only label and branch)
1784 if (instructions->length() == 2) {
1785 BlockBegin* pred = block->pred_at(0);
1786 BlockBegin* sux = block->sux_at(0);
1788 // prevent optimization of two consecutive blocks
1789 if (!block_completed.at(pred->linear_scan_number()) && !block_completed.at(sux->linear_scan_number())) {
1790 TRACE_LINEAR_SCAN(3, tty->print_cr("**** optimizing empty block B%d (pred: B%d, sux: B%d)", block->block_id(), pred->block_id(), sux->block_id()));
1791 block_completed.set_bit(block->linear_scan_number());
1793 // directly resolve between pred and sux (without looking at the empty block between)
1794 resolve_collect_mappings(pred, sux, move_resolver);
1795 if (move_resolver.has_mappings()) {
1796 move_resolver.set_insert_position(block->lir(), 0);
1797 move_resolver.resolve_and_append_moves();
1798 }
1799 }
1800 }
1801 }
1802 }
1805 for (i = 0; i < num_blocks; i++) {
1806 if (!block_completed.at(i)) {
1807 BlockBegin* from_block = block_at(i);
1808 already_resolved.set_from(block_completed);
1810 int num_sux = from_block->number_of_sux();
1811 for (int s = 0; s < num_sux; s++) {
1812 BlockBegin* to_block = from_block->sux_at(s);
1814 // check for duplicate edges between the same blocks (can happen with switch blocks)
1815 if (!already_resolved.at(to_block->linear_scan_number())) {
1816 TRACE_LINEAR_SCAN(3, tty->print_cr("**** processing edge between B%d and B%d", from_block->block_id(), to_block->block_id()));
1817 already_resolved.set_bit(to_block->linear_scan_number());
1819 // collect all intervals that have been split between from_block and to_block
1820 resolve_collect_mappings(from_block, to_block, move_resolver);
1821 if (move_resolver.has_mappings()) {
1822 resolve_find_insert_pos(from_block, to_block, move_resolver);
1823 move_resolver.resolve_and_append_moves();
1824 }
1825 }
1826 }
1827 }
1828 }
1829 }
1832 void LinearScan::resolve_exception_entry(BlockBegin* block, int reg_num, MoveResolver &move_resolver) {
1833 if (interval_at(reg_num) == NULL) {
1834 // if a phi function is never used, no interval is created -> ignore this
1835 return;
1836 }
1838 Interval* interval = interval_at_block_begin(block, reg_num);
1839 int reg = interval->assigned_reg();
1840 int regHi = interval->assigned_regHi();
1842 if ((reg < nof_regs && interval->always_in_memory()) ||
1843 (use_fpu_stack_allocation() && reg >= pd_first_fpu_reg && reg <= pd_last_fpu_reg)) {
1844 // the interval is split to get a short range that is located on the stack
1845 // in the following two cases:
1846 // * the interval started in memory (e.g. method parameter), but is currently in a register
1847 // this is an optimization for exception handling that reduces the number of moves that
1848 // are necessary for resolving the states when an exception uses this exception handler
1849 // * the interval would be on the fpu stack at the begin of the exception handler
1850 // this is not allowed because of the complicated fpu stack handling on Intel
1852 // range that will be spilled to memory
1853 int from_op_id = block->first_lir_instruction_id();
1854 int to_op_id = from_op_id + 1; // short live range of length 1
1855 assert(interval->from() <= from_op_id && interval->to() >= to_op_id,
1856 "no split allowed between exception entry and first instruction");
1858 if (interval->from() != from_op_id) {
1859 // the part before from_op_id is unchanged
1860 interval = interval->split(from_op_id);
1861 interval->assign_reg(reg, regHi);
1862 append_interval(interval);
1863 } else {
1864 _needs_full_resort = true;
1865 }
1866 assert(interval->from() == from_op_id, "must be true now");
1868 Interval* spilled_part = interval;
1869 if (interval->to() != to_op_id) {
1870 // the part after to_op_id is unchanged
1871 spilled_part = interval->split_from_start(to_op_id);
1872 append_interval(spilled_part);
1873 move_resolver.add_mapping(spilled_part, interval);
1874 }
1875 assign_spill_slot(spilled_part);
1877 assert(spilled_part->from() == from_op_id && spilled_part->to() == to_op_id, "just checking");
1878 }
1879 }
1881 void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_resolver) {
1882 assert(block->is_set(BlockBegin::exception_entry_flag), "should not call otherwise");
1883 DEBUG_ONLY(move_resolver.check_empty());
1885 // visit all registers where the live_in bit is set
1886 int size = live_set_size();
1887 for (int r = (int)block->live_in().get_next_one_offset(0, size); r < size; r = (int)block->live_in().get_next_one_offset(r + 1, size)) {
1888 resolve_exception_entry(block, r, move_resolver);
1889 }
1891 // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
1892 for_each_phi_fun(block, phi,
1893 resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver)
1894 );
1896 if (move_resolver.has_mappings()) {
1897 // insert moves after first instruction
1898 move_resolver.set_insert_position(block->lir(), 0);
1899 move_resolver.resolve_and_append_moves();
1900 }
1901 }
1904 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, int reg_num, Phi* phi, MoveResolver &move_resolver) {
1905 if (interval_at(reg_num) == NULL) {
1906 // if a phi function is never used, no interval is created -> ignore this
1907 return;
1908 }
1910 // the computation of to_interval is equal to resolve_collect_mappings,
1911 // but from_interval is more complicated because of phi functions
1912 BlockBegin* to_block = handler->entry_block();
1913 Interval* to_interval = interval_at_block_begin(to_block, reg_num);
1915 if (phi != NULL) {
1916 // phi function of the exception entry block
1917 // no moves are created for this phi function in the LIR_Generator, so the
1918 // interval at the throwing instruction must be searched using the operands
1919 // of the phi function
1920 Value from_value = phi->operand_at(handler->phi_operand());
1922 // with phi functions it can happen that the same from_value is used in
1923 // multiple mappings, so notify move-resolver that this is allowed
1924 move_resolver.set_multiple_reads_allowed();
1926 Constant* con = from_value->as_Constant();
1927 if (con != NULL && !con->is_pinned()) {
1928 // unpinned constants may have no register, so add mapping from constant to interval
1929 move_resolver.add_mapping(LIR_OprFact::value_type(con->type()), to_interval);
1930 } else {
1931 // search split child at the throwing op_id
1932 Interval* from_interval = interval_at_op_id(from_value->operand()->vreg_number(), throwing_op_id);
1933 move_resolver.add_mapping(from_interval, to_interval);
1934 }
1936 } else {
1937 // no phi function, so use reg_num also for from_interval
1938 // search split child at the throwing op_id
1939 Interval* from_interval = interval_at_op_id(reg_num, throwing_op_id);
1940 if (from_interval != to_interval) {
1941 // optimization to reduce number of moves: when to_interval is on stack and
1942 // the stack slot is known to be always correct, then no move is necessary
1943 if (!from_interval->always_in_memory() || from_interval->canonical_spill_slot() != to_interval->assigned_reg()) {
1944 move_resolver.add_mapping(from_interval, to_interval);
1945 }
1946 }
1947 }
1948 }
1950 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, MoveResolver &move_resolver) {
1951 TRACE_LINEAR_SCAN(4, tty->print_cr("resolving exception handler B%d: throwing_op_id=%d", handler->entry_block()->block_id(), throwing_op_id));
1953 DEBUG_ONLY(move_resolver.check_empty());
1954 assert(handler->lir_op_id() == -1, "already processed this xhandler");
1955 DEBUG_ONLY(handler->set_lir_op_id(throwing_op_id));
1956 assert(handler->entry_code() == NULL, "code already present");
1958 // visit all registers where the live_in bit is set
1959 BlockBegin* block = handler->entry_block();
1960 int size = live_set_size();
1961 for (int r = (int)block->live_in().get_next_one_offset(0, size); r < size; r = (int)block->live_in().get_next_one_offset(r + 1, size)) {
1962 resolve_exception_edge(handler, throwing_op_id, r, NULL, move_resolver);
1963 }
1965 // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
1966 for_each_phi_fun(block, phi,
1967 resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver)
1968 );
1970 if (move_resolver.has_mappings()) {
1971 LIR_List* entry_code = new LIR_List(compilation());
1972 move_resolver.set_insert_position(entry_code, 0);
1973 move_resolver.resolve_and_append_moves();
1975 entry_code->jump(handler->entry_block());
1976 handler->set_entry_code(entry_code);
1977 }
1978 }
1981 void LinearScan::resolve_exception_handlers() {
1982 MoveResolver move_resolver(this);
1983 LIR_OpVisitState visitor;
1984 int num_blocks = block_count();
1986 int i;
1987 for (i = 0; i < num_blocks; i++) {
1988 BlockBegin* block = block_at(i);
1989 if (block->is_set(BlockBegin::exception_entry_flag)) {
1990 resolve_exception_entry(block, move_resolver);
1991 }
1992 }
1994 for (i = 0; i < num_blocks; i++) {
1995 BlockBegin* block = block_at(i);
1996 LIR_List* ops = block->lir();
1997 int num_ops = ops->length();
1999 // iterate all instructions of the block. skip the first because it is always a label
2000 assert(visitor.no_operands(ops->at(0)), "first operation must always be a label");
2001 for (int j = 1; j < num_ops; j++) {
2002 LIR_Op* op = ops->at(j);
2003 int op_id = op->id();
2005 if (op_id != -1 && has_info(op_id)) {
2006 // visit operation to collect all operands
2007 visitor.visit(op);
2008 assert(visitor.info_count() > 0, "should not visit otherwise");
2010 XHandlers* xhandlers = visitor.all_xhandler();
2011 int n = xhandlers->length();
2012 for (int k = 0; k < n; k++) {
2013 resolve_exception_edge(xhandlers->handler_at(k), op_id, move_resolver);
2014 }
2016 #ifdef ASSERT
2017 } else {
2018 visitor.visit(op);
2019 assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
2020 #endif
2021 }
2022 }
2023 }
2024 }
2027 // ********** Phase 7: assign register numbers back to LIR
2028 // (includes computation of debug information and oop maps)
2030 VMReg LinearScan::vm_reg_for_interval(Interval* interval) {
2031 VMReg reg = interval->cached_vm_reg();
2032 if (!reg->is_valid() ) {
2033 reg = vm_reg_for_operand(operand_for_interval(interval));
2034 interval->set_cached_vm_reg(reg);
2035 }
2036 assert(reg == vm_reg_for_operand(operand_for_interval(interval)), "wrong cached value");
2037 return reg;
2038 }
2040 VMReg LinearScan::vm_reg_for_operand(LIR_Opr opr) {
2041 assert(opr->is_oop(), "currently only implemented for oop operands");
2042 return frame_map()->regname(opr);
2043 }
2046 LIR_Opr LinearScan::operand_for_interval(Interval* interval) {
2047 LIR_Opr opr = interval->cached_opr();
2048 if (opr->is_illegal()) {
2049 opr = calc_operand_for_interval(interval);
2050 interval->set_cached_opr(opr);
2051 }
2053 assert(opr == calc_operand_for_interval(interval), "wrong cached value");
2054 return opr;
2055 }
2057 LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) {
2058 int assigned_reg = interval->assigned_reg();
2059 BasicType type = interval->type();
2061 if (assigned_reg >= nof_regs) {
2062 // stack slot
2063 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2064 return LIR_OprFact::stack(assigned_reg - nof_regs, type);
2066 } else {
2067 // register
2068 switch (type) {
2069 case T_OBJECT: {
2070 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2071 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2072 return LIR_OprFact::single_cpu_oop(assigned_reg);
2073 }
2075 case T_ADDRESS: {
2076 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2077 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2078 return LIR_OprFact::single_cpu_address(assigned_reg);
2079 }
2081 case T_METADATA: {
2082 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2083 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2084 return LIR_OprFact::single_cpu_metadata(assigned_reg);
2085 }
2087 #ifdef __SOFTFP__
2088 case T_FLOAT: // fall through
2089 #endif // __SOFTFP__
2090 case T_INT: {
2091 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2092 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2093 return LIR_OprFact::single_cpu(assigned_reg);
2094 }
2096 #ifdef __SOFTFP__
2097 case T_DOUBLE: // fall through
2098 #endif // __SOFTFP__
2099 case T_LONG: {
2100 int assigned_regHi = interval->assigned_regHi();
2101 assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
2102 assert(num_physical_regs(T_LONG) == 1 ||
2103 (assigned_regHi >= pd_first_cpu_reg && assigned_regHi <= pd_last_cpu_reg), "no cpu register");
2105 assert(assigned_reg != assigned_regHi, "invalid allocation");
2106 assert(num_physical_regs(T_LONG) == 1 || assigned_reg < assigned_regHi,
2107 "register numbers must be sorted (ensure that e.g. a move from eax,ebx to ebx,eax can not occur)");
2108 assert((assigned_regHi != any_reg) ^ (num_physical_regs(T_LONG) == 1), "must be match");
2109 if (requires_adjacent_regs(T_LONG)) {
2110 assert(assigned_reg % 2 == 0 && assigned_reg + 1 == assigned_regHi, "must be sequential and even");
2111 }
2113 #ifdef _LP64
2114 return LIR_OprFact::double_cpu(assigned_reg, assigned_reg);
2115 #else
2116 #if defined(SPARC) || defined(PPC)
2117 return LIR_OprFact::double_cpu(assigned_regHi, assigned_reg);
2118 #else
2119 return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi);
2120 #endif // SPARC
2121 #endif // LP64
2122 }
2124 #ifndef __SOFTFP__
2125 case T_FLOAT: {
2126 #ifdef X86
2127 if (UseSSE >= 1) {
2128 assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= pd_last_xmm_reg, "no xmm register");
2129 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2130 return LIR_OprFact::single_xmm(assigned_reg - pd_first_xmm_reg);
2131 }
2132 #endif
2134 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2135 assert(interval->assigned_regHi() == any_reg, "must not have hi register");
2136 return LIR_OprFact::single_fpu(assigned_reg - pd_first_fpu_reg);
2137 }
2139 case T_DOUBLE: {
2140 #ifdef X86
2141 if (UseSSE >= 2) {
2142 assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= pd_last_xmm_reg, "no xmm register");
2143 assert(interval->assigned_regHi() == any_reg, "must not have hi register (double xmm values are stored in one register)");
2144 return LIR_OprFact::double_xmm(assigned_reg - pd_first_xmm_reg);
2145 }
2146 #endif
2148 #ifdef SPARC
2149 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2150 assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
2151 assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
2152 LIR_Opr result = LIR_OprFact::double_fpu(interval->assigned_regHi() - pd_first_fpu_reg, assigned_reg - pd_first_fpu_reg);
2153 #elif defined(ARM)
2154 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2155 assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
2156 assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
2157 LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg);
2158 #else
2159 assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
2160 assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)");
2161 LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg);
2162 #endif
2163 return result;
2164 }
2165 #endif // __SOFTFP__
2167 default: {
2168 ShouldNotReachHere();
2169 return LIR_OprFact::illegalOpr;
2170 }
2171 }
2172 }
2173 }
2175 LIR_Opr LinearScan::canonical_spill_opr(Interval* interval) {
2176 assert(interval->canonical_spill_slot() >= nof_regs, "canonical spill slot not set");
2177 return LIR_OprFact::stack(interval->canonical_spill_slot() - nof_regs, interval->type());
2178 }
2180 LIR_Opr LinearScan::color_lir_opr(LIR_Opr opr, int op_id, LIR_OpVisitState::OprMode mode) {
2181 assert(opr->is_virtual(), "should not call this otherwise");
2183 Interval* interval = interval_at(opr->vreg_number());
2184 assert(interval != NULL, "interval must exist");
2186 if (op_id != -1) {
2187 #ifdef ASSERT
2188 BlockBegin* block = block_of_op_with_id(op_id);
2189 if (block->number_of_sux() <= 1 && op_id == block->last_lir_instruction_id()) {
2190 // check if spill moves could have been appended at the end of this block, but
2191 // before the branch instruction. So the split child information for this branch would
2192 // be incorrect.
2193 LIR_OpBranch* branch = block->lir()->instructions_list()->last()->as_OpBranch();
2194 if (branch != NULL) {
2195 if (block->live_out().at(opr->vreg_number())) {
2196 assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
2197 assert(false, "can't get split child for the last branch of a block because the information would be incorrect (moves are inserted before the branch in resolve_data_flow)");
2198 }
2199 }
2200 }
2201 #endif
2203 // operands are not changed when an interval is split during allocation,
2204 // so search the right interval here
2205 interval = split_child_at_op_id(interval, op_id, mode);
2206 }
2208 LIR_Opr res = operand_for_interval(interval);
2210 #ifdef X86
2211 // new semantic for is_last_use: not only set on definite end of interval,
2212 // but also before hole
2213 // This may still miss some cases (e.g. for dead values), but it is not necessary that the
2214 // last use information is completely correct
2215 // information is only needed for fpu stack allocation
2216 if (res->is_fpu_register()) {
2217 if (opr->is_last_use() || op_id == interval->to() || (op_id != -1 && interval->has_hole_between(op_id, op_id + 1))) {
2218 assert(op_id == -1 || !is_block_begin(op_id), "holes at begin of block may also result from control flow");
2219 res = res->make_last_use();
2220 }
2221 }
2222 #endif
2224 assert(!gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::callee_saved) || !FrameMap::is_caller_save_register(res), "bad allocation");
2226 return res;
2227 }
2230 #ifdef ASSERT
2231 // some methods used to check correctness of debug information
2233 void assert_no_register_values(GrowableArray<ScopeValue*>* values) {
2234 if (values == NULL) {
2235 return;
2236 }
2238 for (int i = 0; i < values->length(); i++) {
2239 ScopeValue* value = values->at(i);
2241 if (value->is_location()) {
2242 Location location = ((LocationValue*)value)->location();
2243 assert(location.where() == Location::on_stack, "value is in register");
2244 }
2245 }
2246 }
2248 void assert_no_register_values(GrowableArray<MonitorValue*>* values) {
2249 if (values == NULL) {
2250 return;
2251 }
2253 for (int i = 0; i < values->length(); i++) {
2254 MonitorValue* value = values->at(i);
2256 if (value->owner()->is_location()) {
2257 Location location = ((LocationValue*)value->owner())->location();
2258 assert(location.where() == Location::on_stack, "owner is in register");
2259 }
2260 assert(value->basic_lock().where() == Location::on_stack, "basic_lock is in register");
2261 }
2262 }
2264 void assert_equal(Location l1, Location l2) {
2265 assert(l1.where() == l2.where() && l1.type() == l2.type() && l1.offset() == l2.offset(), "");
2266 }
2268 void assert_equal(ScopeValue* v1, ScopeValue* v2) {
2269 if (v1->is_location()) {
2270 assert(v2->is_location(), "");
2271 assert_equal(((LocationValue*)v1)->location(), ((LocationValue*)v2)->location());
2272 } else if (v1->is_constant_int()) {
2273 assert(v2->is_constant_int(), "");
2274 assert(((ConstantIntValue*)v1)->value() == ((ConstantIntValue*)v2)->value(), "");
2275 } else if (v1->is_constant_double()) {
2276 assert(v2->is_constant_double(), "");
2277 assert(((ConstantDoubleValue*)v1)->value() == ((ConstantDoubleValue*)v2)->value(), "");
2278 } else if (v1->is_constant_long()) {
2279 assert(v2->is_constant_long(), "");
2280 assert(((ConstantLongValue*)v1)->value() == ((ConstantLongValue*)v2)->value(), "");
2281 } else if (v1->is_constant_oop()) {
2282 assert(v2->is_constant_oop(), "");
2283 assert(((ConstantOopWriteValue*)v1)->value() == ((ConstantOopWriteValue*)v2)->value(), "");
2284 } else {
2285 ShouldNotReachHere();
2286 }
2287 }
2289 void assert_equal(MonitorValue* m1, MonitorValue* m2) {
2290 assert_equal(m1->owner(), m2->owner());
2291 assert_equal(m1->basic_lock(), m2->basic_lock());
2292 }
2294 void assert_equal(IRScopeDebugInfo* d1, IRScopeDebugInfo* d2) {
2295 assert(d1->scope() == d2->scope(), "not equal");
2296 assert(d1->bci() == d2->bci(), "not equal");
2298 if (d1->locals() != NULL) {
2299 assert(d1->locals() != NULL && d2->locals() != NULL, "not equal");
2300 assert(d1->locals()->length() == d2->locals()->length(), "not equal");
2301 for (int i = 0; i < d1->locals()->length(); i++) {
2302 assert_equal(d1->locals()->at(i), d2->locals()->at(i));
2303 }
2304 } else {
2305 assert(d1->locals() == NULL && d2->locals() == NULL, "not equal");
2306 }
2308 if (d1->expressions() != NULL) {
2309 assert(d1->expressions() != NULL && d2->expressions() != NULL, "not equal");
2310 assert(d1->expressions()->length() == d2->expressions()->length(), "not equal");
2311 for (int i = 0; i < d1->expressions()->length(); i++) {
2312 assert_equal(d1->expressions()->at(i), d2->expressions()->at(i));
2313 }
2314 } else {
2315 assert(d1->expressions() == NULL && d2->expressions() == NULL, "not equal");
2316 }
2318 if (d1->monitors() != NULL) {
2319 assert(d1->monitors() != NULL && d2->monitors() != NULL, "not equal");
2320 assert(d1->monitors()->length() == d2->monitors()->length(), "not equal");
2321 for (int i = 0; i < d1->monitors()->length(); i++) {
2322 assert_equal(d1->monitors()->at(i), d2->monitors()->at(i));
2323 }
2324 } else {
2325 assert(d1->monitors() == NULL && d2->monitors() == NULL, "not equal");
2326 }
2328 if (d1->caller() != NULL) {
2329 assert(d1->caller() != NULL && d2->caller() != NULL, "not equal");
2330 assert_equal(d1->caller(), d2->caller());
2331 } else {
2332 assert(d1->caller() == NULL && d2->caller() == NULL, "not equal");
2333 }
2334 }
2336 void check_stack_depth(CodeEmitInfo* info, int stack_end) {
2337 if (info->stack()->bci() != SynchronizationEntryBCI && !info->scope()->method()->is_native()) {
2338 Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());
2339 switch (code) {
2340 case Bytecodes::_ifnull : // fall through
2341 case Bytecodes::_ifnonnull : // fall through
2342 case Bytecodes::_ifeq : // fall through
2343 case Bytecodes::_ifne : // fall through
2344 case Bytecodes::_iflt : // fall through
2345 case Bytecodes::_ifge : // fall through
2346 case Bytecodes::_ifgt : // fall through
2347 case Bytecodes::_ifle : // fall through
2348 case Bytecodes::_if_icmpeq : // fall through
2349 case Bytecodes::_if_icmpne : // fall through
2350 case Bytecodes::_if_icmplt : // fall through
2351 case Bytecodes::_if_icmpge : // fall through
2352 case Bytecodes::_if_icmpgt : // fall through
2353 case Bytecodes::_if_icmple : // fall through
2354 case Bytecodes::_if_acmpeq : // fall through
2355 case Bytecodes::_if_acmpne :
2356 assert(stack_end >= -Bytecodes::depth(code), "must have non-empty expression stack at if bytecode");
2357 break;
2358 }
2359 }
2360 }
2362 #endif // ASSERT
2365 IntervalWalker* LinearScan::init_compute_oop_maps() {
2366 // setup lists of potential oops for walking
2367 Interval* oop_intervals;
2368 Interval* non_oop_intervals;
2370 create_unhandled_lists(&oop_intervals, &non_oop_intervals, is_oop_interval, NULL);
2372 // intervals that have no oops inside need not to be processed
2373 // to ensure a walking until the last instruction id, add a dummy interval
2374 // with a high operation id
2375 non_oop_intervals = new Interval(any_reg);
2376 non_oop_intervals->add_range(max_jint - 2, max_jint - 1);
2378 return new IntervalWalker(this, oop_intervals, non_oop_intervals);
2379 }
2382 OopMap* LinearScan::compute_oop_map(IntervalWalker* iw, LIR_Op* op, CodeEmitInfo* info, bool is_call_site) {
2383 TRACE_LINEAR_SCAN(3, tty->print_cr("creating oop map at op_id %d", op->id()));
2385 // walk before the current operation -> intervals that start at
2386 // the operation (= output operands of the operation) are not
2387 // included in the oop map
2388 iw->walk_before(op->id());
2390 int frame_size = frame_map()->framesize();
2391 int arg_count = frame_map()->oop_map_arg_count();
2392 OopMap* map = new OopMap(frame_size, arg_count);
2394 // Iterate through active intervals
2395 for (Interval* interval = iw->active_first(fixedKind); interval != Interval::end(); interval = interval->next()) {
2396 int assigned_reg = interval->assigned_reg();
2398 assert(interval->current_from() <= op->id() && op->id() <= interval->current_to(), "interval should not be active otherwise");
2399 assert(interval->assigned_regHi() == any_reg, "oop must be single word");
2400 assert(interval->reg_num() >= LIR_OprDesc::vreg_base, "fixed interval found");
2402 // Check if this range covers the instruction. Intervals that
2403 // start or end at the current operation are not included in the
2404 // oop map, except in the case of patching moves. For patching
2405 // moves, any intervals which end at this instruction are included
2406 // in the oop map since we may safepoint while doing the patch
2407 // before we've consumed the inputs.
2408 if (op->is_patching() || op->id() < interval->current_to()) {
2410 // caller-save registers must not be included into oop-maps at calls
2411 assert(!is_call_site || assigned_reg >= nof_regs || !is_caller_save(assigned_reg), "interval is in a caller-save register at a call -> register will be overwritten");
2413 VMReg name = vm_reg_for_interval(interval);
2414 set_oop(map, name);
2416 // Spill optimization: when the stack value is guaranteed to be always correct,
2417 // then it must be added to the oop map even if the interval is currently in a register
2418 if (interval->always_in_memory() &&
2419 op->id() > interval->spill_definition_pos() &&
2420 interval->assigned_reg() != interval->canonical_spill_slot()) {
2421 assert(interval->spill_definition_pos() > 0, "position not set correctly");
2422 assert(interval->canonical_spill_slot() >= LinearScan::nof_regs, "no spill slot assigned");
2423 assert(interval->assigned_reg() < LinearScan::nof_regs, "interval is on stack, so stack slot is registered twice");
2425 set_oop(map, frame_map()->slot_regname(interval->canonical_spill_slot() - LinearScan::nof_regs));
2426 }
2427 }
2428 }
2430 // add oops from lock stack
2431 assert(info->stack() != NULL, "CodeEmitInfo must always have a stack");
2432 int locks_count = info->stack()->total_locks_size();
2433 for (int i = 0; i < locks_count; i++) {
2434 set_oop(map, frame_map()->monitor_object_regname(i));
2435 }
2437 return map;
2438 }
2441 void LinearScan::compute_oop_map(IntervalWalker* iw, const LIR_OpVisitState &visitor, LIR_Op* op) {
2442 assert(visitor.info_count() > 0, "no oop map needed");
2444 // compute oop_map only for first CodeEmitInfo
2445 // because it is (in most cases) equal for all other infos of the same operation
2446 CodeEmitInfo* first_info = visitor.info_at(0);
2447 OopMap* first_oop_map = compute_oop_map(iw, op, first_info, visitor.has_call());
2449 for (int i = 0; i < visitor.info_count(); i++) {
2450 CodeEmitInfo* info = visitor.info_at(i);
2451 OopMap* oop_map = first_oop_map;
2453 // compute worst case interpreter size in case of a deoptimization
2454 _compilation->update_interpreter_frame_size(info->interpreter_frame_size());
2456 if (info->stack()->locks_size() != first_info->stack()->locks_size()) {
2457 // this info has a different number of locks then the precomputed oop map
2458 // (possible for lock and unlock instructions) -> compute oop map with
2459 // correct lock information
2460 oop_map = compute_oop_map(iw, op, info, visitor.has_call());
2461 }
2463 if (info->_oop_map == NULL) {
2464 info->_oop_map = oop_map;
2465 } else {
2466 // a CodeEmitInfo can not be shared between different LIR-instructions
2467 // because interval splitting can occur anywhere between two instructions
2468 // and so the oop maps must be different
2469 // -> check if the already set oop_map is exactly the one calculated for this operation
2470 assert(info->_oop_map == oop_map, "same CodeEmitInfo used for multiple LIR instructions");
2471 }
2472 }
2473 }
2476 // frequently used constants
2477 // Allocate them with new so they are never destroyed (otherwise, a
2478 // forced exit could destroy these objects while they are still in
2479 // use).
2480 ConstantOopWriteValue* LinearScan::_oop_null_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantOopWriteValue(NULL);
2481 ConstantIntValue* LinearScan::_int_m1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(-1);
2482 ConstantIntValue* LinearScan::_int_0_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(0);
2483 ConstantIntValue* LinearScan::_int_1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(1);
2484 ConstantIntValue* LinearScan::_int_2_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(2);
2485 LocationValue* _illegal_value = new (ResourceObj::C_HEAP, mtCompiler) LocationValue(Location());
2487 void LinearScan::init_compute_debug_info() {
2488 // cache for frequently used scope values
2489 // (cpu registers and stack slots)
2490 _scope_value_cache = ScopeValueArray((LinearScan::nof_cpu_regs + frame_map()->argcount() + max_spills()) * 2, NULL);
2491 }
2493 MonitorValue* LinearScan::location_for_monitor_index(int monitor_index) {
2494 Location loc;
2495 if (!frame_map()->location_for_monitor_object(monitor_index, &loc)) {
2496 bailout("too large frame");
2497 }
2498 ScopeValue* object_scope_value = new LocationValue(loc);
2500 if (!frame_map()->location_for_monitor_lock(monitor_index, &loc)) {
2501 bailout("too large frame");
2502 }
2503 return new MonitorValue(object_scope_value, loc);
2504 }
2506 LocationValue* LinearScan::location_for_name(int name, Location::Type loc_type) {
2507 Location loc;
2508 if (!frame_map()->locations_for_slot(name, loc_type, &loc)) {
2509 bailout("too large frame");
2510 }
2511 return new LocationValue(loc);
2512 }
2515 int LinearScan::append_scope_value_for_constant(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
2516 assert(opr->is_constant(), "should not be called otherwise");
2518 LIR_Const* c = opr->as_constant_ptr();
2519 BasicType t = c->type();
2520 switch (t) {
2521 case T_OBJECT: {
2522 jobject value = c->as_jobject();
2523 if (value == NULL) {
2524 scope_values->append(_oop_null_scope_value);
2525 } else {
2526 scope_values->append(new ConstantOopWriteValue(c->as_jobject()));
2527 }
2528 return 1;
2529 }
2531 case T_INT: // fall through
2532 case T_FLOAT: {
2533 int value = c->as_jint_bits();
2534 switch (value) {
2535 case -1: scope_values->append(_int_m1_scope_value); break;
2536 case 0: scope_values->append(_int_0_scope_value); break;
2537 case 1: scope_values->append(_int_1_scope_value); break;
2538 case 2: scope_values->append(_int_2_scope_value); break;
2539 default: scope_values->append(new ConstantIntValue(c->as_jint_bits())); break;
2540 }
2541 return 1;
2542 }
2544 case T_LONG: // fall through
2545 case T_DOUBLE: {
2546 #ifdef _LP64
2547 scope_values->append(_int_0_scope_value);
2548 scope_values->append(new ConstantLongValue(c->as_jlong_bits()));
2549 #else
2550 if (hi_word_offset_in_bytes > lo_word_offset_in_bytes) {
2551 scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
2552 scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
2553 } else {
2554 scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
2555 scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
2556 }
2557 #endif
2558 return 2;
2559 }
2561 case T_ADDRESS: {
2562 #ifdef _LP64
2563 scope_values->append(new ConstantLongValue(c->as_jint()));
2564 #else
2565 scope_values->append(new ConstantIntValue(c->as_jint()));
2566 #endif
2567 return 1;
2568 }
2570 default:
2571 ShouldNotReachHere();
2572 return -1;
2573 }
2574 }
2576 int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
2577 if (opr->is_single_stack()) {
2578 int stack_idx = opr->single_stack_ix();
2579 bool is_oop = opr->is_oop_register();
2580 int cache_idx = (stack_idx + LinearScan::nof_cpu_regs) * 2 + (is_oop ? 1 : 0);
2582 ScopeValue* sv = _scope_value_cache.at(cache_idx);
2583 if (sv == NULL) {
2584 Location::Type loc_type = is_oop ? Location::oop : Location::normal;
2585 sv = location_for_name(stack_idx, loc_type);
2586 _scope_value_cache.at_put(cache_idx, sv);
2587 }
2589 // check if cached value is correct
2590 DEBUG_ONLY(assert_equal(sv, location_for_name(stack_idx, is_oop ? Location::oop : Location::normal)));
2592 scope_values->append(sv);
2593 return 1;
2595 } else if (opr->is_single_cpu()) {
2596 bool is_oop = opr->is_oop_register();
2597 int cache_idx = opr->cpu_regnr() * 2 + (is_oop ? 1 : 0);
2598 Location::Type int_loc_type = NOT_LP64(Location::normal) LP64_ONLY(Location::int_in_long);
2600 ScopeValue* sv = _scope_value_cache.at(cache_idx);
2601 if (sv == NULL) {
2602 Location::Type loc_type = is_oop ? Location::oop : int_loc_type;
2603 VMReg rname = frame_map()->regname(opr);
2604 sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
2605 _scope_value_cache.at_put(cache_idx, sv);
2606 }
2608 // check if cached value is correct
2609 DEBUG_ONLY(assert_equal(sv, new LocationValue(Location::new_reg_loc(is_oop ? Location::oop : int_loc_type, frame_map()->regname(opr)))));
2611 scope_values->append(sv);
2612 return 1;
2614 #ifdef X86
2615 } else if (opr->is_single_xmm()) {
2616 VMReg rname = opr->as_xmm_float_reg()->as_VMReg();
2617 LocationValue* sv = new LocationValue(Location::new_reg_loc(Location::normal, rname));
2619 scope_values->append(sv);
2620 return 1;
2621 #endif
2623 } else if (opr->is_single_fpu()) {
2624 #ifdef X86
2625 // the exact location of fpu stack values is only known
2626 // during fpu stack allocation, so the stack allocator object
2627 // must be present
2628 assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");
2629 assert(_fpu_stack_allocator != NULL, "must be present");
2630 opr = _fpu_stack_allocator->to_fpu_stack(opr);
2631 #endif
2633 Location::Type loc_type = float_saved_as_double ? Location::float_in_dbl : Location::normal;
2634 VMReg rname = frame_map()->fpu_regname(opr->fpu_regnr());
2635 #ifndef __SOFTFP__
2636 #ifndef VM_LITTLE_ENDIAN
2637 if (! float_saved_as_double) {
2638 // On big endian system, we may have an issue if float registers use only
2639 // the low half of the (same) double registers.
2640 // Both the float and the double could have the same regnr but would correspond
2641 // to two different addresses once saved.
2643 // get next safely (no assertion checks)
2644 VMReg next = VMRegImpl::as_VMReg(1+rname->value());
2645 if (next->is_reg() &&
2646 (next->as_FloatRegister() == rname->as_FloatRegister())) {
2647 // the back-end does use the same numbering for the double and the float
2648 rname = next; // VMReg for the low bits, e.g. the real VMReg for the float
2649 }
2650 }
2651 #endif
2652 #endif
2653 LocationValue* sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
2655 scope_values->append(sv);
2656 return 1;
2658 } else {
2659 // double-size operands
2661 ScopeValue* first;
2662 ScopeValue* second;
2664 if (opr->is_double_stack()) {
2665 #ifdef _LP64
2666 Location loc1;
2667 Location::Type loc_type = opr->type() == T_LONG ? Location::lng : Location::dbl;
2668 if (!frame_map()->locations_for_slot(opr->double_stack_ix(), loc_type, &loc1, NULL)) {
2669 bailout("too large frame");
2670 }
2671 // Does this reverse on x86 vs. sparc?
2672 first = new LocationValue(loc1);
2673 second = _int_0_scope_value;
2674 #else
2675 Location loc1, loc2;
2676 if (!frame_map()->locations_for_slot(opr->double_stack_ix(), Location::normal, &loc1, &loc2)) {
2677 bailout("too large frame");
2678 }
2679 first = new LocationValue(loc1);
2680 second = new LocationValue(loc2);
2681 #endif // _LP64
2683 } else if (opr->is_double_cpu()) {
2684 #ifdef _LP64
2685 VMReg rname_first = opr->as_register_lo()->as_VMReg();
2686 first = new LocationValue(Location::new_reg_loc(Location::lng, rname_first));
2687 second = _int_0_scope_value;
2688 #else
2689 VMReg rname_first = opr->as_register_lo()->as_VMReg();
2690 VMReg rname_second = opr->as_register_hi()->as_VMReg();
2692 if (hi_word_offset_in_bytes < lo_word_offset_in_bytes) {
2693 // lo/hi and swapped relative to first and second, so swap them
2694 VMReg tmp = rname_first;
2695 rname_first = rname_second;
2696 rname_second = tmp;
2697 }
2699 first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
2700 second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
2701 #endif //_LP64
2704 #ifdef X86
2705 } else if (opr->is_double_xmm()) {
2706 assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation");
2707 VMReg rname_first = opr->as_xmm_double_reg()->as_VMReg();
2708 # ifdef _LP64
2709 first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
2710 second = _int_0_scope_value;
2711 # else
2712 first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
2713 // %%% This is probably a waste but we'll keep things as they were for now
2714 if (true) {
2715 VMReg rname_second = rname_first->next();
2716 second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
2717 }
2718 # endif
2719 #endif
2721 } else if (opr->is_double_fpu()) {
2722 // On SPARC, fpu_regnrLo/fpu_regnrHi represents the two halves of
2723 // the double as float registers in the native ordering. On X86,
2724 // fpu_regnrLo is a FPU stack slot whose VMReg represents
2725 // the low-order word of the double and fpu_regnrLo + 1 is the
2726 // name for the other half. *first and *second must represent the
2727 // least and most significant words, respectively.
2729 #ifdef X86
2730 // the exact location of fpu stack values is only known
2731 // during fpu stack allocation, so the stack allocator object
2732 // must be present
2733 assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");
2734 assert(_fpu_stack_allocator != NULL, "must be present");
2735 opr = _fpu_stack_allocator->to_fpu_stack(opr);
2737 assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrLo is used)");
2738 #endif
2739 #ifdef SPARC
2740 assert(opr->fpu_regnrLo() == opr->fpu_regnrHi() + 1, "assumed in calculation (only fpu_regnrHi is used)");
2741 #endif
2742 #ifdef ARM
2743 assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)");
2744 #endif
2745 #ifdef PPC
2746 assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)");
2747 #endif
2749 #ifdef VM_LITTLE_ENDIAN
2750 VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrLo());
2751 #else
2752 VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi());
2753 #endif
2755 #ifdef _LP64
2756 first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
2757 second = _int_0_scope_value;
2758 #else
2759 first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
2760 // %%% This is probably a waste but we'll keep things as they were for now
2761 if (true) {
2762 VMReg rname_second = rname_first->next();
2763 second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
2764 }
2765 #endif
2767 } else {
2768 ShouldNotReachHere();
2769 first = NULL;
2770 second = NULL;
2771 }
2773 assert(first != NULL && second != NULL, "must be set");
2774 // The convention the interpreter uses is that the second local
2775 // holds the first raw word of the native double representation.
2776 // This is actually reasonable, since locals and stack arrays
2777 // grow downwards in all implementations.
2778 // (If, on some machine, the interpreter's Java locals or stack
2779 // were to grow upwards, the embedded doubles would be word-swapped.)
2780 scope_values->append(second);
2781 scope_values->append(first);
2782 return 2;
2783 }
2784 }
2787 int LinearScan::append_scope_value(int op_id, Value value, GrowableArray<ScopeValue*>* scope_values) {
2788 if (value != NULL) {
2789 LIR_Opr opr = value->operand();
2790 Constant* con = value->as_Constant();
2792 assert(con == NULL || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "asumption: Constant instructions have only constant operands (or illegal if constant is optimized away)");
2793 assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");
2795 if (con != NULL && !con->is_pinned() && !opr->is_constant()) {
2796 // Unpinned constants may have a virtual operand for a part of the lifetime
2797 // or may be illegal when it was optimized away,
2798 // so always use a constant operand
2799 opr = LIR_OprFact::value_type(con->type());
2800 }
2801 assert(opr->is_virtual() || opr->is_constant(), "other cases not allowed here");
2803 if (opr->is_virtual()) {
2804 LIR_OpVisitState::OprMode mode = LIR_OpVisitState::inputMode;
2806 BlockBegin* block = block_of_op_with_id(op_id);
2807 if (block->number_of_sux() == 1 && op_id == block->last_lir_instruction_id()) {
2808 // generating debug information for the last instruction of a block.
2809 // if this instruction is a branch, spill moves are inserted before this branch
2810 // and so the wrong operand would be returned (spill moves at block boundaries are not
2811 // considered in the live ranges of intervals)
2812 // Solution: use the first op_id of the branch target block instead.
2813 if (block->lir()->instructions_list()->last()->as_OpBranch() != NULL) {
2814 if (block->live_out().at(opr->vreg_number())) {
2815 op_id = block->sux_at(0)->first_lir_instruction_id();
2816 mode = LIR_OpVisitState::outputMode;
2817 }
2818 }
2819 }
2821 // Get current location of operand
2822 // The operand must be live because debug information is considered when building the intervals
2823 // if the interval is not live, color_lir_opr will cause an assertion failure
2824 opr = color_lir_opr(opr, op_id, mode);
2825 assert(!has_call(op_id) || opr->is_stack() || !is_caller_save(reg_num(opr)), "can not have caller-save register operands at calls");
2827 // Append to ScopeValue array
2828 return append_scope_value_for_operand(opr, scope_values);
2830 } else {
2831 assert(value->as_Constant() != NULL, "all other instructions have only virtual operands");
2832 assert(opr->is_constant(), "operand must be constant");
2834 return append_scope_value_for_constant(opr, scope_values);
2835 }
2836 } else {
2837 // append a dummy value because real value not needed
2838 scope_values->append(_illegal_value);
2839 return 1;
2840 }
2841 }
2844 IRScopeDebugInfo* LinearScan::compute_debug_info_for_scope(int op_id, IRScope* cur_scope, ValueStack* cur_state, ValueStack* innermost_state) {
2845 IRScopeDebugInfo* caller_debug_info = NULL;
2847 ValueStack* caller_state = cur_state->caller_state();
2848 if (caller_state != NULL) {
2849 // process recursively to compute outermost scope first
2850 caller_debug_info = compute_debug_info_for_scope(op_id, cur_scope->caller(), caller_state, innermost_state);
2851 }
2853 // initialize these to null.
2854 // If we don't need deopt info or there are no locals, expressions or monitors,
2855 // then these get recorded as no information and avoids the allocation of 0 length arrays.
2856 GrowableArray<ScopeValue*>* locals = NULL;
2857 GrowableArray<ScopeValue*>* expressions = NULL;
2858 GrowableArray<MonitorValue*>* monitors = NULL;
2860 // describe local variable values
2861 int nof_locals = cur_state->locals_size();
2862 if (nof_locals > 0) {
2863 locals = new GrowableArray<ScopeValue*>(nof_locals);
2865 int pos = 0;
2866 while (pos < nof_locals) {
2867 assert(pos < cur_state->locals_size(), "why not?");
2869 Value local = cur_state->local_at(pos);
2870 pos += append_scope_value(op_id, local, locals);
2872 assert(locals->length() == pos, "must match");
2873 }
2874 assert(locals->length() == cur_scope->method()->max_locals(), "wrong number of locals");
2875 assert(locals->length() == cur_state->locals_size(), "wrong number of locals");
2876 } else if (cur_scope->method()->max_locals() > 0) {
2877 assert(cur_state->kind() == ValueStack::EmptyExceptionState, "should be");
2878 nof_locals = cur_scope->method()->max_locals();
2879 locals = new GrowableArray<ScopeValue*>(nof_locals);
2880 for(int i = 0; i < nof_locals; i++) {
2881 locals->append(_illegal_value);
2882 }
2883 }
2885 // describe expression stack
2886 int nof_stack = cur_state->stack_size();
2887 if (nof_stack > 0) {
2888 expressions = new GrowableArray<ScopeValue*>(nof_stack);
2890 int pos = 0;
2891 while (pos < nof_stack) {
2892 Value expression = cur_state->stack_at_inc(pos);
2893 append_scope_value(op_id, expression, expressions);
2895 assert(expressions->length() == pos, "must match");
2896 }
2897 assert(expressions->length() == cur_state->stack_size(), "wrong number of stack entries");
2898 }
2900 // describe monitors
2901 int nof_locks = cur_state->locks_size();
2902 if (nof_locks > 0) {
2903 int lock_offset = cur_state->caller_state() != NULL ? cur_state->caller_state()->total_locks_size() : 0;
2904 monitors = new GrowableArray<MonitorValue*>(nof_locks);
2905 for (int i = 0; i < nof_locks; i++) {
2906 monitors->append(location_for_monitor_index(lock_offset + i));
2907 }
2908 }
2910 return new IRScopeDebugInfo(cur_scope, cur_state->bci(), locals, expressions, monitors, caller_debug_info);
2911 }
2914 void LinearScan::compute_debug_info(CodeEmitInfo* info, int op_id) {
2915 TRACE_LINEAR_SCAN(3, tty->print_cr("creating debug information at op_id %d", op_id));
2917 IRScope* innermost_scope = info->scope();
2918 ValueStack* innermost_state = info->stack();
2920 assert(innermost_scope != NULL && innermost_state != NULL, "why is it missing?");
2922 DEBUG_ONLY(check_stack_depth(info, innermost_state->stack_size()));
2924 if (info->_scope_debug_info == NULL) {
2925 // compute debug information
2926 info->_scope_debug_info = compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state);
2927 } else {
2928 // debug information already set. Check that it is correct from the current point of view
2929 DEBUG_ONLY(assert_equal(info->_scope_debug_info, compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state)));
2930 }
2931 }
2934 void LinearScan::assign_reg_num(LIR_OpList* instructions, IntervalWalker* iw) {
2935 LIR_OpVisitState visitor;
2936 int num_inst = instructions->length();
2937 bool has_dead = false;
2939 for (int j = 0; j < num_inst; j++) {
2940 LIR_Op* op = instructions->at(j);
2941 if (op == NULL) { // this can happen when spill-moves are removed in eliminate_spill_moves
2942 has_dead = true;
2943 continue;
2944 }
2945 int op_id = op->id();
2947 // visit instruction to get list of operands
2948 visitor.visit(op);
2950 // iterate all modes of the visitor and process all virtual operands
2951 for_each_visitor_mode(mode) {
2952 int n = visitor.opr_count(mode);
2953 for (int k = 0; k < n; k++) {
2954 LIR_Opr opr = visitor.opr_at(mode, k);
2955 if (opr->is_virtual_register()) {
2956 visitor.set_opr_at(mode, k, color_lir_opr(opr, op_id, mode));
2957 }
2958 }
2959 }
2961 if (visitor.info_count() > 0) {
2962 // exception handling
2963 if (compilation()->has_exception_handlers()) {
2964 XHandlers* xhandlers = visitor.all_xhandler();
2965 int n = xhandlers->length();
2966 for (int k = 0; k < n; k++) {
2967 XHandler* handler = xhandlers->handler_at(k);
2968 if (handler->entry_code() != NULL) {
2969 assign_reg_num(handler->entry_code()->instructions_list(), NULL);
2970 }
2971 }
2972 } else {
2973 assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
2974 }
2976 // compute oop map
2977 assert(iw != NULL, "needed for compute_oop_map");
2978 compute_oop_map(iw, visitor, op);
2980 // compute debug information
2981 if (!use_fpu_stack_allocation()) {
2982 // compute debug information if fpu stack allocation is not needed.
2983 // when fpu stack allocation is needed, the debug information can not
2984 // be computed here because the exact location of fpu operands is not known
2985 // -> debug information is created inside the fpu stack allocator
2986 int n = visitor.info_count();
2987 for (int k = 0; k < n; k++) {
2988 compute_debug_info(visitor.info_at(k), op_id);
2989 }
2990 }
2991 }
2993 #ifdef ASSERT
2994 // make sure we haven't made the op invalid.
2995 op->verify();
2996 #endif
2998 // remove useless moves
2999 if (op->code() == lir_move) {
3000 assert(op->as_Op1() != NULL, "move must be LIR_Op1");
3001 LIR_Op1* move = (LIR_Op1*)op;
3002 LIR_Opr src = move->in_opr();
3003 LIR_Opr dst = move->result_opr();
3004 if (dst == src ||
3005 !dst->is_pointer() && !src->is_pointer() &&
3006 src->is_same_register(dst)) {
3007 instructions->at_put(j, NULL);
3008 has_dead = true;
3009 }
3010 }
3011 }
3013 if (has_dead) {
3014 // iterate all instructions of the block and remove all null-values.
3015 int insert_point = 0;
3016 for (int j = 0; j < num_inst; j++) {
3017 LIR_Op* op = instructions->at(j);
3018 if (op != NULL) {
3019 if (insert_point != j) {
3020 instructions->at_put(insert_point, op);
3021 }
3022 insert_point++;
3023 }
3024 }
3025 instructions->truncate(insert_point);
3026 }
3027 }
3029 void LinearScan::assign_reg_num() {
3030 TIME_LINEAR_SCAN(timer_assign_reg_num);
3032 init_compute_debug_info();
3033 IntervalWalker* iw = init_compute_oop_maps();
3035 int num_blocks = block_count();
3036 for (int i = 0; i < num_blocks; i++) {
3037 BlockBegin* block = block_at(i);
3038 assign_reg_num(block->lir()->instructions_list(), iw);
3039 }
3040 }
3043 void LinearScan::do_linear_scan() {
3044 NOT_PRODUCT(_total_timer.begin_method());
3046 number_instructions();
3048 NOT_PRODUCT(print_lir(1, "Before Register Allocation"));
3050 compute_local_live_sets();
3051 compute_global_live_sets();
3052 CHECK_BAILOUT();
3054 build_intervals();
3055 CHECK_BAILOUT();
3056 sort_intervals_before_allocation();
3058 NOT_PRODUCT(print_intervals("Before Register Allocation"));
3059 NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_before_alloc));
3061 allocate_registers();
3062 CHECK_BAILOUT();
3064 resolve_data_flow();
3065 if (compilation()->has_exception_handlers()) {
3066 resolve_exception_handlers();
3067 }
3068 // fill in number of spill slots into frame_map
3069 propagate_spill_slots();
3070 CHECK_BAILOUT();
3072 NOT_PRODUCT(print_intervals("After Register Allocation"));
3073 NOT_PRODUCT(print_lir(2, "LIR after register allocation:"));
3075 sort_intervals_after_allocation();
3077 DEBUG_ONLY(verify());
3079 eliminate_spill_moves();
3080 assign_reg_num();
3081 CHECK_BAILOUT();
3083 NOT_PRODUCT(print_lir(2, "LIR after assignment of register numbers:"));
3084 NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_after_asign));
3086 { TIME_LINEAR_SCAN(timer_allocate_fpu_stack);
3088 if (use_fpu_stack_allocation()) {
3089 allocate_fpu_stack(); // Only has effect on Intel
3090 NOT_PRODUCT(print_lir(2, "LIR after FPU stack allocation:"));
3091 }
3092 }
3094 { TIME_LINEAR_SCAN(timer_optimize_lir);
3096 EdgeMoveOptimizer::optimize(ir()->code());
3097 ControlFlowOptimizer::optimize(ir()->code());
3098 // check that cfg is still correct after optimizations
3099 ir()->verify();
3100 }
3102 NOT_PRODUCT(print_lir(1, "Before Code Generation", false));
3103 NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_final));
3104 NOT_PRODUCT(_total_timer.end_method(this));
3105 }
3108 // ********** Printing functions
3110 #ifndef PRODUCT
3112 void LinearScan::print_timers(double total) {
3113 _total_timer.print(total);
3114 }
3116 void LinearScan::print_statistics() {
3117 _stat_before_alloc.print("before allocation");
3118 _stat_after_asign.print("after assignment of register");
3119 _stat_final.print("after optimization");
3120 }
3122 void LinearScan::print_bitmap(BitMap& b) {
3123 for (unsigned int i = 0; i < b.size(); i++) {
3124 if (b.at(i)) tty->print("%d ", i);
3125 }
3126 tty->cr();
3127 }
3129 void LinearScan::print_intervals(const char* label) {
3130 if (TraceLinearScanLevel >= 1) {
3131 int i;
3132 tty->cr();
3133 tty->print_cr("%s", label);
3135 for (i = 0; i < interval_count(); i++) {
3136 Interval* interval = interval_at(i);
3137 if (interval != NULL) {
3138 interval->print();
3139 }
3140 }
3142 tty->cr();
3143 tty->print_cr("--- Basic Blocks ---");
3144 for (i = 0; i < block_count(); i++) {
3145 BlockBegin* block = block_at(i);
3146 tty->print("B%d [%d, %d, %d, %d] ", block->block_id(), block->first_lir_instruction_id(), block->last_lir_instruction_id(), block->loop_index(), block->loop_depth());
3147 }
3148 tty->cr();
3149 tty->cr();
3150 }
3152 if (PrintCFGToFile) {
3153 CFGPrinter::print_intervals(&_intervals, label);
3154 }
3155 }
3157 void LinearScan::print_lir(int level, const char* label, bool hir_valid) {
3158 if (TraceLinearScanLevel >= level) {
3159 tty->cr();
3160 tty->print_cr("%s", label);
3161 print_LIR(ir()->linear_scan_order());
3162 tty->cr();
3163 }
3165 if (level == 1 && PrintCFGToFile) {
3166 CFGPrinter::print_cfg(ir()->linear_scan_order(), label, hir_valid, true);
3167 }
3168 }
3170 #endif //PRODUCT
3173 // ********** verification functions for allocation
3174 // (check that all intervals have a correct register and that no registers are overwritten)
3175 #ifdef ASSERT
3177 void LinearScan::verify() {
3178 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying intervals ******************************************"));
3179 verify_intervals();
3181 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that no oops are in fixed intervals ****************"));
3182 verify_no_oops_in_fixed_intervals();
3184 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that unpinned constants are not alive across block boundaries"));
3185 verify_constants();
3187 TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying register allocation ********************************"));
3188 verify_registers();
3190 TRACE_LINEAR_SCAN(2, tty->print_cr("********* no errors found **********************************************"));
3191 }
3193 void LinearScan::verify_intervals() {
3194 int len = interval_count();
3195 bool has_error = false;
3197 for (int i = 0; i < len; i++) {
3198 Interval* i1 = interval_at(i);
3199 if (i1 == NULL) continue;
3201 i1->check_split_children();
3203 if (i1->reg_num() != i) {
3204 tty->print_cr("Interval %d is on position %d in list", i1->reg_num(), i); i1->print(); tty->cr();
3205 has_error = true;
3206 }
3208 if (i1->reg_num() >= LIR_OprDesc::vreg_base && i1->type() == T_ILLEGAL) {
3209 tty->print_cr("Interval %d has no type assigned", i1->reg_num()); i1->print(); tty->cr();
3210 has_error = true;
3211 }
3213 if (i1->assigned_reg() == any_reg) {
3214 tty->print_cr("Interval %d has no register assigned", i1->reg_num()); i1->print(); tty->cr();
3215 has_error = true;
3216 }
3218 if (i1->assigned_reg() == i1->assigned_regHi()) {
3219 tty->print_cr("Interval %d: low and high register equal", i1->reg_num()); i1->print(); tty->cr();
3220 has_error = true;
3221 }
3223 if (!is_processed_reg_num(i1->assigned_reg())) {
3224 tty->print_cr("Can not have an Interval for an ignored register"); i1->print(); tty->cr();
3225 has_error = true;
3226 }
3228 if (i1->first() == Range::end()) {
3229 tty->print_cr("Interval %d has no Range", i1->reg_num()); i1->print(); tty->cr();
3230 has_error = true;
3231 }
3233 for (Range* r = i1->first(); r != Range::end(); r = r->next()) {
3234 if (r->from() >= r->to()) {
3235 tty->print_cr("Interval %d has zero length range", i1->reg_num()); i1->print(); tty->cr();
3236 has_error = true;
3237 }
3238 }
3240 for (int j = i + 1; j < len; j++) {
3241 Interval* i2 = interval_at(j);
3242 if (i2 == NULL) continue;
3244 // special intervals that are created in MoveResolver
3245 // -> ignore them because the range information has no meaning there
3246 if (i1->from() == 1 && i1->to() == 2) continue;
3247 if (i2->from() == 1 && i2->to() == 2) continue;
3249 int r1 = i1->assigned_reg();
3250 int r1Hi = i1->assigned_regHi();
3251 int r2 = i2->assigned_reg();
3252 int r2Hi = i2->assigned_regHi();
3253 if (i1->intersects(i2) && (r1 == r2 || r1 == r2Hi || (r1Hi != any_reg && (r1Hi == r2 || r1Hi == r2Hi)))) {
3254 tty->print_cr("Intervals %d and %d overlap and have the same register assigned", i1->reg_num(), i2->reg_num());
3255 i1->print(); tty->cr();
3256 i2->print(); tty->cr();
3257 has_error = true;
3258 }
3259 }
3260 }
3262 assert(has_error == false, "register allocation invalid");
3263 }
3266 void LinearScan::verify_no_oops_in_fixed_intervals() {
3267 Interval* fixed_intervals;
3268 Interval* other_intervals;
3269 create_unhandled_lists(&fixed_intervals, &other_intervals, is_precolored_cpu_interval, NULL);
3271 // to ensure a walking until the last instruction id, add a dummy interval
3272 // with a high operation id
3273 other_intervals = new Interval(any_reg);
3274 other_intervals->add_range(max_jint - 2, max_jint - 1);
3275 IntervalWalker* iw = new IntervalWalker(this, fixed_intervals, other_intervals);
3277 LIR_OpVisitState visitor;
3278 for (int i = 0; i < block_count(); i++) {
3279 BlockBegin* block = block_at(i);
3281 LIR_OpList* instructions = block->lir()->instructions_list();
3283 for (int j = 0; j < instructions->length(); j++) {
3284 LIR_Op* op = instructions->at(j);
3285 int op_id = op->id();
3287 visitor.visit(op);
3289 if (visitor.info_count() > 0) {
3290 iw->walk_before(op->id());
3291 bool check_live = true;
3292 if (op->code() == lir_move) {
3293 LIR_Op1* move = (LIR_Op1*)op;
3294 check_live = (move->patch_code() == lir_patch_none);
3295 }
3296 LIR_OpBranch* branch = op->as_OpBranch();
3297 if (branch != NULL && branch->stub() != NULL && branch->stub()->is_exception_throw_stub()) {
3298 // Don't bother checking the stub in this case since the
3299 // exception stub will never return to normal control flow.
3300 check_live = false;
3301 }
3303 // Make sure none of the fixed registers is live across an
3304 // oopmap since we can't handle that correctly.
3305 if (check_live) {
3306 for (Interval* interval = iw->active_first(fixedKind);
3307 interval != Interval::end();
3308 interval = interval->next()) {
3309 if (interval->current_to() > op->id() + 1) {
3310 // This interval is live out of this op so make sure
3311 // that this interval represents some value that's
3312 // referenced by this op either as an input or output.
3313 bool ok = false;
3314 for_each_visitor_mode(mode) {
3315 int n = visitor.opr_count(mode);
3316 for (int k = 0; k < n; k++) {
3317 LIR_Opr opr = visitor.opr_at(mode, k);
3318 if (opr->is_fixed_cpu()) {
3319 if (interval_at(reg_num(opr)) == interval) {
3320 ok = true;
3321 break;
3322 }
3323 int hi = reg_numHi(opr);
3324 if (hi != -1 && interval_at(hi) == interval) {
3325 ok = true;
3326 break;
3327 }
3328 }
3329 }
3330 }
3331 assert(ok, "fixed intervals should never be live across an oopmap point");
3332 }
3333 }
3334 }
3335 }
3337 // oop-maps at calls do not contain registers, so check is not needed
3338 if (!visitor.has_call()) {
3340 for_each_visitor_mode(mode) {
3341 int n = visitor.opr_count(mode);
3342 for (int k = 0; k < n; k++) {
3343 LIR_Opr opr = visitor.opr_at(mode, k);
3345 if (opr->is_fixed_cpu() && opr->is_oop()) {
3346 // operand is a non-virtual cpu register and contains an oop
3347 TRACE_LINEAR_SCAN(4, op->print_on(tty); tty->print("checking operand "); opr->print(); tty->cr());
3349 Interval* interval = interval_at(reg_num(opr));
3350 assert(interval != NULL, "no interval");
3352 if (mode == LIR_OpVisitState::inputMode) {
3353 if (interval->to() >= op_id + 1) {
3354 assert(interval->to() < op_id + 2 ||
3355 interval->has_hole_between(op_id, op_id + 2),
3356 "oop input operand live after instruction");
3357 }
3358 } else if (mode == LIR_OpVisitState::outputMode) {
3359 if (interval->from() <= op_id - 1) {
3360 assert(interval->has_hole_between(op_id - 1, op_id),
3361 "oop input operand live after instruction");
3362 }
3363 }
3364 }
3365 }
3366 }
3367 }
3368 }
3369 }
3370 }
3373 void LinearScan::verify_constants() {
3374 int num_regs = num_virtual_regs();
3375 int size = live_set_size();
3376 int num_blocks = block_count();
3378 for (int i = 0; i < num_blocks; i++) {
3379 BlockBegin* block = block_at(i);
3380 BitMap live_at_edge = block->live_in();
3382 // visit all registers where the live_at_edge bit is set
3383 for (int r = (int)live_at_edge.get_next_one_offset(0, size); r < size; r = (int)live_at_edge.get_next_one_offset(r + 1, size)) {
3384 TRACE_LINEAR_SCAN(4, tty->print("checking interval %d of block B%d", r, block->block_id()));
3386 Value value = gen()->instruction_for_vreg(r);
3388 assert(value != NULL, "all intervals live across block boundaries must have Value");
3389 assert(value->operand()->is_register() && value->operand()->is_virtual(), "value must have virtual operand");
3390 assert(value->operand()->vreg_number() == r, "register number must match");
3391 // TKR assert(value->as_Constant() == NULL || value->is_pinned(), "only pinned constants can be alive accross block boundaries");
3392 }
3393 }
3394 }
3397 class RegisterVerifier: public StackObj {
3398 private:
3399 LinearScan* _allocator;
3400 BlockList _work_list; // all blocks that must be processed
3401 IntervalsList _saved_states; // saved information of previous check
3403 // simplified access to methods of LinearScan
3404 Compilation* compilation() const { return _allocator->compilation(); }
3405 Interval* interval_at(int reg_num) const { return _allocator->interval_at(reg_num); }
3406 int reg_num(LIR_Opr opr) const { return _allocator->reg_num(opr); }
3408 // currently, only registers are processed
3409 int state_size() { return LinearScan::nof_regs; }
3411 // accessors
3412 IntervalList* state_for_block(BlockBegin* block) { return _saved_states.at(block->block_id()); }
3413 void set_state_for_block(BlockBegin* block, IntervalList* saved_state) { _saved_states.at_put(block->block_id(), saved_state); }
3414 void add_to_work_list(BlockBegin* block) { if (!_work_list.contains(block)) _work_list.append(block); }
3416 // helper functions
3417 IntervalList* copy(IntervalList* input_state);
3418 void state_put(IntervalList* input_state, int reg, Interval* interval);
3419 bool check_state(IntervalList* input_state, int reg, Interval* interval);
3421 void process_block(BlockBegin* block);
3422 void process_xhandler(XHandler* xhandler, IntervalList* input_state);
3423 void process_successor(BlockBegin* block, IntervalList* input_state);
3424 void process_operations(LIR_List* ops, IntervalList* input_state);
3426 public:
3427 RegisterVerifier(LinearScan* allocator)
3428 : _allocator(allocator)
3429 , _work_list(16)
3430 , _saved_states(BlockBegin::number_of_blocks(), NULL)
3431 { }
3433 void verify(BlockBegin* start);
3434 };
3437 // entry function from LinearScan that starts the verification
3438 void LinearScan::verify_registers() {
3439 RegisterVerifier verifier(this);
3440 verifier.verify(block_at(0));
3441 }
3444 void RegisterVerifier::verify(BlockBegin* start) {
3445 // setup input registers (method arguments) for first block
3446 IntervalList* input_state = new IntervalList(state_size(), NULL);
3447 CallingConvention* args = compilation()->frame_map()->incoming_arguments();
3448 for (int n = 0; n < args->length(); n++) {
3449 LIR_Opr opr = args->at(n);
3450 if (opr->is_register()) {
3451 Interval* interval = interval_at(reg_num(opr));
3453 if (interval->assigned_reg() < state_size()) {
3454 input_state->at_put(interval->assigned_reg(), interval);
3455 }
3456 if (interval->assigned_regHi() != LinearScan::any_reg && interval->assigned_regHi() < state_size()) {
3457 input_state->at_put(interval->assigned_regHi(), interval);
3458 }
3459 }
3460 }
3462 set_state_for_block(start, input_state);
3463 add_to_work_list(start);
3465 // main loop for verification
3466 do {
3467 BlockBegin* block = _work_list.at(0);
3468 _work_list.remove_at(0);
3470 process_block(block);
3471 } while (!_work_list.is_empty());
3472 }
3474 void RegisterVerifier::process_block(BlockBegin* block) {
3475 TRACE_LINEAR_SCAN(2, tty->cr(); tty->print_cr("process_block B%d", block->block_id()));
3477 // must copy state because it is modified
3478 IntervalList* input_state = copy(state_for_block(block));
3480 if (TraceLinearScanLevel >= 4) {
3481 tty->print_cr("Input-State of intervals:");
3482 tty->print(" ");
3483 for (int i = 0; i < state_size(); i++) {
3484 if (input_state->at(i) != NULL) {
3485 tty->print(" %4d", input_state->at(i)->reg_num());
3486 } else {
3487 tty->print(" __");
3488 }
3489 }
3490 tty->cr();
3491 tty->cr();
3492 }
3494 // process all operations of the block
3495 process_operations(block->lir(), input_state);
3497 // iterate all successors
3498 for (int i = 0; i < block->number_of_sux(); i++) {
3499 process_successor(block->sux_at(i), input_state);
3500 }
3501 }
3503 void RegisterVerifier::process_xhandler(XHandler* xhandler, IntervalList* input_state) {
3504 TRACE_LINEAR_SCAN(2, tty->print_cr("process_xhandler B%d", xhandler->entry_block()->block_id()));
3506 // must copy state because it is modified
3507 input_state = copy(input_state);
3509 if (xhandler->entry_code() != NULL) {
3510 process_operations(xhandler->entry_code(), input_state);
3511 }
3512 process_successor(xhandler->entry_block(), input_state);
3513 }
3515 void RegisterVerifier::process_successor(BlockBegin* block, IntervalList* input_state) {
3516 IntervalList* saved_state = state_for_block(block);
3518 if (saved_state != NULL) {
3519 // this block was already processed before.
3520 // check if new input_state is consistent with saved_state
3522 bool saved_state_correct = true;
3523 for (int i = 0; i < state_size(); i++) {
3524 if (input_state->at(i) != saved_state->at(i)) {
3525 // current input_state and previous saved_state assume a different
3526 // interval in this register -> assume that this register is invalid
3527 if (saved_state->at(i) != NULL) {
3528 // invalidate old calculation only if it assumed that
3529 // register was valid. when the register was already invalid,
3530 // then the old calculation was correct.
3531 saved_state_correct = false;
3532 saved_state->at_put(i, NULL);
3534 TRACE_LINEAR_SCAN(4, tty->print_cr("process_successor B%d: invalidating slot %d", block->block_id(), i));
3535 }
3536 }
3537 }
3539 if (saved_state_correct) {
3540 // already processed block with correct input_state
3541 TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: previous visit already correct", block->block_id()));
3542 } else {
3543 // must re-visit this block
3544 TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: must re-visit because input state changed", block->block_id()));
3545 add_to_work_list(block);
3546 }
3548 } else {
3549 // block was not processed before, so set initial input_state
3550 TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: initial visit", block->block_id()));
3552 set_state_for_block(block, copy(input_state));
3553 add_to_work_list(block);
3554 }
3555 }
3558 IntervalList* RegisterVerifier::copy(IntervalList* input_state) {
3559 IntervalList* copy_state = new IntervalList(input_state->length());
3560 copy_state->push_all(input_state);
3561 return copy_state;
3562 }
3564 void RegisterVerifier::state_put(IntervalList* input_state, int reg, Interval* interval) {
3565 if (reg != LinearScan::any_reg && reg < state_size()) {
3566 if (interval != NULL) {
3567 TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = %d", reg, interval->reg_num()));
3568 } else if (input_state->at(reg) != NULL) {
3569 TRACE_LINEAR_SCAN(4, tty->print_cr(" reg[%d] = NULL", reg));
3570 }
3572 input_state->at_put(reg, interval);
3573 }
3574 }
3576 bool RegisterVerifier::check_state(IntervalList* input_state, int reg, Interval* interval) {
3577 if (reg != LinearScan::any_reg && reg < state_size()) {
3578 if (input_state->at(reg) != interval) {
3579 tty->print_cr("!! Error in register allocation: register %d does not contain interval %d", reg, interval->reg_num());
3580 return true;
3581 }
3582 }
3583 return false;
3584 }
3586 void RegisterVerifier::process_operations(LIR_List* ops, IntervalList* input_state) {
3587 // visit all instructions of the block
3588 LIR_OpVisitState visitor;
3589 bool has_error = false;
3591 for (int i = 0; i < ops->length(); i++) {
3592 LIR_Op* op = ops->at(i);
3593 visitor.visit(op);
3595 TRACE_LINEAR_SCAN(4, op->print_on(tty));
3597 // check if input operands are correct
3598 int j;
3599 int n = visitor.opr_count(LIR_OpVisitState::inputMode);
3600 for (j = 0; j < n; j++) {
3601 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, j);
3602 if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
3603 Interval* interval = interval_at(reg_num(opr));
3604 if (op->id() != -1) {
3605 interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::inputMode);
3606 }
3608 has_error |= check_state(input_state, interval->assigned_reg(), interval->split_parent());
3609 has_error |= check_state(input_state, interval->assigned_regHi(), interval->split_parent());
3611 // When an operand is marked with is_last_use, then the fpu stack allocator
3612 // removes the register from the fpu stack -> the register contains no value
3613 if (opr->is_last_use()) {
3614 state_put(input_state, interval->assigned_reg(), NULL);
3615 state_put(input_state, interval->assigned_regHi(), NULL);
3616 }
3617 }
3618 }
3620 // invalidate all caller save registers at calls
3621 if (visitor.has_call()) {
3622 for (j = 0; j < FrameMap::nof_caller_save_cpu_regs(); j++) {
3623 state_put(input_state, reg_num(FrameMap::caller_save_cpu_reg_at(j)), NULL);
3624 }
3625 for (j = 0; j < FrameMap::nof_caller_save_fpu_regs; j++) {
3626 state_put(input_state, reg_num(FrameMap::caller_save_fpu_reg_at(j)), NULL);
3627 }
3629 #ifdef X86
3630 for (j = 0; j < FrameMap::nof_caller_save_xmm_regs; j++) {
3631 state_put(input_state, reg_num(FrameMap::caller_save_xmm_reg_at(j)), NULL);
3632 }
3633 #endif
3634 }
3636 // process xhandler before output and temp operands
3637 XHandlers* xhandlers = visitor.all_xhandler();
3638 n = xhandlers->length();
3639 for (int k = 0; k < n; k++) {
3640 process_xhandler(xhandlers->handler_at(k), input_state);
3641 }
3643 // set temp operands (some operations use temp operands also as output operands, so can't set them NULL)
3644 n = visitor.opr_count(LIR_OpVisitState::tempMode);
3645 for (j = 0; j < n; j++) {
3646 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, j);
3647 if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
3648 Interval* interval = interval_at(reg_num(opr));
3649 if (op->id() != -1) {
3650 interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::tempMode);
3651 }
3653 state_put(input_state, interval->assigned_reg(), interval->split_parent());
3654 state_put(input_state, interval->assigned_regHi(), interval->split_parent());
3655 }
3656 }
3658 // set output operands
3659 n = visitor.opr_count(LIR_OpVisitState::outputMode);
3660 for (j = 0; j < n; j++) {
3661 LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, j);
3662 if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
3663 Interval* interval = interval_at(reg_num(opr));
3664 if (op->id() != -1) {
3665 interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::outputMode);
3666 }
3668 state_put(input_state, interval->assigned_reg(), interval->split_parent());
3669 state_put(input_state, interval->assigned_regHi(), interval->split_parent());
3670 }
3671 }
3672 }
3673 assert(has_error == false, "Error in register allocation");
3674 }
3676 #endif // ASSERT
3680 // **** Implementation of MoveResolver ******************************
3682 MoveResolver::MoveResolver(LinearScan* allocator) :
3683 _allocator(allocator),
3684 _multiple_reads_allowed(false),
3685 _mapping_from(8),
3686 _mapping_from_opr(8),
3687 _mapping_to(8),
3688 _insert_list(NULL),
3689 _insert_idx(-1),
3690 _insertion_buffer()
3691 {
3692 for (int i = 0; i < LinearScan::nof_regs; i++) {
3693 _register_blocked[i] = 0;
3694 }
3695 DEBUG_ONLY(check_empty());
3696 }
3699 #ifdef ASSERT
3701 void MoveResolver::check_empty() {
3702 assert(_mapping_from.length() == 0 && _mapping_from_opr.length() == 0 && _mapping_to.length() == 0, "list must be empty before and after processing");
3703 for (int i = 0; i < LinearScan::nof_regs; i++) {
3704 assert(register_blocked(i) == 0, "register map must be empty before and after processing");
3705 }
3706 assert(_multiple_reads_allowed == false, "must have default value");
3707 }
3709 void MoveResolver::verify_before_resolve() {
3710 assert(_mapping_from.length() == _mapping_from_opr.length(), "length must be equal");
3711 assert(_mapping_from.length() == _mapping_to.length(), "length must be equal");
3712 assert(_insert_list != NULL && _insert_idx != -1, "insert position not set");
3714 int i, j;
3715 if (!_multiple_reads_allowed) {
3716 for (i = 0; i < _mapping_from.length(); i++) {
3717 for (j = i + 1; j < _mapping_from.length(); j++) {
3718 assert(_mapping_from.at(i) == NULL || _mapping_from.at(i) != _mapping_from.at(j), "cannot read from same interval twice");
3719 }
3720 }
3721 }
3723 for (i = 0; i < _mapping_to.length(); i++) {
3724 for (j = i + 1; j < _mapping_to.length(); j++) {
3725 assert(_mapping_to.at(i) != _mapping_to.at(j), "cannot write to same interval twice");
3726 }
3727 }
3730 BitMap used_regs(LinearScan::nof_regs + allocator()->frame_map()->argcount() + allocator()->max_spills());
3731 used_regs.clear();
3732 if (!_multiple_reads_allowed) {
3733 for (i = 0; i < _mapping_from.length(); i++) {
3734 Interval* it = _mapping_from.at(i);
3735 if (it != NULL) {
3736 assert(!used_regs.at(it->assigned_reg()), "cannot read from same register twice");
3737 used_regs.set_bit(it->assigned_reg());
3739 if (it->assigned_regHi() != LinearScan::any_reg) {
3740 assert(!used_regs.at(it->assigned_regHi()), "cannot read from same register twice");
3741 used_regs.set_bit(it->assigned_regHi());
3742 }
3743 }
3744 }
3745 }
3747 used_regs.clear();
3748 for (i = 0; i < _mapping_to.length(); i++) {
3749 Interval* it = _mapping_to.at(i);
3750 assert(!used_regs.at(it->assigned_reg()), "cannot write to same register twice");
3751 used_regs.set_bit(it->assigned_reg());
3753 if (it->assigned_regHi() != LinearScan::any_reg) {
3754 assert(!used_regs.at(it->assigned_regHi()), "cannot write to same register twice");
3755 used_regs.set_bit(it->assigned_regHi());
3756 }
3757 }
3759 used_regs.clear();
3760 for (i = 0; i < _mapping_from.length(); i++) {
3761 Interval* it = _mapping_from.at(i);
3762 if (it != NULL && it->assigned_reg() >= LinearScan::nof_regs) {
3763 used_regs.set_bit(it->assigned_reg());
3764 }
3765 }
3766 for (i = 0; i < _mapping_to.length(); i++) {
3767 Interval* it = _mapping_to.at(i);
3768 assert(!used_regs.at(it->assigned_reg()) || it->assigned_reg() == _mapping_from.at(i)->assigned_reg(), "stack slots used in _mapping_from must be disjoint to _mapping_to");
3769 }
3770 }
3772 #endif // ASSERT
3775 // mark assigned_reg and assigned_regHi of the interval as blocked
3776 void MoveResolver::block_registers(Interval* it) {
3777 int reg = it->assigned_reg();
3778 if (reg < LinearScan::nof_regs) {
3779 assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
3780 set_register_blocked(reg, 1);
3781 }
3782 reg = it->assigned_regHi();
3783 if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
3784 assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
3785 set_register_blocked(reg, 1);
3786 }
3787 }
3789 // mark assigned_reg and assigned_regHi of the interval as unblocked
3790 void MoveResolver::unblock_registers(Interval* it) {
3791 int reg = it->assigned_reg();
3792 if (reg < LinearScan::nof_regs) {
3793 assert(register_blocked(reg) > 0, "register already marked as unused");
3794 set_register_blocked(reg, -1);
3795 }
3796 reg = it->assigned_regHi();
3797 if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
3798 assert(register_blocked(reg) > 0, "register already marked as unused");
3799 set_register_blocked(reg, -1);
3800 }
3801 }
3803 // check if assigned_reg and assigned_regHi of the to-interval are not blocked (or only blocked by from)
3804 bool MoveResolver::save_to_process_move(Interval* from, Interval* to) {
3805 int from_reg = -1;
3806 int from_regHi = -1;
3807 if (from != NULL) {
3808 from_reg = from->assigned_reg();
3809 from_regHi = from->assigned_regHi();
3810 }
3812 int reg = to->assigned_reg();
3813 if (reg < LinearScan::nof_regs) {
3814 if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
3815 return false;
3816 }
3817 }
3818 reg = to->assigned_regHi();
3819 if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
3820 if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
3821 return false;
3822 }
3823 }
3825 return true;
3826 }
3829 void MoveResolver::create_insertion_buffer(LIR_List* list) {
3830 assert(!_insertion_buffer.initialized(), "overwriting existing buffer");
3831 _insertion_buffer.init(list);
3832 }
3834 void MoveResolver::append_insertion_buffer() {
3835 if (_insertion_buffer.initialized()) {
3836 _insertion_buffer.lir_list()->append(&_insertion_buffer);
3837 }
3838 assert(!_insertion_buffer.initialized(), "must be uninitialized now");
3840 _insert_list = NULL;
3841 _insert_idx = -1;
3842 }
3844 void MoveResolver::insert_move(Interval* from_interval, Interval* to_interval) {
3845 assert(from_interval->reg_num() != to_interval->reg_num(), "from and to interval equal");
3846 assert(from_interval->type() == to_interval->type(), "move between different types");
3847 assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");
3848 assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
3850 LIR_Opr from_opr = LIR_OprFact::virtual_register(from_interval->reg_num(), from_interval->type());
3851 LIR_Opr to_opr = LIR_OprFact::virtual_register(to_interval->reg_num(), to_interval->type());
3853 if (!_multiple_reads_allowed) {
3854 // the last_use flag is an optimization for FPU stack allocation. When the same
3855 // input interval is used in more than one move, then it is too difficult to determine
3856 // if this move is really the last use.
3857 from_opr = from_opr->make_last_use();
3858 }
3859 _insertion_buffer.move(_insert_idx, from_opr, to_opr);
3861 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: inserted move from register %d (%d, %d) to %d (%d, %d)", from_interval->reg_num(), from_interval->assigned_reg(), from_interval->assigned_regHi(), to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
3862 }
3864 void MoveResolver::insert_move(LIR_Opr from_opr, Interval* to_interval) {
3865 assert(from_opr->type() == to_interval->type(), "move between different types");
3866 assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");
3867 assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
3869 LIR_Opr to_opr = LIR_OprFact::virtual_register(to_interval->reg_num(), to_interval->type());
3870 _insertion_buffer.move(_insert_idx, from_opr, to_opr);
3872 TRACE_LINEAR_SCAN(4, tty->print("MoveResolver: inserted move from constant "); from_opr->print(); tty->print_cr(" to %d (%d, %d)", to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
3873 }
3876 void MoveResolver::resolve_mappings() {
3877 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: resolving mappings for Block B%d, index %d", _insert_list->block() != NULL ? _insert_list->block()->block_id() : -1, _insert_idx));
3878 DEBUG_ONLY(verify_before_resolve());
3880 // Block all registers that are used as input operands of a move.
3881 // When a register is blocked, no move to this register is emitted.
3882 // This is necessary for detecting cycles in moves.
3883 int i;
3884 for (i = _mapping_from.length() - 1; i >= 0; i--) {
3885 Interval* from_interval = _mapping_from.at(i);
3886 if (from_interval != NULL) {
3887 block_registers(from_interval);
3888 }
3889 }
3891 int spill_candidate = -1;
3892 while (_mapping_from.length() > 0) {
3893 bool processed_interval = false;
3895 for (i = _mapping_from.length() - 1; i >= 0; i--) {
3896 Interval* from_interval = _mapping_from.at(i);
3897 Interval* to_interval = _mapping_to.at(i);
3899 if (save_to_process_move(from_interval, to_interval)) {
3900 // this inverval can be processed because target is free
3901 if (from_interval != NULL) {
3902 insert_move(from_interval, to_interval);
3903 unblock_registers(from_interval);
3904 } else {
3905 insert_move(_mapping_from_opr.at(i), to_interval);
3906 }
3907 _mapping_from.remove_at(i);
3908 _mapping_from_opr.remove_at(i);
3909 _mapping_to.remove_at(i);
3911 processed_interval = true;
3912 } else if (from_interval != NULL && from_interval->assigned_reg() < LinearScan::nof_regs) {
3913 // this interval cannot be processed now because target is not free
3914 // it starts in a register, so it is a possible candidate for spilling
3915 spill_candidate = i;
3916 }
3917 }
3919 if (!processed_interval) {
3920 // no move could be processed because there is a cycle in the move list
3921 // (e.g. r1 -> r2, r2 -> r1), so one interval must be spilled to memory
3922 assert(spill_candidate != -1, "no interval in register for spilling found");
3924 // create a new spill interval and assign a stack slot to it
3925 Interval* from_interval = _mapping_from.at(spill_candidate);
3926 Interval* spill_interval = new Interval(-1);
3927 spill_interval->set_type(from_interval->type());
3929 // add a dummy range because real position is difficult to calculate
3930 // Note: this range is a special case when the integrity of the allocation is checked
3931 spill_interval->add_range(1, 2);
3933 // do not allocate a new spill slot for temporary interval, but
3934 // use spill slot assigned to from_interval. Otherwise moves from
3935 // one stack slot to another can happen (not allowed by LIR_Assembler
3936 int spill_slot = from_interval->canonical_spill_slot();
3937 if (spill_slot < 0) {
3938 spill_slot = allocator()->allocate_spill_slot(type2spill_size[spill_interval->type()] == 2);
3939 from_interval->set_canonical_spill_slot(spill_slot);
3940 }
3941 spill_interval->assign_reg(spill_slot);
3942 allocator()->append_interval(spill_interval);
3944 TRACE_LINEAR_SCAN(4, tty->print_cr("created new Interval %d for spilling", spill_interval->reg_num()));
3946 // insert a move from register to stack and update the mapping
3947 insert_move(from_interval, spill_interval);
3948 _mapping_from.at_put(spill_candidate, spill_interval);
3949 unblock_registers(from_interval);
3950 }
3951 }
3953 // reset to default value
3954 _multiple_reads_allowed = false;
3956 // check that all intervals have been processed
3957 DEBUG_ONLY(check_empty());
3958 }
3961 void MoveResolver::set_insert_position(LIR_List* insert_list, int insert_idx) {
3962 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: setting insert position to Block B%d, index %d", insert_list->block() != NULL ? insert_list->block()->block_id() : -1, insert_idx));
3963 assert(_insert_list == NULL && _insert_idx == -1, "use move_insert_position instead of set_insert_position when data already set");
3965 create_insertion_buffer(insert_list);
3966 _insert_list = insert_list;
3967 _insert_idx = insert_idx;
3968 }
3970 void MoveResolver::move_insert_position(LIR_List* insert_list, int insert_idx) {
3971 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: moving insert position to Block B%d, index %d", insert_list->block() != NULL ? insert_list->block()->block_id() : -1, insert_idx));
3973 if (_insert_list != NULL && (insert_list != _insert_list || insert_idx != _insert_idx)) {
3974 // insert position changed -> resolve current mappings
3975 resolve_mappings();
3976 }
3978 if (insert_list != _insert_list) {
3979 // block changed -> append insertion_buffer because it is
3980 // bound to a specific block and create a new insertion_buffer
3981 append_insertion_buffer();
3982 create_insertion_buffer(insert_list);
3983 }
3985 _insert_list = insert_list;
3986 _insert_idx = insert_idx;
3987 }
3989 void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {
3990 TRACE_LINEAR_SCAN(4, tty->print_cr("MoveResolver: adding mapping from %d (%d, %d) to %d (%d, %d)", from_interval->reg_num(), from_interval->assigned_reg(), from_interval->assigned_regHi(), to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
3992 _mapping_from.append(from_interval);
3993 _mapping_from_opr.append(LIR_OprFact::illegalOpr);
3994 _mapping_to.append(to_interval);
3995 }
3998 void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {
3999 TRACE_LINEAR_SCAN(4, tty->print("MoveResolver: adding mapping from "); from_opr->print(); tty->print_cr(" to %d (%d, %d)", to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
4000 assert(from_opr->is_constant(), "only for constants");
4002 _mapping_from.append(NULL);
4003 _mapping_from_opr.append(from_opr);
4004 _mapping_to.append(to_interval);
4005 }
4007 void MoveResolver::resolve_and_append_moves() {
4008 if (has_mappings()) {
4009 resolve_mappings();
4010 }
4011 append_insertion_buffer();
4012 }
4016 // **** Implementation of Range *************************************
4018 Range::Range(int from, int to, Range* next) :
4019 _from(from),
4020 _to(to),
4021 _next(next)
4022 {
4023 }
4025 // initialize sentinel
4026 Range* Range::_end = NULL;
4027 void Range::initialize(Arena* arena) {
4028 _end = new (arena) Range(max_jint, max_jint, NULL);
4029 }
4031 int Range::intersects_at(Range* r2) const {
4032 const Range* r1 = this;
4034 assert(r1 != NULL && r2 != NULL, "null ranges not allowed");
4035 assert(r1 != _end && r2 != _end, "empty ranges not allowed");
4037 do {
4038 if (r1->from() < r2->from()) {
4039 if (r1->to() <= r2->from()) {
4040 r1 = r1->next(); if (r1 == _end) return -1;
4041 } else {
4042 return r2->from();
4043 }
4044 } else if (r2->from() < r1->from()) {
4045 if (r2->to() <= r1->from()) {
4046 r2 = r2->next(); if (r2 == _end) return -1;
4047 } else {
4048 return r1->from();
4049 }
4050 } else { // r1->from() == r2->from()
4051 if (r1->from() == r1->to()) {
4052 r1 = r1->next(); if (r1 == _end) return -1;
4053 } else if (r2->from() == r2->to()) {
4054 r2 = r2->next(); if (r2 == _end) return -1;
4055 } else {
4056 return r1->from();
4057 }
4058 }
4059 } while (true);
4060 }
4062 #ifndef PRODUCT
4063 void Range::print(outputStream* out) const {
4064 out->print("[%d, %d[ ", _from, _to);
4065 }
4066 #endif
4070 // **** Implementation of Interval **********************************
4072 // initialize sentinel
4073 Interval* Interval::_end = NULL;
4074 void Interval::initialize(Arena* arena) {
4075 Range::initialize(arena);
4076 _end = new (arena) Interval(-1);
4077 }
4079 Interval::Interval(int reg_num) :
4080 _reg_num(reg_num),
4081 _type(T_ILLEGAL),
4082 _first(Range::end()),
4083 _use_pos_and_kinds(12),
4084 _current(Range::end()),
4085 _next(_end),
4086 _state(invalidState),
4087 _assigned_reg(LinearScan::any_reg),
4088 _assigned_regHi(LinearScan::any_reg),
4089 _cached_to(-1),
4090 _cached_opr(LIR_OprFact::illegalOpr),
4091 _cached_vm_reg(VMRegImpl::Bad()),
4092 _split_children(0),
4093 _canonical_spill_slot(-1),
4094 _insert_move_when_activated(false),
4095 _register_hint(NULL),
4096 _spill_state(noDefinitionFound),
4097 _spill_definition_pos(-1)
4098 {
4099 _split_parent = this;
4100 _current_split_child = this;
4101 }
4103 int Interval::calc_to() {
4104 assert(_first != Range::end(), "interval has no range");
4106 Range* r = _first;
4107 while (r->next() != Range::end()) {
4108 r = r->next();
4109 }
4110 return r->to();
4111 }
4114 #ifdef ASSERT
4115 // consistency check of split-children
4116 void Interval::check_split_children() {
4117 if (_split_children.length() > 0) {
4118 assert(is_split_parent(), "only split parents can have children");
4120 for (int i = 0; i < _split_children.length(); i++) {
4121 Interval* i1 = _split_children.at(i);
4123 assert(i1->split_parent() == this, "not a split child of this interval");
4124 assert(i1->type() == type(), "must be equal for all split children");
4125 assert(i1->canonical_spill_slot() == canonical_spill_slot(), "must be equal for all split children");
4127 for (int j = i + 1; j < _split_children.length(); j++) {
4128 Interval* i2 = _split_children.at(j);
4130 assert(i1->reg_num() != i2->reg_num(), "same register number");
4132 if (i1->from() < i2->from()) {
4133 assert(i1->to() <= i2->from() && i1->to() < i2->to(), "intervals overlapping");
4134 } else {
4135 assert(i2->from() < i1->from(), "intervals start at same op_id");
4136 assert(i2->to() <= i1->from() && i2->to() < i1->to(), "intervals overlapping");
4137 }
4138 }
4139 }
4140 }
4141 }
4142 #endif // ASSERT
4144 Interval* Interval::register_hint(bool search_split_child) const {
4145 if (!search_split_child) {
4146 return _register_hint;
4147 }
4149 if (_register_hint != NULL) {
4150 assert(_register_hint->is_split_parent(), "ony split parents are valid hint registers");
4152 if (_register_hint->assigned_reg() >= 0 && _register_hint->assigned_reg() < LinearScan::nof_regs) {
4153 return _register_hint;
4155 } else if (_register_hint->_split_children.length() > 0) {
4156 // search the first split child that has a register assigned
4157 int len = _register_hint->_split_children.length();
4158 for (int i = 0; i < len; i++) {
4159 Interval* cur = _register_hint->_split_children.at(i);
4161 if (cur->assigned_reg() >= 0 && cur->assigned_reg() < LinearScan::nof_regs) {
4162 return cur;
4163 }
4164 }
4165 }
4166 }
4168 // no hint interval found that has a register assigned
4169 return NULL;
4170 }
4173 Interval* Interval::split_child_at_op_id(int op_id, LIR_OpVisitState::OprMode mode) {
4174 assert(is_split_parent(), "can only be called for split parents");
4175 assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
4177 Interval* result;
4178 if (_split_children.length() == 0) {
4179 result = this;
4180 } else {
4181 result = NULL;
4182 int len = _split_children.length();
4184 // in outputMode, the end of the interval (op_id == cur->to()) is not valid
4185 int to_offset = (mode == LIR_OpVisitState::outputMode ? 0 : 1);
4187 int i;
4188 for (i = 0; i < len; i++) {
4189 Interval* cur = _split_children.at(i);
4190 if (cur->from() <= op_id && op_id < cur->to() + to_offset) {
4191 if (i > 0) {
4192 // exchange current split child to start of list (faster access for next call)
4193 _split_children.at_put(i, _split_children.at(0));
4194 _split_children.at_put(0, cur);
4195 }
4197 // interval found
4198 result = cur;
4199 break;
4200 }
4201 }
4203 #ifdef ASSERT
4204 for (i = 0; i < len; i++) {
4205 Interval* tmp = _split_children.at(i);
4206 if (tmp != result && tmp->from() <= op_id && op_id < tmp->to() + to_offset) {
4207 tty->print_cr("two valid result intervals found for op_id %d: %d and %d", op_id, result->reg_num(), tmp->reg_num());
4208 result->print();
4209 tmp->print();
4210 assert(false, "two valid result intervals found");
4211 }
4212 }
4213 #endif
4214 }
4216 assert(result != NULL, "no matching interval found");
4217 assert(result->covers(op_id, mode), "op_id not covered by interval");
4219 return result;
4220 }
4223 // returns the last split child that ends before the given op_id
4224 Interval* Interval::split_child_before_op_id(int op_id) {
4225 assert(op_id >= 0, "invalid op_id");
4227 Interval* parent = split_parent();
4228 Interval* result = NULL;
4230 int len = parent->_split_children.length();
4231 assert(len > 0, "no split children available");
4233 for (int i = len - 1; i >= 0; i--) {
4234 Interval* cur = parent->_split_children.at(i);
4235 if (cur->to() <= op_id && (result == NULL || result->to() < cur->to())) {
4236 result = cur;
4237 }
4238 }
4240 assert(result != NULL, "no split child found");
4241 return result;
4242 }
4245 // checks if op_id is covered by any split child
4246 bool Interval::split_child_covers(int op_id, LIR_OpVisitState::OprMode mode) {
4247 assert(is_split_parent(), "can only be called for split parents");
4248 assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
4250 if (_split_children.length() == 0) {
4251 // simple case if interval was not split
4252 return covers(op_id, mode);
4254 } else {
4255 // extended case: check all split children
4256 int len = _split_children.length();
4257 for (int i = 0; i < len; i++) {
4258 Interval* cur = _split_children.at(i);
4259 if (cur->covers(op_id, mode)) {
4260 return true;
4261 }
4262 }
4263 return false;
4264 }
4265 }
4268 // Note: use positions are sorted descending -> first use has highest index
4269 int Interval::first_usage(IntervalUseKind min_use_kind) const {
4270 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4272 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4273 if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
4274 return _use_pos_and_kinds.at(i);
4275 }
4276 }
4277 return max_jint;
4278 }
4280 int Interval::next_usage(IntervalUseKind min_use_kind, int from) const {
4281 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4283 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4284 if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) >= min_use_kind) {
4285 return _use_pos_and_kinds.at(i);
4286 }
4287 }
4288 return max_jint;
4289 }
4291 int Interval::next_usage_exact(IntervalUseKind exact_use_kind, int from) const {
4292 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4294 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4295 if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) == exact_use_kind) {
4296 return _use_pos_and_kinds.at(i);
4297 }
4298 }
4299 return max_jint;
4300 }
4302 int Interval::previous_usage(IntervalUseKind min_use_kind, int from) const {
4303 assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
4305 int prev = 0;
4306 for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4307 if (_use_pos_and_kinds.at(i) > from) {
4308 return prev;
4309 }
4310 if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
4311 prev = _use_pos_and_kinds.at(i);
4312 }
4313 }
4314 return prev;
4315 }
4317 void Interval::add_use_pos(int pos, IntervalUseKind use_kind) {
4318 assert(covers(pos, LIR_OpVisitState::inputMode), "use position not covered by live range");
4320 // do not add use positions for precolored intervals because
4321 // they are never used
4322 if (use_kind != noUse && reg_num() >= LIR_OprDesc::vreg_base) {
4323 #ifdef ASSERT
4324 assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
4325 for (int i = 0; i < _use_pos_and_kinds.length(); i += 2) {
4326 assert(pos <= _use_pos_and_kinds.at(i), "already added a use-position with lower position");
4327 assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4328 if (i > 0) {
4329 assert(_use_pos_and_kinds.at(i) < _use_pos_and_kinds.at(i - 2), "not sorted descending");
4330 }
4331 }
4332 #endif
4334 // Note: add_use is called in descending order, so list gets sorted
4335 // automatically by just appending new use positions
4336 int len = _use_pos_and_kinds.length();
4337 if (len == 0 || _use_pos_and_kinds.at(len - 2) > pos) {
4338 _use_pos_and_kinds.append(pos);
4339 _use_pos_and_kinds.append(use_kind);
4340 } else if (_use_pos_and_kinds.at(len - 1) < use_kind) {
4341 assert(_use_pos_and_kinds.at(len - 2) == pos, "list not sorted correctly");
4342 _use_pos_and_kinds.at_put(len - 1, use_kind);
4343 }
4344 }
4345 }
4347 void Interval::add_range(int from, int to) {
4348 assert(from < to, "invalid range");
4349 assert(first() == Range::end() || to < first()->next()->from(), "not inserting at begin of interval");
4350 assert(from <= first()->to(), "not inserting at begin of interval");
4352 if (first()->from() <= to) {
4353 // join intersecting ranges
4354 first()->set_from(MIN2(from, first()->from()));
4355 first()->set_to (MAX2(to, first()->to()));
4356 } else {
4357 // insert new range
4358 _first = new Range(from, to, first());
4359 }
4360 }
4362 Interval* Interval::new_split_child() {
4363 // allocate new interval
4364 Interval* result = new Interval(-1);
4365 result->set_type(type());
4367 Interval* parent = split_parent();
4368 result->_split_parent = parent;
4369 result->set_register_hint(parent);
4371 // insert new interval in children-list of parent
4372 if (parent->_split_children.length() == 0) {
4373 assert(is_split_parent(), "list must be initialized at first split");
4375 parent->_split_children = IntervalList(4);
4376 parent->_split_children.append(this);
4377 }
4378 parent->_split_children.append(result);
4380 return result;
4381 }
4383 // split this interval at the specified position and return
4384 // the remainder as a new interval.
4385 //
4386 // when an interval is split, a bi-directional link is established between the original interval
4387 // (the split parent) and the intervals that are split off this interval (the split children)
4388 // When a split child is split again, the new created interval is also a direct child
4389 // of the original parent (there is no tree of split children stored, but a flat list)
4390 // All split children are spilled to the same stack slot (stored in _canonical_spill_slot)
4391 //
4392 // Note: The new interval has no valid reg_num
4393 Interval* Interval::split(int split_pos) {
4394 assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
4396 // allocate new interval
4397 Interval* result = new_split_child();
4399 // split the ranges
4400 Range* prev = NULL;
4401 Range* cur = _first;
4402 while (cur != Range::end() && cur->to() <= split_pos) {
4403 prev = cur;
4404 cur = cur->next();
4405 }
4406 assert(cur != Range::end(), "split interval after end of last range");
4408 if (cur->from() < split_pos) {
4409 result->_first = new Range(split_pos, cur->to(), cur->next());
4410 cur->set_to(split_pos);
4411 cur->set_next(Range::end());
4413 } else {
4414 assert(prev != NULL, "split before start of first range");
4415 result->_first = cur;
4416 prev->set_next(Range::end());
4417 }
4418 result->_current = result->_first;
4419 _cached_to = -1; // clear cached value
4421 // split list of use positions
4422 int total_len = _use_pos_and_kinds.length();
4423 int start_idx = total_len - 2;
4424 while (start_idx >= 0 && _use_pos_and_kinds.at(start_idx) < split_pos) {
4425 start_idx -= 2;
4426 }
4428 intStack new_use_pos_and_kinds(total_len - start_idx);
4429 int i;
4430 for (i = start_idx + 2; i < total_len; i++) {
4431 new_use_pos_and_kinds.append(_use_pos_and_kinds.at(i));
4432 }
4434 _use_pos_and_kinds.truncate(start_idx + 2);
4435 result->_use_pos_and_kinds = _use_pos_and_kinds;
4436 _use_pos_and_kinds = new_use_pos_and_kinds;
4438 #ifdef ASSERT
4439 assert(_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
4440 assert(result->_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
4441 assert(_use_pos_and_kinds.length() + result->_use_pos_and_kinds.length() == total_len, "missed some entries");
4443 for (i = 0; i < _use_pos_and_kinds.length(); i += 2) {
4444 assert(_use_pos_and_kinds.at(i) < split_pos, "must be");
4445 assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4446 }
4447 for (i = 0; i < result->_use_pos_and_kinds.length(); i += 2) {
4448 assert(result->_use_pos_and_kinds.at(i) >= split_pos, "must be");
4449 assert(result->_use_pos_and_kinds.at(i + 1) >= firstValidKind && result->_use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4450 }
4451 #endif
4453 return result;
4454 }
4456 // split this interval at the specified position and return
4457 // the head as a new interval (the original interval is the tail)
4458 //
4459 // Currently, only the first range can be split, and the new interval
4460 // must not have split positions
4461 Interval* Interval::split_from_start(int split_pos) {
4462 assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
4463 assert(split_pos > from() && split_pos < to(), "can only split inside interval");
4464 assert(split_pos > _first->from() && split_pos <= _first->to(), "can only split inside first range");
4465 assert(first_usage(noUse) > split_pos, "can not split when use positions are present");
4467 // allocate new interval
4468 Interval* result = new_split_child();
4470 // the new created interval has only one range (checked by assertion above),
4471 // so the splitting of the ranges is very simple
4472 result->add_range(_first->from(), split_pos);
4474 if (split_pos == _first->to()) {
4475 assert(_first->next() != Range::end(), "must not be at end");
4476 _first = _first->next();
4477 } else {
4478 _first->set_from(split_pos);
4479 }
4481 return result;
4482 }
4485 // returns true if the op_id is inside the interval
4486 bool Interval::covers(int op_id, LIR_OpVisitState::OprMode mode) const {
4487 Range* cur = _first;
4489 while (cur != Range::end() && cur->to() < op_id) {
4490 cur = cur->next();
4491 }
4492 if (cur != Range::end()) {
4493 assert(cur->to() != cur->next()->from(), "ranges not separated");
4495 if (mode == LIR_OpVisitState::outputMode) {
4496 return cur->from() <= op_id && op_id < cur->to();
4497 } else {
4498 return cur->from() <= op_id && op_id <= cur->to();
4499 }
4500 }
4501 return false;
4502 }
4504 // returns true if the interval has any hole between hole_from and hole_to
4505 // (even if the hole has only the length 1)
4506 bool Interval::has_hole_between(int hole_from, int hole_to) {
4507 assert(hole_from < hole_to, "check");
4508 assert(from() <= hole_from && hole_to <= to(), "index out of interval");
4510 Range* cur = _first;
4511 while (cur != Range::end()) {
4512 assert(cur->to() < cur->next()->from(), "no space between ranges");
4514 // hole-range starts before this range -> hole
4515 if (hole_from < cur->from()) {
4516 return true;
4518 // hole-range completely inside this range -> no hole
4519 } else if (hole_to <= cur->to()) {
4520 return false;
4522 // overlapping of hole-range with this range -> hole
4523 } else if (hole_from <= cur->to()) {
4524 return true;
4525 }
4527 cur = cur->next();
4528 }
4530 return false;
4531 }
4534 #ifndef PRODUCT
4535 void Interval::print(outputStream* out) const {
4536 const char* SpillState2Name[] = { "no definition", "no spill store", "one spill store", "store at definition", "start in memory", "no optimization" };
4537 const char* UseKind2Name[] = { "N", "L", "S", "M" };
4539 const char* type_name;
4540 LIR_Opr opr = LIR_OprFact::illegal();
4541 if (reg_num() < LIR_OprDesc::vreg_base) {
4542 type_name = "fixed";
4543 // need a temporary operand for fixed intervals because type() cannot be called
4544 if (assigned_reg() >= pd_first_cpu_reg && assigned_reg() <= pd_last_cpu_reg) {
4545 opr = LIR_OprFact::single_cpu(assigned_reg());
4546 } else if (assigned_reg() >= pd_first_fpu_reg && assigned_reg() <= pd_last_fpu_reg) {
4547 opr = LIR_OprFact::single_fpu(assigned_reg() - pd_first_fpu_reg);
4548 #ifdef X86
4549 } else if (assigned_reg() >= pd_first_xmm_reg && assigned_reg() <= pd_last_xmm_reg) {
4550 opr = LIR_OprFact::single_xmm(assigned_reg() - pd_first_xmm_reg);
4551 #endif
4552 } else {
4553 ShouldNotReachHere();
4554 }
4555 } else {
4556 type_name = type2name(type());
4557 if (assigned_reg() != -1 &&
4558 (LinearScan::num_physical_regs(type()) == 1 || assigned_regHi() != -1)) {
4559 opr = LinearScan::calc_operand_for_interval(this);
4560 }
4561 }
4563 out->print("%d %s ", reg_num(), type_name);
4564 if (opr->is_valid()) {
4565 out->print("\"");
4566 opr->print(out);
4567 out->print("\" ");
4568 }
4569 out->print("%d %d ", split_parent()->reg_num(), (register_hint(false) != NULL ? register_hint(false)->reg_num() : -1));
4571 // print ranges
4572 Range* cur = _first;
4573 while (cur != Range::end()) {
4574 cur->print(out);
4575 cur = cur->next();
4576 assert(cur != NULL, "range list not closed with range sentinel");
4577 }
4579 // print use positions
4580 int prev = 0;
4581 assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
4582 for (int i =_use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
4583 assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
4584 assert(prev < _use_pos_and_kinds.at(i), "use positions not sorted");
4586 out->print("%d %s ", _use_pos_and_kinds.at(i), UseKind2Name[_use_pos_and_kinds.at(i + 1)]);
4587 prev = _use_pos_and_kinds.at(i);
4588 }
4590 out->print(" \"%s\"", SpillState2Name[spill_state()]);
4591 out->cr();
4592 }
4593 #endif
4597 // **** Implementation of IntervalWalker ****************************
4599 IntervalWalker::IntervalWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
4600 : _compilation(allocator->compilation())
4601 , _allocator(allocator)
4602 {
4603 _unhandled_first[fixedKind] = unhandled_fixed_first;
4604 _unhandled_first[anyKind] = unhandled_any_first;
4605 _active_first[fixedKind] = Interval::end();
4606 _inactive_first[fixedKind] = Interval::end();
4607 _active_first[anyKind] = Interval::end();
4608 _inactive_first[anyKind] = Interval::end();
4609 _current_position = -1;
4610 _current = NULL;
4611 next_interval();
4612 }
4615 // append interval at top of list
4616 void IntervalWalker::append_unsorted(Interval** list, Interval* interval) {
4617 interval->set_next(*list); *list = interval;
4618 }
4621 // append interval in order of current range from()
4622 void IntervalWalker::append_sorted(Interval** list, Interval* interval) {
4623 Interval* prev = NULL;
4624 Interval* cur = *list;
4625 while (cur->current_from() < interval->current_from()) {
4626 prev = cur; cur = cur->next();
4627 }
4628 if (prev == NULL) {
4629 *list = interval;
4630 } else {
4631 prev->set_next(interval);
4632 }
4633 interval->set_next(cur);
4634 }
4636 void IntervalWalker::append_to_unhandled(Interval** list, Interval* interval) {
4637 assert(interval->from() >= current()->current_from(), "cannot append new interval before current walk position");
4639 Interval* prev = NULL;
4640 Interval* cur = *list;
4641 while (cur->from() < interval->from() || (cur->from() == interval->from() && cur->first_usage(noUse) < interval->first_usage(noUse))) {
4642 prev = cur; cur = cur->next();
4643 }
4644 if (prev == NULL) {
4645 *list = interval;
4646 } else {
4647 prev->set_next(interval);
4648 }
4649 interval->set_next(cur);
4650 }
4653 inline bool IntervalWalker::remove_from_list(Interval** list, Interval* i) {
4654 while (*list != Interval::end() && *list != i) {
4655 list = (*list)->next_addr();
4656 }
4657 if (*list != Interval::end()) {
4658 assert(*list == i, "check");
4659 *list = (*list)->next();
4660 return true;
4661 } else {
4662 return false;
4663 }
4664 }
4666 void IntervalWalker::remove_from_list(Interval* i) {
4667 bool deleted;
4669 if (i->state() == activeState) {
4670 deleted = remove_from_list(active_first_addr(anyKind), i);
4671 } else {
4672 assert(i->state() == inactiveState, "invalid state");
4673 deleted = remove_from_list(inactive_first_addr(anyKind), i);
4674 }
4676 assert(deleted, "interval has not been found in list");
4677 }
4680 void IntervalWalker::walk_to(IntervalState state, int from) {
4681 assert (state == activeState || state == inactiveState, "wrong state");
4682 for_each_interval_kind(kind) {
4683 Interval** prev = state == activeState ? active_first_addr(kind) : inactive_first_addr(kind);
4684 Interval* next = *prev;
4685 while (next->current_from() <= from) {
4686 Interval* cur = next;
4687 next = cur->next();
4689 bool range_has_changed = false;
4690 while (cur->current_to() <= from) {
4691 cur->next_range();
4692 range_has_changed = true;
4693 }
4695 // also handle move from inactive list to active list
4696 range_has_changed = range_has_changed || (state == inactiveState && cur->current_from() <= from);
4698 if (range_has_changed) {
4699 // remove cur from list
4700 *prev = next;
4701 if (cur->current_at_end()) {
4702 // move to handled state (not maintained as a list)
4703 cur->set_state(handledState);
4704 interval_moved(cur, kind, state, handledState);
4705 } else if (cur->current_from() <= from){
4706 // sort into active list
4707 append_sorted(active_first_addr(kind), cur);
4708 cur->set_state(activeState);
4709 if (*prev == cur) {
4710 assert(state == activeState, "check");
4711 prev = cur->next_addr();
4712 }
4713 interval_moved(cur, kind, state, activeState);
4714 } else {
4715 // sort into inactive list
4716 append_sorted(inactive_first_addr(kind), cur);
4717 cur->set_state(inactiveState);
4718 if (*prev == cur) {
4719 assert(state == inactiveState, "check");
4720 prev = cur->next_addr();
4721 }
4722 interval_moved(cur, kind, state, inactiveState);
4723 }
4724 } else {
4725 prev = cur->next_addr();
4726 continue;
4727 }
4728 }
4729 }
4730 }
4733 void IntervalWalker::next_interval() {
4734 IntervalKind kind;
4735 Interval* any = _unhandled_first[anyKind];
4736 Interval* fixed = _unhandled_first[fixedKind];
4738 if (any != Interval::end()) {
4739 // intervals may start at same position -> prefer fixed interval
4740 kind = fixed != Interval::end() && fixed->from() <= any->from() ? fixedKind : anyKind;
4742 assert (kind == fixedKind && fixed->from() <= any->from() ||
4743 kind == anyKind && any->from() <= fixed->from(), "wrong interval!!!");
4744 assert(any == Interval::end() || fixed == Interval::end() || any->from() != fixed->from() || kind == fixedKind, "if fixed and any-Interval start at same position, fixed must be processed first");
4746 } else if (fixed != Interval::end()) {
4747 kind = fixedKind;
4748 } else {
4749 _current = NULL; return;
4750 }
4751 _current_kind = kind;
4752 _current = _unhandled_first[kind];
4753 _unhandled_first[kind] = _current->next();
4754 _current->set_next(Interval::end());
4755 _current->rewind_range();
4756 }
4759 void IntervalWalker::walk_to(int lir_op_id) {
4760 assert(_current_position <= lir_op_id, "can not walk backwards");
4761 while (current() != NULL) {
4762 bool is_active = current()->from() <= lir_op_id;
4763 int id = is_active ? current()->from() : lir_op_id;
4765 TRACE_LINEAR_SCAN(2, if (_current_position < id) { tty->cr(); tty->print_cr("walk_to(%d) **************************************************************", id); })
4767 // set _current_position prior to call of walk_to
4768 _current_position = id;
4770 // call walk_to even if _current_position == id
4771 walk_to(activeState, id);
4772 walk_to(inactiveState, id);
4774 if (is_active) {
4775 current()->set_state(activeState);
4776 if (activate_current()) {
4777 append_sorted(active_first_addr(current_kind()), current());
4778 interval_moved(current(), current_kind(), unhandledState, activeState);
4779 }
4781 next_interval();
4782 } else {
4783 return;
4784 }
4785 }
4786 }
4788 void IntervalWalker::interval_moved(Interval* interval, IntervalKind kind, IntervalState from, IntervalState to) {
4789 #ifndef PRODUCT
4790 if (TraceLinearScanLevel >= 4) {
4791 #define print_state(state) \
4792 switch(state) {\
4793 case unhandledState: tty->print("unhandled"); break;\
4794 case activeState: tty->print("active"); break;\
4795 case inactiveState: tty->print("inactive"); break;\
4796 case handledState: tty->print("handled"); break;\
4797 default: ShouldNotReachHere(); \
4798 }
4800 print_state(from); tty->print(" to "); print_state(to);
4801 tty->fill_to(23);
4802 interval->print();
4804 #undef print_state
4805 }
4806 #endif
4807 }
4811 // **** Implementation of LinearScanWalker **************************
4813 LinearScanWalker::LinearScanWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
4814 : IntervalWalker(allocator, unhandled_fixed_first, unhandled_any_first)
4815 , _move_resolver(allocator)
4816 {
4817 for (int i = 0; i < LinearScan::nof_regs; i++) {
4818 _spill_intervals[i] = new IntervalList(2);
4819 }
4820 }
4823 inline void LinearScanWalker::init_use_lists(bool only_process_use_pos) {
4824 for (int i = _first_reg; i <= _last_reg; i++) {
4825 _use_pos[i] = max_jint;
4827 if (!only_process_use_pos) {
4828 _block_pos[i] = max_jint;
4829 _spill_intervals[i]->clear();
4830 }
4831 }
4832 }
4834 inline void LinearScanWalker::exclude_from_use(int reg) {
4835 assert(reg < LinearScan::nof_regs, "interval must have a register assigned (stack slots not allowed)");
4836 if (reg >= _first_reg && reg <= _last_reg) {
4837 _use_pos[reg] = 0;
4838 }
4839 }
4840 inline void LinearScanWalker::exclude_from_use(Interval* i) {
4841 assert(i->assigned_reg() != any_reg, "interval has no register assigned");
4843 exclude_from_use(i->assigned_reg());
4844 exclude_from_use(i->assigned_regHi());
4845 }
4847 inline void LinearScanWalker::set_use_pos(int reg, Interval* i, int use_pos, bool only_process_use_pos) {
4848 assert(use_pos != 0, "must use exclude_from_use to set use_pos to 0");
4850 if (reg >= _first_reg && reg <= _last_reg) {
4851 if (_use_pos[reg] > use_pos) {
4852 _use_pos[reg] = use_pos;
4853 }
4854 if (!only_process_use_pos) {
4855 _spill_intervals[reg]->append(i);
4856 }
4857 }
4858 }
4859 inline void LinearScanWalker::set_use_pos(Interval* i, int use_pos, bool only_process_use_pos) {
4860 assert(i->assigned_reg() != any_reg, "interval has no register assigned");
4861 if (use_pos != -1) {
4862 set_use_pos(i->assigned_reg(), i, use_pos, only_process_use_pos);
4863 set_use_pos(i->assigned_regHi(), i, use_pos, only_process_use_pos);
4864 }
4865 }
4867 inline void LinearScanWalker::set_block_pos(int reg, Interval* i, int block_pos) {
4868 if (reg >= _first_reg && reg <= _last_reg) {
4869 if (_block_pos[reg] > block_pos) {
4870 _block_pos[reg] = block_pos;
4871 }
4872 if (_use_pos[reg] > block_pos) {
4873 _use_pos[reg] = block_pos;
4874 }
4875 }
4876 }
4877 inline void LinearScanWalker::set_block_pos(Interval* i, int block_pos) {
4878 assert(i->assigned_reg() != any_reg, "interval has no register assigned");
4879 if (block_pos != -1) {
4880 set_block_pos(i->assigned_reg(), i, block_pos);
4881 set_block_pos(i->assigned_regHi(), i, block_pos);
4882 }
4883 }
4886 void LinearScanWalker::free_exclude_active_fixed() {
4887 Interval* list = active_first(fixedKind);
4888 while (list != Interval::end()) {
4889 assert(list->assigned_reg() < LinearScan::nof_regs, "active interval must have a register assigned");
4890 exclude_from_use(list);
4891 list = list->next();
4892 }
4893 }
4895 void LinearScanWalker::free_exclude_active_any() {
4896 Interval* list = active_first(anyKind);
4897 while (list != Interval::end()) {
4898 exclude_from_use(list);
4899 list = list->next();
4900 }
4901 }
4903 void LinearScanWalker::free_collect_inactive_fixed(Interval* cur) {
4904 Interval* list = inactive_first(fixedKind);
4905 while (list != Interval::end()) {
4906 if (cur->to() <= list->current_from()) {
4907 assert(list->current_intersects_at(cur) == -1, "must not intersect");
4908 set_use_pos(list, list->current_from(), true);
4909 } else {
4910 set_use_pos(list, list->current_intersects_at(cur), true);
4911 }
4912 list = list->next();
4913 }
4914 }
4916 void LinearScanWalker::free_collect_inactive_any(Interval* cur) {
4917 Interval* list = inactive_first(anyKind);
4918 while (list != Interval::end()) {
4919 set_use_pos(list, list->current_intersects_at(cur), true);
4920 list = list->next();
4921 }
4922 }
4924 void LinearScanWalker::free_collect_unhandled(IntervalKind kind, Interval* cur) {
4925 Interval* list = unhandled_first(kind);
4926 while (list != Interval::end()) {
4927 set_use_pos(list, list->intersects_at(cur), true);
4928 if (kind == fixedKind && cur->to() <= list->from()) {
4929 set_use_pos(list, list->from(), true);
4930 }
4931 list = list->next();
4932 }
4933 }
4935 void LinearScanWalker::spill_exclude_active_fixed() {
4936 Interval* list = active_first(fixedKind);
4937 while (list != Interval::end()) {
4938 exclude_from_use(list);
4939 list = list->next();
4940 }
4941 }
4943 void LinearScanWalker::spill_block_unhandled_fixed(Interval* cur) {
4944 Interval* list = unhandled_first(fixedKind);
4945 while (list != Interval::end()) {
4946 set_block_pos(list, list->intersects_at(cur));
4947 list = list->next();
4948 }
4949 }
4951 void LinearScanWalker::spill_block_inactive_fixed(Interval* cur) {
4952 Interval* list = inactive_first(fixedKind);
4953 while (list != Interval::end()) {
4954 if (cur->to() > list->current_from()) {
4955 set_block_pos(list, list->current_intersects_at(cur));
4956 } else {
4957 assert(list->current_intersects_at(cur) == -1, "invalid optimization: intervals intersect");
4958 }
4960 list = list->next();
4961 }
4962 }
4964 void LinearScanWalker::spill_collect_active_any() {
4965 Interval* list = active_first(anyKind);
4966 while (list != Interval::end()) {
4967 set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
4968 list = list->next();
4969 }
4970 }
4972 void LinearScanWalker::spill_collect_inactive_any(Interval* cur) {
4973 Interval* list = inactive_first(anyKind);
4974 while (list != Interval::end()) {
4975 if (list->current_intersects(cur)) {
4976 set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
4977 }
4978 list = list->next();
4979 }
4980 }
4983 void LinearScanWalker::insert_move(int op_id, Interval* src_it, Interval* dst_it) {
4984 // output all moves here. When source and target are equal, the move is
4985 // optimized away later in assign_reg_nums
4987 op_id = (op_id + 1) & ~1;
4988 BlockBegin* op_block = allocator()->block_of_op_with_id(op_id);
4989 assert(op_id > 0 && allocator()->block_of_op_with_id(op_id - 2) == op_block, "cannot insert move at block boundary");
4991 // calculate index of instruction inside instruction list of current block
4992 // the minimal index (for a block with no spill moves) can be calculated because the
4993 // numbering of instructions is known.
4994 // When the block already contains spill moves, the index must be increased until the
4995 // correct index is reached.
4996 LIR_OpList* list = op_block->lir()->instructions_list();
4997 int index = (op_id - list->at(0)->id()) / 2;
4998 assert(list->at(index)->id() <= op_id, "error in calculation");
5000 while (list->at(index)->id() != op_id) {
5001 index++;
5002 assert(0 <= index && index < list->length(), "index out of bounds");
5003 }
5004 assert(1 <= index && index < list->length(), "index out of bounds");
5005 assert(list->at(index)->id() == op_id, "error in calculation");
5007 // insert new instruction before instruction at position index
5008 _move_resolver.move_insert_position(op_block->lir(), index - 1);
5009 _move_resolver.add_mapping(src_it, dst_it);
5010 }
5013 int LinearScanWalker::find_optimal_split_pos(BlockBegin* min_block, BlockBegin* max_block, int max_split_pos) {
5014 int from_block_nr = min_block->linear_scan_number();
5015 int to_block_nr = max_block->linear_scan_number();
5017 assert(0 <= from_block_nr && from_block_nr < block_count(), "out of range");
5018 assert(0 <= to_block_nr && to_block_nr < block_count(), "out of range");
5019 assert(from_block_nr < to_block_nr, "must cross block boundary");
5021 // Try to split at end of max_block. If this would be after
5022 // max_split_pos, then use the begin of max_block
5023 int optimal_split_pos = max_block->last_lir_instruction_id() + 2;
5024 if (optimal_split_pos > max_split_pos) {
5025 optimal_split_pos = max_block->first_lir_instruction_id();
5026 }
5028 int min_loop_depth = max_block->loop_depth();
5029 for (int i = to_block_nr - 1; i >= from_block_nr; i--) {
5030 BlockBegin* cur = block_at(i);
5032 if (cur->loop_depth() < min_loop_depth) {
5033 // block with lower loop-depth found -> split at the end of this block
5034 min_loop_depth = cur->loop_depth();
5035 optimal_split_pos = cur->last_lir_instruction_id() + 2;
5036 }
5037 }
5038 assert(optimal_split_pos > allocator()->max_lir_op_id() || allocator()->is_block_begin(optimal_split_pos), "algorithm must move split pos to block boundary");
5040 return optimal_split_pos;
5041 }
5044 int LinearScanWalker::find_optimal_split_pos(Interval* it, int min_split_pos, int max_split_pos, bool do_loop_optimization) {
5045 int optimal_split_pos = -1;
5046 if (min_split_pos == max_split_pos) {
5047 // trivial case, no optimization of split position possible
5048 TRACE_LINEAR_SCAN(4, tty->print_cr(" min-pos and max-pos are equal, no optimization possible"));
5049 optimal_split_pos = min_split_pos;
5051 } else {
5052 assert(min_split_pos < max_split_pos, "must be true then");
5053 assert(min_split_pos > 0, "cannot access min_split_pos - 1 otherwise");
5055 // reason for using min_split_pos - 1: when the minimal split pos is exactly at the
5056 // beginning of a block, then min_split_pos is also a possible split position.
5057 // Use the block before as min_block, because then min_block->last_lir_instruction_id() + 2 == min_split_pos
5058 BlockBegin* min_block = allocator()->block_of_op_with_id(min_split_pos - 1);
5060 // reason for using max_split_pos - 1: otherwise there would be an assertion failure
5061 // when an interval ends at the end of the last block of the method
5062 // (in this case, max_split_pos == allocator()->max_lir_op_id() + 2, and there is no
5063 // block at this op_id)
5064 BlockBegin* max_block = allocator()->block_of_op_with_id(max_split_pos - 1);
5066 assert(min_block->linear_scan_number() <= max_block->linear_scan_number(), "invalid order");
5067 if (min_block == max_block) {
5068 // split position cannot be moved to block boundary, so split as late as possible
5069 TRACE_LINEAR_SCAN(4, tty->print_cr(" cannot move split pos to block boundary because min_pos and max_pos are in same block"));
5070 optimal_split_pos = max_split_pos;
5072 } else if (it->has_hole_between(max_split_pos - 1, max_split_pos) && !allocator()->is_block_begin(max_split_pos)) {
5073 // Do not move split position if the interval has a hole before max_split_pos.
5074 // Intervals resulting from Phi-Functions have more than one definition (marked
5075 // as mustHaveRegister) with a hole before each definition. When the register is needed
5076 // for the second definition, an earlier reloading is unnecessary.
5077 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has hole just before max_split_pos, so splitting at max_split_pos"));
5078 optimal_split_pos = max_split_pos;
5080 } else {
5081 // seach optimal block boundary between min_split_pos and max_split_pos
5082 TRACE_LINEAR_SCAN(4, tty->print_cr(" moving split pos to optimal block boundary between block B%d and B%d", min_block->block_id(), max_block->block_id()));
5084 if (do_loop_optimization) {
5085 // Loop optimization: if a loop-end marker is found between min- and max-position,
5086 // then split before this loop
5087 int loop_end_pos = it->next_usage_exact(loopEndMarker, min_block->last_lir_instruction_id() + 2);
5088 TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization: loop end found at pos %d", loop_end_pos));
5090 assert(loop_end_pos > min_split_pos, "invalid order");
5091 if (loop_end_pos < max_split_pos) {
5092 // loop-end marker found between min- and max-position
5093 // if it is not the end marker for the same loop as the min-position, then move
5094 // the max-position to this loop block.
5095 // Desired result: uses tagged as shouldHaveRegister inside a loop cause a reloading
5096 // of the interval (normally, only mustHaveRegister causes a reloading)
5097 BlockBegin* loop_block = allocator()->block_of_op_with_id(loop_end_pos);
5099 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval is used in loop that ends in block B%d, so trying to move max_block back from B%d to B%d", loop_block->block_id(), max_block->block_id(), loop_block->block_id()));
5100 assert(loop_block != min_block, "loop_block and min_block must be different because block boundary is needed between");
5102 optimal_split_pos = find_optimal_split_pos(min_block, loop_block, loop_block->last_lir_instruction_id() + 2);
5103 if (optimal_split_pos == loop_block->last_lir_instruction_id() + 2) {
5104 optimal_split_pos = -1;
5105 TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization not necessary"));
5106 } else {
5107 TRACE_LINEAR_SCAN(4, tty->print_cr(" loop optimization successful"));
5108 }
5109 }
5110 }
5112 if (optimal_split_pos == -1) {
5113 // not calculated by loop optimization
5114 optimal_split_pos = find_optimal_split_pos(min_block, max_block, max_split_pos);
5115 }
5116 }
5117 }
5118 TRACE_LINEAR_SCAN(4, tty->print_cr(" optimal split position: %d", optimal_split_pos));
5120 return optimal_split_pos;
5121 }
5124 /*
5125 split an interval at the optimal position between min_split_pos and
5126 max_split_pos in two parts:
5127 1) the left part has already a location assigned
5128 2) the right part is sorted into to the unhandled-list
5129 */
5130 void LinearScanWalker::split_before_usage(Interval* it, int min_split_pos, int max_split_pos) {
5131 TRACE_LINEAR_SCAN(2, tty->print ("----- splitting interval: "); it->print());
5132 TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));
5134 assert(it->from() < min_split_pos, "cannot split at start of interval");
5135 assert(current_position() < min_split_pos, "cannot split before current position");
5136 assert(min_split_pos <= max_split_pos, "invalid order");
5137 assert(max_split_pos <= it->to(), "cannot split after end of interval");
5139 int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, true);
5141 assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
5142 assert(optimal_split_pos <= it->to(), "cannot split after end of interval");
5143 assert(optimal_split_pos > it->from(), "cannot split at start of interval");
5145 if (optimal_split_pos == it->to() && it->next_usage(mustHaveRegister, min_split_pos) == max_jint) {
5146 // the split position would be just before the end of the interval
5147 // -> no split at all necessary
5148 TRACE_LINEAR_SCAN(4, tty->print_cr(" no split necessary because optimal split position is at end of interval"));
5149 return;
5150 }
5152 // must calculate this before the actual split is performed and before split position is moved to odd op_id
5153 bool move_necessary = !allocator()->is_block_begin(optimal_split_pos) && !it->has_hole_between(optimal_split_pos - 1, optimal_split_pos);
5155 if (!allocator()->is_block_begin(optimal_split_pos)) {
5156 // move position before actual instruction (odd op_id)
5157 optimal_split_pos = (optimal_split_pos - 1) | 1;
5158 }
5160 TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));
5161 assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
5162 assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
5164 Interval* split_part = it->split(optimal_split_pos);
5166 allocator()->append_interval(split_part);
5167 allocator()->copy_register_flags(it, split_part);
5168 split_part->set_insert_move_when_activated(move_necessary);
5169 append_to_unhandled(unhandled_first_addr(anyKind), split_part);
5171 TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts (insert_move_when_activated: %d)", move_necessary));
5172 TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());
5173 TRACE_LINEAR_SCAN(2, tty->print (" "); split_part->print());
5174 }
5176 /*
5177 split an interval at the optimal position between min_split_pos and
5178 max_split_pos in two parts:
5179 1) the left part has already a location assigned
5180 2) the right part is always on the stack and therefore ignored in further processing
5181 */
5182 void LinearScanWalker::split_for_spilling(Interval* it) {
5183 // calculate allowed range of splitting position
5184 int max_split_pos = current_position();
5185 int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, max_split_pos) + 1, it->from());
5187 TRACE_LINEAR_SCAN(2, tty->print ("----- splitting and spilling interval: "); it->print());
5188 TRACE_LINEAR_SCAN(2, tty->print_cr(" between %d and %d", min_split_pos, max_split_pos));
5190 assert(it->state() == activeState, "why spill interval that is not active?");
5191 assert(it->from() <= min_split_pos, "cannot split before start of interval");
5192 assert(min_split_pos <= max_split_pos, "invalid order");
5193 assert(max_split_pos < it->to(), "cannot split at end end of interval");
5194 assert(current_position() < it->to(), "interval must not end before current position");
5196 if (min_split_pos == it->from()) {
5197 // the whole interval is never used, so spill it entirely to memory
5198 TRACE_LINEAR_SCAN(2, tty->print_cr(" spilling entire interval because split pos is at beginning of interval"));
5199 assert(it->first_usage(shouldHaveRegister) > current_position(), "interval must not have use position before current_position");
5201 allocator()->assign_spill_slot(it);
5202 allocator()->change_spill_state(it, min_split_pos);
5204 // Also kick parent intervals out of register to memory when they have no use
5205 // position. This avoids short interval in register surrounded by intervals in
5206 // memory -> avoid useless moves from memory to register and back
5207 Interval* parent = it;
5208 while (parent != NULL && parent->is_split_child()) {
5209 parent = parent->split_child_before_op_id(parent->from());
5211 if (parent->assigned_reg() < LinearScan::nof_regs) {
5212 if (parent->first_usage(shouldHaveRegister) == max_jint) {
5213 // parent is never used, so kick it out of its assigned register
5214 TRACE_LINEAR_SCAN(4, tty->print_cr(" kicking out interval %d out of its register because it is never used", parent->reg_num()));
5215 allocator()->assign_spill_slot(parent);
5216 } else {
5217 // do not go further back because the register is actually used by the interval
5218 parent = NULL;
5219 }
5220 }
5221 }
5223 } else {
5224 // search optimal split pos, split interval and spill only the right hand part
5225 int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, false);
5227 assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
5228 assert(optimal_split_pos < it->to(), "cannot split at end of interval");
5229 assert(optimal_split_pos >= it->from(), "cannot split before start of interval");
5231 if (!allocator()->is_block_begin(optimal_split_pos)) {
5232 // move position before actual instruction (odd op_id)
5233 optimal_split_pos = (optimal_split_pos - 1) | 1;
5234 }
5236 TRACE_LINEAR_SCAN(4, tty->print_cr(" splitting at position %d", optimal_split_pos));
5237 assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
5238 assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
5240 Interval* spilled_part = it->split(optimal_split_pos);
5241 allocator()->append_interval(spilled_part);
5242 allocator()->assign_spill_slot(spilled_part);
5243 allocator()->change_spill_state(spilled_part, optimal_split_pos);
5245 if (!allocator()->is_block_begin(optimal_split_pos)) {
5246 TRACE_LINEAR_SCAN(4, tty->print_cr(" inserting move from interval %d to %d", it->reg_num(), spilled_part->reg_num()));
5247 insert_move(optimal_split_pos, it, spilled_part);
5248 }
5250 // the current_split_child is needed later when moves are inserted for reloading
5251 assert(spilled_part->current_split_child() == it, "overwriting wrong current_split_child");
5252 spilled_part->make_current_split_child();
5254 TRACE_LINEAR_SCAN(2, tty->print_cr(" split interval in two parts"));
5255 TRACE_LINEAR_SCAN(2, tty->print (" "); it->print());
5256 TRACE_LINEAR_SCAN(2, tty->print (" "); spilled_part->print());
5257 }
5258 }
5261 void LinearScanWalker::split_stack_interval(Interval* it) {
5262 int min_split_pos = current_position() + 1;
5263 int max_split_pos = MIN2(it->first_usage(shouldHaveRegister), it->to());
5265 split_before_usage(it, min_split_pos, max_split_pos);
5266 }
5268 void LinearScanWalker::split_when_partial_register_available(Interval* it, int register_available_until) {
5269 int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, register_available_until), it->from() + 1);
5270 int max_split_pos = register_available_until;
5272 split_before_usage(it, min_split_pos, max_split_pos);
5273 }
5275 void LinearScanWalker::split_and_spill_interval(Interval* it) {
5276 assert(it->state() == activeState || it->state() == inactiveState, "other states not allowed");
5278 int current_pos = current_position();
5279 if (it->state() == inactiveState) {
5280 // the interval is currently inactive, so no spill slot is needed for now.
5281 // when the split part is activated, the interval has a new chance to get a register,
5282 // so in the best case no stack slot is necessary
5283 assert(it->has_hole_between(current_pos - 1, current_pos + 1), "interval can not be inactive otherwise");
5284 split_before_usage(it, current_pos + 1, current_pos + 1);
5286 } else {
5287 // search the position where the interval must have a register and split
5288 // at the optimal position before.
5289 // The new created part is added to the unhandled list and will get a register
5290 // when it is activated
5291 int min_split_pos = current_pos + 1;
5292 int max_split_pos = MIN2(it->next_usage(mustHaveRegister, min_split_pos), it->to());
5294 split_before_usage(it, min_split_pos, max_split_pos);
5296 assert(it->next_usage(mustHaveRegister, current_pos) == max_jint, "the remaining part is spilled to stack and therefore has no register");
5297 split_for_spilling(it);
5298 }
5299 }
5302 int LinearScanWalker::find_free_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
5303 int min_full_reg = any_reg;
5304 int max_partial_reg = any_reg;
5306 for (int i = _first_reg; i <= _last_reg; i++) {
5307 if (i == ignore_reg) {
5308 // this register must be ignored
5310 } else if (_use_pos[i] >= interval_to) {
5311 // this register is free for the full interval
5312 if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
5313 min_full_reg = i;
5314 }
5315 } else if (_use_pos[i] > reg_needed_until) {
5316 // this register is at least free until reg_needed_until
5317 if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
5318 max_partial_reg = i;
5319 }
5320 }
5321 }
5323 if (min_full_reg != any_reg) {
5324 return min_full_reg;
5325 } else if (max_partial_reg != any_reg) {
5326 *need_split = true;
5327 return max_partial_reg;
5328 } else {
5329 return any_reg;
5330 }
5331 }
5333 int LinearScanWalker::find_free_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
5334 assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
5336 int min_full_reg = any_reg;
5337 int max_partial_reg = any_reg;
5339 for (int i = _first_reg; i < _last_reg; i+=2) {
5340 if (_use_pos[i] >= interval_to && _use_pos[i + 1] >= interval_to) {
5341 // this register is free for the full interval
5342 if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
5343 min_full_reg = i;
5344 }
5345 } else if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
5346 // this register is at least free until reg_needed_until
5347 if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
5348 max_partial_reg = i;
5349 }
5350 }
5351 }
5353 if (min_full_reg != any_reg) {
5354 return min_full_reg;
5355 } else if (max_partial_reg != any_reg) {
5356 *need_split = true;
5357 return max_partial_reg;
5358 } else {
5359 return any_reg;
5360 }
5361 }
5364 bool LinearScanWalker::alloc_free_reg(Interval* cur) {
5365 TRACE_LINEAR_SCAN(2, tty->print("trying to find free register for "); cur->print());
5367 init_use_lists(true);
5368 free_exclude_active_fixed();
5369 free_exclude_active_any();
5370 free_collect_inactive_fixed(cur);
5371 free_collect_inactive_any(cur);
5372 // free_collect_unhandled(fixedKind, cur);
5373 assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
5375 // _use_pos contains the start of the next interval that has this register assigned
5376 // (either as a fixed register or a normal allocated register in the past)
5377 // only intervals overlapping with cur are processed, non-overlapping invervals can be ignored safely
5378 TRACE_LINEAR_SCAN(4, tty->print_cr(" state of registers:"));
5379 TRACE_LINEAR_SCAN(4, for (int i = _first_reg; i <= _last_reg; i++) tty->print_cr(" reg %d: use_pos: %d", i, _use_pos[i]));
5381 int hint_reg, hint_regHi;
5382 Interval* register_hint = cur->register_hint();
5383 if (register_hint != NULL) {
5384 hint_reg = register_hint->assigned_reg();
5385 hint_regHi = register_hint->assigned_regHi();
5387 if (allocator()->is_precolored_cpu_interval(register_hint)) {
5388 assert(hint_reg != any_reg && hint_regHi == any_reg, "must be for fixed intervals");
5389 hint_regHi = hint_reg + 1; // connect e.g. eax-edx
5390 }
5391 TRACE_LINEAR_SCAN(4, tty->print(" hint registers %d, %d from interval ", hint_reg, hint_regHi); register_hint->print());
5393 } else {
5394 hint_reg = any_reg;
5395 hint_regHi = any_reg;
5396 }
5397 assert(hint_reg == any_reg || hint_reg != hint_regHi, "hint reg and regHi equal");
5398 assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned to interval");
5400 // the register must be free at least until this position
5401 int reg_needed_until = cur->from() + 1;
5402 int interval_to = cur->to();
5404 bool need_split = false;
5405 int split_pos = -1;
5406 int reg = any_reg;
5407 int regHi = any_reg;
5409 if (_adjacent_regs) {
5410 reg = find_free_double_reg(reg_needed_until, interval_to, hint_reg, &need_split);
5411 regHi = reg + 1;
5412 if (reg == any_reg) {
5413 return false;
5414 }
5415 split_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
5417 } else {
5418 reg = find_free_reg(reg_needed_until, interval_to, hint_reg, any_reg, &need_split);
5419 if (reg == any_reg) {
5420 return false;
5421 }
5422 split_pos = _use_pos[reg];
5424 if (_num_phys_regs == 2) {
5425 regHi = find_free_reg(reg_needed_until, interval_to, hint_regHi, reg, &need_split);
5427 if (_use_pos[reg] < interval_to && regHi == any_reg) {
5428 // do not split interval if only one register can be assigned until the split pos
5429 // (when one register is found for the whole interval, split&spill is only
5430 // performed for the hi register)
5431 return false;
5433 } else if (regHi != any_reg) {
5434 split_pos = MIN2(split_pos, _use_pos[regHi]);
5436 // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
5437 if (reg > regHi) {
5438 int temp = reg;
5439 reg = regHi;
5440 regHi = temp;
5441 }
5442 }
5443 }
5444 }
5446 cur->assign_reg(reg, regHi);
5447 TRACE_LINEAR_SCAN(2, tty->print_cr("selected register %d, %d", reg, regHi));
5449 assert(split_pos > 0, "invalid split_pos");
5450 if (need_split) {
5451 // register not available for full interval, so split it
5452 split_when_partial_register_available(cur, split_pos);
5453 }
5455 // only return true if interval is completely assigned
5456 return _num_phys_regs == 1 || regHi != any_reg;
5457 }
5460 int LinearScanWalker::find_locked_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
5461 int max_reg = any_reg;
5463 for (int i = _first_reg; i <= _last_reg; i++) {
5464 if (i == ignore_reg) {
5465 // this register must be ignored
5467 } else if (_use_pos[i] > reg_needed_until) {
5468 if (max_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_reg] && max_reg != hint_reg)) {
5469 max_reg = i;
5470 }
5471 }
5472 }
5474 if (max_reg != any_reg && _block_pos[max_reg] <= interval_to) {
5475 *need_split = true;
5476 }
5478 return max_reg;
5479 }
5481 int LinearScanWalker::find_locked_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
5482 assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
5484 int max_reg = any_reg;
5486 for (int i = _first_reg; i < _last_reg; i+=2) {
5487 if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
5488 if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {
5489 max_reg = i;
5490 }
5491 }
5492 }
5494 if (_block_pos[max_reg] <= interval_to || _block_pos[max_reg + 1] <= interval_to) {
5495 *need_split = true;
5496 }
5498 return max_reg;
5499 }
5501 void LinearScanWalker::split_and_spill_intersecting_intervals(int reg, int regHi) {
5502 assert(reg != any_reg, "no register assigned");
5504 for (int i = 0; i < _spill_intervals[reg]->length(); i++) {
5505 Interval* it = _spill_intervals[reg]->at(i);
5506 remove_from_list(it);
5507 split_and_spill_interval(it);
5508 }
5510 if (regHi != any_reg) {
5511 IntervalList* processed = _spill_intervals[reg];
5512 for (int i = 0; i < _spill_intervals[regHi]->length(); i++) {
5513 Interval* it = _spill_intervals[regHi]->at(i);
5514 if (processed->index_of(it) == -1) {
5515 remove_from_list(it);
5516 split_and_spill_interval(it);
5517 }
5518 }
5519 }
5520 }
5523 // Split an Interval and spill it to memory so that cur can be placed in a register
5524 void LinearScanWalker::alloc_locked_reg(Interval* cur) {
5525 TRACE_LINEAR_SCAN(2, tty->print("need to split and spill to get register for "); cur->print());
5527 // collect current usage of registers
5528 init_use_lists(false);
5529 spill_exclude_active_fixed();
5530 // spill_block_unhandled_fixed(cur);
5531 assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
5532 spill_block_inactive_fixed(cur);
5533 spill_collect_active_any();
5534 spill_collect_inactive_any(cur);
5536 #ifndef PRODUCT
5537 if (TraceLinearScanLevel >= 4) {
5538 tty->print_cr(" state of registers:");
5539 for (int i = _first_reg; i <= _last_reg; i++) {
5540 tty->print(" reg %d: use_pos: %d, block_pos: %d, intervals: ", i, _use_pos[i], _block_pos[i]);
5541 for (int j = 0; j < _spill_intervals[i]->length(); j++) {
5542 tty->print("%d ", _spill_intervals[i]->at(j)->reg_num());
5543 }
5544 tty->cr();
5545 }
5546 }
5547 #endif
5549 // the register must be free at least until this position
5550 int reg_needed_until = MIN2(cur->first_usage(mustHaveRegister), cur->from() + 1);
5551 int interval_to = cur->to();
5552 assert (reg_needed_until > 0 && reg_needed_until < max_jint, "interval has no use");
5554 int split_pos = 0;
5555 int use_pos = 0;
5556 bool need_split = false;
5557 int reg, regHi;
5559 if (_adjacent_regs) {
5560 reg = find_locked_double_reg(reg_needed_until, interval_to, any_reg, &need_split);
5561 regHi = reg + 1;
5563 if (reg != any_reg) {
5564 use_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
5565 split_pos = MIN2(_block_pos[reg], _block_pos[regHi]);
5566 }
5567 } else {
5568 reg = find_locked_reg(reg_needed_until, interval_to, any_reg, cur->assigned_reg(), &need_split);
5569 regHi = any_reg;
5571 if (reg != any_reg) {
5572 use_pos = _use_pos[reg];
5573 split_pos = _block_pos[reg];
5575 if (_num_phys_regs == 2) {
5576 if (cur->assigned_reg() != any_reg) {
5577 regHi = reg;
5578 reg = cur->assigned_reg();
5579 } else {
5580 regHi = find_locked_reg(reg_needed_until, interval_to, any_reg, reg, &need_split);
5581 if (regHi != any_reg) {
5582 use_pos = MIN2(use_pos, _use_pos[regHi]);
5583 split_pos = MIN2(split_pos, _block_pos[regHi]);
5584 }
5585 }
5587 if (regHi != any_reg && reg > regHi) {
5588 // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
5589 int temp = reg;
5590 reg = regHi;
5591 regHi = temp;
5592 }
5593 }
5594 }
5595 }
5597 if (reg == any_reg || (_num_phys_regs == 2 && regHi == any_reg) || use_pos <= cur->first_usage(mustHaveRegister)) {
5598 // the first use of cur is later than the spilling position -> spill cur
5599 TRACE_LINEAR_SCAN(4, tty->print_cr("able to spill current interval. first_usage(register): %d, use_pos: %d", cur->first_usage(mustHaveRegister), use_pos));
5601 if (cur->first_usage(mustHaveRegister) <= cur->from() + 1) {
5602 assert(false, "cannot spill interval that is used in first instruction (possible reason: no register found)");
5603 // assign a reasonable register and do a bailout in product mode to avoid errors
5604 allocator()->assign_spill_slot(cur);
5605 BAILOUT("LinearScan: no register found");
5606 }
5608 split_and_spill_interval(cur);
5609 } else {
5610 TRACE_LINEAR_SCAN(4, tty->print_cr("decided to use register %d, %d", reg, regHi));
5611 assert(reg != any_reg && (_num_phys_regs == 1 || regHi != any_reg), "no register found");
5612 assert(split_pos > 0, "invalid split_pos");
5613 assert(need_split == false || split_pos > cur->from(), "splitting interval at from");
5615 cur->assign_reg(reg, regHi);
5616 if (need_split) {
5617 // register not available for full interval, so split it
5618 split_when_partial_register_available(cur, split_pos);
5619 }
5621 // perform splitting and spilling for all affected intervalls
5622 split_and_spill_intersecting_intervals(reg, regHi);
5623 }
5624 }
5626 bool LinearScanWalker::no_allocation_possible(Interval* cur) {
5627 #ifdef X86
5628 // fast calculation of intervals that can never get a register because the
5629 // the next instruction is a call that blocks all registers
5630 // Note: this does not work if callee-saved registers are available (e.g. on Sparc)
5632 // check if this interval is the result of a split operation
5633 // (an interval got a register until this position)
5634 int pos = cur->from();
5635 if ((pos & 1) == 1) {
5636 // the current instruction is a call that blocks all registers
5637 if (pos < allocator()->max_lir_op_id() && allocator()->has_call(pos + 1)) {
5638 TRACE_LINEAR_SCAN(4, tty->print_cr(" free register cannot be available because all registers blocked by following call"));
5640 // safety check that there is really no register available
5641 assert(alloc_free_reg(cur) == false, "found a register for this interval");
5642 return true;
5643 }
5645 }
5646 #endif
5647 return false;
5648 }
5650 void LinearScanWalker::init_vars_for_alloc(Interval* cur) {
5651 BasicType type = cur->type();
5652 _num_phys_regs = LinearScan::num_physical_regs(type);
5653 _adjacent_regs = LinearScan::requires_adjacent_regs(type);
5655 if (pd_init_regs_for_alloc(cur)) {
5656 // the appropriate register range was selected.
5657 } else if (type == T_FLOAT || type == T_DOUBLE) {
5658 _first_reg = pd_first_fpu_reg;
5659 _last_reg = pd_last_fpu_reg;
5660 } else {
5661 _first_reg = pd_first_cpu_reg;
5662 _last_reg = FrameMap::last_cpu_reg();
5663 }
5665 assert(0 <= _first_reg && _first_reg < LinearScan::nof_regs, "out of range");
5666 assert(0 <= _last_reg && _last_reg < LinearScan::nof_regs, "out of range");
5667 }
5670 bool LinearScanWalker::is_move(LIR_Op* op, Interval* from, Interval* to) {
5671 if (op->code() != lir_move) {
5672 return false;
5673 }
5674 assert(op->as_Op1() != NULL, "move must be LIR_Op1");
5676 LIR_Opr in = ((LIR_Op1*)op)->in_opr();
5677 LIR_Opr res = ((LIR_Op1*)op)->result_opr();
5678 return in->is_virtual() && res->is_virtual() && in->vreg_number() == from->reg_num() && res->vreg_number() == to->reg_num();
5679 }
5681 // optimization (especially for phi functions of nested loops):
5682 // assign same spill slot to non-intersecting intervals
5683 void LinearScanWalker::combine_spilled_intervals(Interval* cur) {
5684 if (cur->is_split_child()) {
5685 // optimization is only suitable for split parents
5686 return;
5687 }
5689 Interval* register_hint = cur->register_hint(false);
5690 if (register_hint == NULL) {
5691 // cur is not the target of a move, otherwise register_hint would be set
5692 return;
5693 }
5694 assert(register_hint->is_split_parent(), "register hint must be split parent");
5696 if (cur->spill_state() != noOptimization || register_hint->spill_state() != noOptimization) {
5697 // combining the stack slots for intervals where spill move optimization is applied
5698 // is not benefitial and would cause problems
5699 return;
5700 }
5702 int begin_pos = cur->from();
5703 int end_pos = cur->to();
5704 if (end_pos > allocator()->max_lir_op_id() || (begin_pos & 1) != 0 || (end_pos & 1) != 0) {
5705 // safety check that lir_op_with_id is allowed
5706 return;
5707 }
5709 if (!is_move(allocator()->lir_op_with_id(begin_pos), register_hint, cur) || !is_move(allocator()->lir_op_with_id(end_pos), cur, register_hint)) {
5710 // cur and register_hint are not connected with two moves
5711 return;
5712 }
5714 Interval* begin_hint = register_hint->split_child_at_op_id(begin_pos, LIR_OpVisitState::inputMode);
5715 Interval* end_hint = register_hint->split_child_at_op_id(end_pos, LIR_OpVisitState::outputMode);
5716 if (begin_hint == end_hint || begin_hint->to() != begin_pos || end_hint->from() != end_pos) {
5717 // register_hint must be split, otherwise the re-writing of use positions does not work
5718 return;
5719 }
5721 assert(begin_hint->assigned_reg() != any_reg, "must have register assigned");
5722 assert(end_hint->assigned_reg() == any_reg, "must not have register assigned");
5723 assert(cur->first_usage(mustHaveRegister) == begin_pos, "must have use position at begin of interval because of move");
5724 assert(end_hint->first_usage(mustHaveRegister) == end_pos, "must have use position at begin of interval because of move");
5726 if (begin_hint->assigned_reg() < LinearScan::nof_regs) {
5727 // register_hint is not spilled at begin_pos, so it would not be benefitial to immediately spill cur
5728 return;
5729 }
5730 assert(register_hint->canonical_spill_slot() != -1, "must be set when part of interval was spilled");
5732 // modify intervals such that cur gets the same stack slot as register_hint
5733 // delete use positions to prevent the intervals to get a register at beginning
5734 cur->set_canonical_spill_slot(register_hint->canonical_spill_slot());
5735 cur->remove_first_use_pos();
5736 end_hint->remove_first_use_pos();
5737 }
5740 // allocate a physical register or memory location to an interval
5741 bool LinearScanWalker::activate_current() {
5742 Interval* cur = current();
5743 bool result = true;
5745 TRACE_LINEAR_SCAN(2, tty->print ("+++++ activating interval "); cur->print());
5746 TRACE_LINEAR_SCAN(4, tty->print_cr(" split_parent: %d, insert_move_when_activated: %d", cur->split_parent()->reg_num(), cur->insert_move_when_activated()));
5748 if (cur->assigned_reg() >= LinearScan::nof_regs) {
5749 // activating an interval that has a stack slot assigned -> split it at first use position
5750 // used for method parameters
5751 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval has spill slot assigned (method parameter) -> split it before first use"));
5753 split_stack_interval(cur);
5754 result = false;
5756 } else if (allocator()->gen()->is_vreg_flag_set(cur->reg_num(), LIRGenerator::must_start_in_memory)) {
5757 // activating an interval that must start in a stack slot, but may get a register later
5758 // used for lir_roundfp: rounding is done by store to stack and reload later
5759 TRACE_LINEAR_SCAN(4, tty->print_cr(" interval must start in stack slot -> split it before first use"));
5760 assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned");
5762 allocator()->assign_spill_slot(cur);
5763 split_stack_interval(cur);
5764 result = false;
5766 } else if (cur->assigned_reg() == any_reg) {
5767 // interval has not assigned register -> normal allocation
5768 // (this is the normal case for most intervals)
5769 TRACE_LINEAR_SCAN(4, tty->print_cr(" normal allocation of register"));
5771 // assign same spill slot to non-intersecting intervals
5772 combine_spilled_intervals(cur);
5774 init_vars_for_alloc(cur);
5775 if (no_allocation_possible(cur) || !alloc_free_reg(cur)) {
5776 // no empty register available.
5777 // split and spill another interval so that this interval gets a register
5778 alloc_locked_reg(cur);
5779 }
5781 // spilled intervals need not be move to active-list
5782 if (cur->assigned_reg() >= LinearScan::nof_regs) {
5783 result = false;
5784 }
5785 }
5787 // load spilled values that become active from stack slot to register
5788 if (cur->insert_move_when_activated()) {
5789 assert(cur->is_split_child(), "must be");
5790 assert(cur->current_split_child() != NULL, "must be");
5791 assert(cur->current_split_child()->reg_num() != cur->reg_num(), "cannot insert move between same interval");
5792 TRACE_LINEAR_SCAN(4, tty->print_cr("Inserting move from interval %d to %d because insert_move_when_activated is set", cur->current_split_child()->reg_num(), cur->reg_num()));
5794 insert_move(cur->from(), cur->current_split_child(), cur);
5795 }
5796 cur->make_current_split_child();
5798 return result; // true = interval is moved to active list
5799 }
5802 // Implementation of EdgeMoveOptimizer
5804 EdgeMoveOptimizer::EdgeMoveOptimizer() :
5805 _edge_instructions(4),
5806 _edge_instructions_idx(4)
5807 {
5808 }
5810 void EdgeMoveOptimizer::optimize(BlockList* code) {
5811 EdgeMoveOptimizer optimizer = EdgeMoveOptimizer();
5813 // ignore the first block in the list (index 0 is not processed)
5814 for (int i = code->length() - 1; i >= 1; i--) {
5815 BlockBegin* block = code->at(i);
5817 if (block->number_of_preds() > 1 && !block->is_set(BlockBegin::exception_entry_flag)) {
5818 optimizer.optimize_moves_at_block_end(block);
5819 }
5820 if (block->number_of_sux() == 2) {
5821 optimizer.optimize_moves_at_block_begin(block);
5822 }
5823 }
5824 }
5827 // clear all internal data structures
5828 void EdgeMoveOptimizer::init_instructions() {
5829 _edge_instructions.clear();
5830 _edge_instructions_idx.clear();
5831 }
5833 // append a lir-instruction-list and the index of the current operation in to the list
5834 void EdgeMoveOptimizer::append_instructions(LIR_OpList* instructions, int instructions_idx) {
5835 _edge_instructions.append(instructions);
5836 _edge_instructions_idx.append(instructions_idx);
5837 }
5839 // return the current operation of the given edge (predecessor or successor)
5840 LIR_Op* EdgeMoveOptimizer::instruction_at(int edge) {
5841 LIR_OpList* instructions = _edge_instructions.at(edge);
5842 int idx = _edge_instructions_idx.at(edge);
5844 if (idx < instructions->length()) {
5845 return instructions->at(idx);
5846 } else {
5847 return NULL;
5848 }
5849 }
5851 // removes the current operation of the given edge (predecessor or successor)
5852 void EdgeMoveOptimizer::remove_cur_instruction(int edge, bool decrement_index) {
5853 LIR_OpList* instructions = _edge_instructions.at(edge);
5854 int idx = _edge_instructions_idx.at(edge);
5855 instructions->remove_at(idx);
5857 if (decrement_index) {
5858 _edge_instructions_idx.at_put(edge, idx - 1);
5859 }
5860 }
5863 bool EdgeMoveOptimizer::operations_different(LIR_Op* op1, LIR_Op* op2) {
5864 if (op1 == NULL || op2 == NULL) {
5865 // at least one block is already empty -> no optimization possible
5866 return true;
5867 }
5869 if (op1->code() == lir_move && op2->code() == lir_move) {
5870 assert(op1->as_Op1() != NULL, "move must be LIR_Op1");
5871 assert(op2->as_Op1() != NULL, "move must be LIR_Op1");
5872 LIR_Op1* move1 = (LIR_Op1*)op1;
5873 LIR_Op1* move2 = (LIR_Op1*)op2;
5874 if (move1->info() == move2->info() && move1->in_opr() == move2->in_opr() && move1->result_opr() == move2->result_opr()) {
5875 // these moves are exactly equal and can be optimized
5876 return false;
5877 }
5879 } else if (op1->code() == lir_fxch && op2->code() == lir_fxch) {
5880 assert(op1->as_Op1() != NULL, "fxch must be LIR_Op1");
5881 assert(op2->as_Op1() != NULL, "fxch must be LIR_Op1");
5882 LIR_Op1* fxch1 = (LIR_Op1*)op1;
5883 LIR_Op1* fxch2 = (LIR_Op1*)op2;
5884 if (fxch1->in_opr()->as_jint() == fxch2->in_opr()->as_jint()) {
5885 // equal FPU stack operations can be optimized
5886 return false;
5887 }
5889 } else if (op1->code() == lir_fpop_raw && op2->code() == lir_fpop_raw) {
5890 // equal FPU stack operations can be optimized
5891 return false;
5892 }
5894 // no optimization possible
5895 return true;
5896 }
5898 void EdgeMoveOptimizer::optimize_moves_at_block_end(BlockBegin* block) {
5899 TRACE_LINEAR_SCAN(4, tty->print_cr("optimizing moves at end of block B%d", block->block_id()));
5901 if (block->is_predecessor(block)) {
5902 // currently we can't handle this correctly.
5903 return;
5904 }
5906 init_instructions();
5907 int num_preds = block->number_of_preds();
5908 assert(num_preds > 1, "do not call otherwise");
5909 assert(!block->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
5911 // setup a list with the lir-instructions of all predecessors
5912 int i;
5913 for (i = 0; i < num_preds; i++) {
5914 BlockBegin* pred = block->pred_at(i);
5915 LIR_OpList* pred_instructions = pred->lir()->instructions_list();
5917 if (pred->number_of_sux() != 1) {
5918 // this can happen with switch-statements where multiple edges are between
5919 // the same blocks.
5920 return;
5921 }
5923 assert(pred->number_of_sux() == 1, "can handle only one successor");
5924 assert(pred->sux_at(0) == block, "invalid control flow");
5925 assert(pred_instructions->last()->code() == lir_branch, "block with successor must end with branch");
5926 assert(pred_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
5927 assert(pred_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
5929 if (pred_instructions->last()->info() != NULL) {
5930 // can not optimize instructions when debug info is needed
5931 return;
5932 }
5934 // ignore the unconditional branch at the end of the block
5935 append_instructions(pred_instructions, pred_instructions->length() - 2);
5936 }
5939 // process lir-instructions while all predecessors end with the same instruction
5940 while (true) {
5941 LIR_Op* op = instruction_at(0);
5942 for (i = 1; i < num_preds; i++) {
5943 if (operations_different(op, instruction_at(i))) {
5944 // these instructions are different and cannot be optimized ->
5945 // no further optimization possible
5946 return;
5947 }
5948 }
5950 TRACE_LINEAR_SCAN(4, tty->print("found instruction that is equal in all %d predecessors: ", num_preds); op->print());
5952 // insert the instruction at the beginning of the current block
5953 block->lir()->insert_before(1, op);
5955 // delete the instruction at the end of all predecessors
5956 for (i = 0; i < num_preds; i++) {
5957 remove_cur_instruction(i, true);
5958 }
5959 }
5960 }
5963 void EdgeMoveOptimizer::optimize_moves_at_block_begin(BlockBegin* block) {
5964 TRACE_LINEAR_SCAN(4, tty->print_cr("optimization moves at begin of block B%d", block->block_id()));
5966 init_instructions();
5967 int num_sux = block->number_of_sux();
5969 LIR_OpList* cur_instructions = block->lir()->instructions_list();
5971 assert(num_sux == 2, "method should not be called otherwise");
5972 assert(cur_instructions->last()->code() == lir_branch, "block with successor must end with branch");
5973 assert(cur_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
5974 assert(cur_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
5976 if (cur_instructions->last()->info() != NULL) {
5977 // can no optimize instructions when debug info is needed
5978 return;
5979 }
5981 LIR_Op* branch = cur_instructions->at(cur_instructions->length() - 2);
5982 if (branch->info() != NULL || (branch->code() != lir_branch && branch->code() != lir_cond_float_branch)) {
5983 // not a valid case for optimization
5984 // currently, only blocks that end with two branches (conditional branch followed
5985 // by unconditional branch) are optimized
5986 return;
5987 }
5989 // now it is guaranteed that the block ends with two branch instructions.
5990 // the instructions are inserted at the end of the block before these two branches
5991 int insert_idx = cur_instructions->length() - 2;
5993 int i;
5994 #ifdef ASSERT
5995 for (i = insert_idx - 1; i >= 0; i--) {
5996 LIR_Op* op = cur_instructions->at(i);
5997 if ((op->code() == lir_branch || op->code() == lir_cond_float_branch) && ((LIR_OpBranch*)op)->block() != NULL) {
5998 assert(false, "block with two successors can have only two branch instructions");
5999 }
6000 }
6001 #endif
6003 // setup a list with the lir-instructions of all successors
6004 for (i = 0; i < num_sux; i++) {
6005 BlockBegin* sux = block->sux_at(i);
6006 LIR_OpList* sux_instructions = sux->lir()->instructions_list();
6008 assert(sux_instructions->at(0)->code() == lir_label, "block must start with label");
6010 if (sux->number_of_preds() != 1) {
6011 // this can happen with switch-statements where multiple edges are between
6012 // the same blocks.
6013 return;
6014 }
6015 assert(sux->pred_at(0) == block, "invalid control flow");
6016 assert(!sux->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
6018 // ignore the label at the beginning of the block
6019 append_instructions(sux_instructions, 1);
6020 }
6022 // process lir-instructions while all successors begin with the same instruction
6023 while (true) {
6024 LIR_Op* op = instruction_at(0);
6025 for (i = 1; i < num_sux; i++) {
6026 if (operations_different(op, instruction_at(i))) {
6027 // these instructions are different and cannot be optimized ->
6028 // no further optimization possible
6029 return;
6030 }
6031 }
6033 TRACE_LINEAR_SCAN(4, tty->print("----- found instruction that is equal in all %d successors: ", num_sux); op->print());
6035 // insert instruction at end of current block
6036 block->lir()->insert_before(insert_idx, op);
6037 insert_idx++;
6039 // delete the instructions at the beginning of all successors
6040 for (i = 0; i < num_sux; i++) {
6041 remove_cur_instruction(i, false);
6042 }
6043 }
6044 }
6047 // Implementation of ControlFlowOptimizer
6049 ControlFlowOptimizer::ControlFlowOptimizer() :
6050 _original_preds(4)
6051 {
6052 }
6054 void ControlFlowOptimizer::optimize(BlockList* code) {
6055 ControlFlowOptimizer optimizer = ControlFlowOptimizer();
6057 // push the OSR entry block to the end so that we're not jumping over it.
6058 BlockBegin* osr_entry = code->at(0)->end()->as_Base()->osr_entry();
6059 if (osr_entry) {
6060 int index = osr_entry->linear_scan_number();
6061 assert(code->at(index) == osr_entry, "wrong index");
6062 code->remove_at(index);
6063 code->append(osr_entry);
6064 }
6066 optimizer.reorder_short_loops(code);
6067 optimizer.delete_empty_blocks(code);
6068 optimizer.delete_unnecessary_jumps(code);
6069 optimizer.delete_jumps_to_return(code);
6070 }
6072 void ControlFlowOptimizer::reorder_short_loop(BlockList* code, BlockBegin* header_block, int header_idx) {
6073 int i = header_idx + 1;
6074 int max_end = MIN2(header_idx + ShortLoopSize, code->length());
6075 while (i < max_end && code->at(i)->loop_depth() >= header_block->loop_depth()) {
6076 i++;
6077 }
6079 if (i == code->length() || code->at(i)->loop_depth() < header_block->loop_depth()) {
6080 int end_idx = i - 1;
6081 BlockBegin* end_block = code->at(end_idx);
6083 if (end_block->number_of_sux() == 1 && end_block->sux_at(0) == header_block) {
6084 // short loop from header_idx to end_idx found -> reorder blocks such that
6085 // the header_block is the last block instead of the first block of the loop
6086 TRACE_LINEAR_SCAN(1, tty->print_cr("Reordering short loop: length %d, header B%d, end B%d",
6087 end_idx - header_idx + 1,
6088 header_block->block_id(), end_block->block_id()));
6090 for (int j = header_idx; j < end_idx; j++) {
6091 code->at_put(j, code->at(j + 1));
6092 }
6093 code->at_put(end_idx, header_block);
6095 // correct the flags so that any loop alignment occurs in the right place.
6096 assert(code->at(end_idx)->is_set(BlockBegin::backward_branch_target_flag), "must be backward branch target");
6097 code->at(end_idx)->clear(BlockBegin::backward_branch_target_flag);
6098 code->at(header_idx)->set(BlockBegin::backward_branch_target_flag);
6099 }
6100 }
6101 }
6103 void ControlFlowOptimizer::reorder_short_loops(BlockList* code) {
6104 for (int i = code->length() - 1; i >= 0; i--) {
6105 BlockBegin* block = code->at(i);
6107 if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {
6108 reorder_short_loop(code, block, i);
6109 }
6110 }
6112 DEBUG_ONLY(verify(code));
6113 }
6115 // only blocks with exactly one successor can be deleted. Such blocks
6116 // must always end with an unconditional branch to this successor
6117 bool ControlFlowOptimizer::can_delete_block(BlockBegin* block) {
6118 if (block->number_of_sux() != 1 || block->number_of_exception_handlers() != 0 || block->is_entry_block()) {
6119 return false;
6120 }
6122 LIR_OpList* instructions = block->lir()->instructions_list();
6124 assert(instructions->length() >= 2, "block must have label and branch");
6125 assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
6126 assert(instructions->last()->as_OpBranch() != NULL, "last instrcution must always be a branch");
6127 assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "branch must be unconditional");
6128 assert(instructions->last()->as_OpBranch()->block() == block->sux_at(0), "branch target must be the successor");
6130 // block must have exactly one successor
6132 if (instructions->length() == 2 && instructions->last()->info() == NULL) {
6133 return true;
6134 }
6135 return false;
6136 }
6138 // substitute branch targets in all branch-instructions of this blocks
6139 void ControlFlowOptimizer::substitute_branch_target(BlockBegin* block, BlockBegin* target_from, BlockBegin* target_to) {
6140 TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting empty block: substituting from B%d to B%d inside B%d", target_from->block_id(), target_to->block_id(), block->block_id()));
6142 LIR_OpList* instructions = block->lir()->instructions_list();
6144 assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
6145 for (int i = instructions->length() - 1; i >= 1; i--) {
6146 LIR_Op* op = instructions->at(i);
6148 if (op->code() == lir_branch || op->code() == lir_cond_float_branch) {
6149 assert(op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
6150 LIR_OpBranch* branch = (LIR_OpBranch*)op;
6152 if (branch->block() == target_from) {
6153 branch->change_block(target_to);
6154 }
6155 if (branch->ublock() == target_from) {
6156 branch->change_ublock(target_to);
6157 }
6158 }
6159 }
6160 }
6162 void ControlFlowOptimizer::delete_empty_blocks(BlockList* code) {
6163 int old_pos = 0;
6164 int new_pos = 0;
6165 int num_blocks = code->length();
6167 while (old_pos < num_blocks) {
6168 BlockBegin* block = code->at(old_pos);
6170 if (can_delete_block(block)) {
6171 BlockBegin* new_target = block->sux_at(0);
6173 // propagate backward branch target flag for correct code alignment
6174 if (block->is_set(BlockBegin::backward_branch_target_flag)) {
6175 new_target->set(BlockBegin::backward_branch_target_flag);
6176 }
6178 // collect a list with all predecessors that contains each predecessor only once
6179 // the predecessors of cur are changed during the substitution, so a copy of the
6180 // predecessor list is necessary
6181 int j;
6182 _original_preds.clear();
6183 for (j = block->number_of_preds() - 1; j >= 0; j--) {
6184 BlockBegin* pred = block->pred_at(j);
6185 if (_original_preds.index_of(pred) == -1) {
6186 _original_preds.append(pred);
6187 }
6188 }
6190 for (j = _original_preds.length() - 1; j >= 0; j--) {
6191 BlockBegin* pred = _original_preds.at(j);
6192 substitute_branch_target(pred, block, new_target);
6193 pred->substitute_sux(block, new_target);
6194 }
6195 } else {
6196 // adjust position of this block in the block list if blocks before
6197 // have been deleted
6198 if (new_pos != old_pos) {
6199 code->at_put(new_pos, code->at(old_pos));
6200 }
6201 new_pos++;
6202 }
6203 old_pos++;
6204 }
6205 code->truncate(new_pos);
6207 DEBUG_ONLY(verify(code));
6208 }
6210 void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) {
6211 // skip the last block because there a branch is always necessary
6212 for (int i = code->length() - 2; i >= 0; i--) {
6213 BlockBegin* block = code->at(i);
6214 LIR_OpList* instructions = block->lir()->instructions_list();
6216 LIR_Op* last_op = instructions->last();
6217 if (last_op->code() == lir_branch) {
6218 assert(last_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
6219 LIR_OpBranch* last_branch = (LIR_OpBranch*)last_op;
6221 assert(last_branch->block() != NULL, "last branch must always have a block as target");
6222 assert(last_branch->label() == last_branch->block()->label(), "must be equal");
6224 if (last_branch->info() == NULL) {
6225 if (last_branch->block() == code->at(i + 1)) {
6227 TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting unconditional branch at end of block B%d", block->block_id()));
6229 // delete last branch instruction
6230 instructions->truncate(instructions->length() - 1);
6232 } else {
6233 LIR_Op* prev_op = instructions->at(instructions->length() - 2);
6234 if (prev_op->code() == lir_branch || prev_op->code() == lir_cond_float_branch) {
6235 assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
6236 LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;
6238 if (prev_branch->stub() == NULL) {
6240 #ifndef MIPS64 //MIPS64 not support lir_cmp. same as openjdk6.
6241 LIR_Op2* prev_cmp = NULL;
6243 for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {
6244 prev_op = instructions->at(j);
6245 if (prev_op->code() == lir_cmp) {
6246 assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");
6247 prev_cmp = (LIR_Op2*)prev_op;
6248 assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");
6249 }
6250 }
6251 assert(prev_cmp != NULL, "should have found comp instruction for branch");
6252 #endif
6253 if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {
6255 TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));
6257 // eliminate a conditional branch to the immediate successor
6258 prev_branch->change_block(last_branch->block());
6259 prev_branch->negate_cond();
6260 #ifndef MIPS64 //MIPS64 not support lir_cmp. same as openjdk6.
6261 prev_cmp->set_condition(prev_branch->cond());
6262 #endif
6263 instructions->truncate(instructions->length() - 1);
6264 }
6265 }
6266 }
6267 }
6268 }
6269 }
6270 }
6272 DEBUG_ONLY(verify(code));
6273 }
6275 void ControlFlowOptimizer::delete_jumps_to_return(BlockList* code) {
6276 #ifdef ASSERT
6277 BitMap return_converted(BlockBegin::number_of_blocks());
6278 return_converted.clear();
6279 #endif
6281 for (int i = code->length() - 1; i >= 0; i--) {
6282 BlockBegin* block = code->at(i);
6283 LIR_OpList* cur_instructions = block->lir()->instructions_list();
6284 LIR_Op* cur_last_op = cur_instructions->last();
6286 assert(cur_instructions->at(0)->code() == lir_label, "first instruction must always be a label");
6287 if (cur_instructions->length() == 2 && cur_last_op->code() == lir_return) {
6288 // the block contains only a label and a return
6289 // if a predecessor ends with an unconditional jump to this block, then the jump
6290 // can be replaced with a return instruction
6291 //
6292 // Note: the original block with only a return statement cannot be deleted completely
6293 // because the predecessors might have other (conditional) jumps to this block
6294 // -> this may lead to unnecesary return instructions in the final code
6296 assert(cur_last_op->info() == NULL, "return instructions do not have debug information");
6297 assert(block->number_of_sux() == 0 ||
6298 (return_converted.at(block->block_id()) && block->number_of_sux() == 1),
6299 "blocks that end with return must not have successors");
6301 assert(cur_last_op->as_Op1() != NULL, "return must be LIR_Op1");
6302 LIR_Opr return_opr = ((LIR_Op1*)cur_last_op)->in_opr();
6304 for (int j = block->number_of_preds() - 1; j >= 0; j--) {
6305 BlockBegin* pred = block->pred_at(j);
6306 LIR_OpList* pred_instructions = pred->lir()->instructions_list();
6307 LIR_Op* pred_last_op = pred_instructions->last();
6309 if (pred_last_op->code() == lir_branch) {
6310 assert(pred_last_op->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
6311 LIR_OpBranch* pred_last_branch = (LIR_OpBranch*)pred_last_op;
6313 if (pred_last_branch->block() == block && pred_last_branch->cond() == lir_cond_always && pred_last_branch->info() == NULL) {
6314 // replace the jump to a return with a direct return
6315 // Note: currently the edge between the blocks is not deleted
6316 pred_instructions->at_put(pred_instructions->length() - 1, new LIR_Op1(lir_return, return_opr));
6317 #ifdef ASSERT
6318 return_converted.set_bit(pred->block_id());
6319 #endif
6320 }
6321 }
6322 }
6323 }
6324 }
6325 }
6328 #ifdef ASSERT
6329 void ControlFlowOptimizer::verify(BlockList* code) {
6330 for (int i = 0; i < code->length(); i++) {
6331 BlockBegin* block = code->at(i);
6332 LIR_OpList* instructions = block->lir()->instructions_list();
6334 int j;
6335 for (j = 0; j < instructions->length(); j++) {
6336 LIR_OpBranch* op_branch = instructions->at(j)->as_OpBranch();
6338 if (op_branch != NULL) {
6339 assert(op_branch->block() == NULL || code->index_of(op_branch->block()) != -1, "branch target not valid");
6340 assert(op_branch->ublock() == NULL || code->index_of(op_branch->ublock()) != -1, "branch target not valid");
6341 }
6342 }
6344 for (j = 0; j < block->number_of_sux() - 1; j++) {
6345 BlockBegin* sux = block->sux_at(j);
6346 assert(code->index_of(sux) != -1, "successor not valid");
6347 }
6349 for (j = 0; j < block->number_of_preds() - 1; j++) {
6350 BlockBegin* pred = block->pred_at(j);
6351 assert(code->index_of(pred) != -1, "successor not valid");
6352 }
6353 }
6354 }
6355 #endif
6358 #ifndef PRODUCT
6360 // Implementation of LinearStatistic
6362 const char* LinearScanStatistic::counter_name(int counter_idx) {
6363 switch (counter_idx) {
6364 case counter_method: return "compiled methods";
6365 case counter_fpu_method: return "methods using fpu";
6366 case counter_loop_method: return "methods with loops";
6367 case counter_exception_method:return "methods with xhandler";
6369 case counter_loop: return "loops";
6370 case counter_block: return "blocks";
6371 case counter_loop_block: return "blocks inside loop";
6372 case counter_exception_block: return "exception handler entries";
6373 case counter_interval: return "intervals";
6374 case counter_fixed_interval: return "fixed intervals";
6375 case counter_range: return "ranges";
6376 case counter_fixed_range: return "fixed ranges";
6377 case counter_use_pos: return "use positions";
6378 case counter_fixed_use_pos: return "fixed use positions";
6379 case counter_spill_slots: return "spill slots";
6381 // counter for classes of lir instructions
6382 case counter_instruction: return "total instructions";
6383 case counter_label: return "labels";
6384 case counter_entry: return "method entries";
6385 case counter_return: return "method returns";
6386 case counter_call: return "method calls";
6387 case counter_move: return "moves";
6388 case counter_cmp: return "compare";
6389 case counter_cond_branch: return "conditional branches";
6390 case counter_uncond_branch: return "unconditional branches";
6391 case counter_stub_branch: return "branches to stub";
6392 case counter_alu: return "artithmetic + logic";
6393 case counter_alloc: return "allocations";
6394 case counter_sync: return "synchronisation";
6395 case counter_throw: return "throw";
6396 case counter_unwind: return "unwind";
6397 case counter_typecheck: return "type+null-checks";
6398 case counter_fpu_stack: return "fpu-stack";
6399 case counter_misc_inst: return "other instructions";
6400 case counter_other_inst: return "misc. instructions";
6402 // counter for different types of moves
6403 case counter_move_total: return "total moves";
6404 case counter_move_reg_reg: return "register->register";
6405 case counter_move_reg_stack: return "register->stack";
6406 case counter_move_stack_reg: return "stack->register";
6407 case counter_move_stack_stack:return "stack->stack";
6408 case counter_move_reg_mem: return "register->memory";
6409 case counter_move_mem_reg: return "memory->register";
6410 case counter_move_const_any: return "constant->any";
6412 case blank_line_1: return "";
6413 case blank_line_2: return "";
6415 default: ShouldNotReachHere(); return "";
6416 }
6417 }
6419 LinearScanStatistic::Counter LinearScanStatistic::base_counter(int counter_idx) {
6420 if (counter_idx == counter_fpu_method || counter_idx == counter_loop_method || counter_idx == counter_exception_method) {
6421 return counter_method;
6422 } else if (counter_idx == counter_loop_block || counter_idx == counter_exception_block) {
6423 return counter_block;
6424 } else if (counter_idx >= counter_instruction && counter_idx <= counter_other_inst) {
6425 return counter_instruction;
6426 } else if (counter_idx >= counter_move_total && counter_idx <= counter_move_const_any) {
6427 return counter_move_total;
6428 }
6429 return invalid_counter;
6430 }
6432 LinearScanStatistic::LinearScanStatistic() {
6433 for (int i = 0; i < number_of_counters; i++) {
6434 _counters_sum[i] = 0;
6435 _counters_max[i] = -1;
6436 }
6438 }
6440 // add the method-local numbers to the total sum
6441 void LinearScanStatistic::sum_up(LinearScanStatistic &method_statistic) {
6442 for (int i = 0; i < number_of_counters; i++) {
6443 _counters_sum[i] += method_statistic._counters_sum[i];
6444 _counters_max[i] = MAX2(_counters_max[i], method_statistic._counters_sum[i]);
6445 }
6446 }
6448 void LinearScanStatistic::print(const char* title) {
6449 if (CountLinearScan || TraceLinearScanLevel > 0) {
6450 tty->cr();
6451 tty->print_cr("***** LinearScan statistic - %s *****", title);
6453 for (int i = 0; i < number_of_counters; i++) {
6454 if (_counters_sum[i] > 0 || _counters_max[i] >= 0) {
6455 tty->print("%25s: %8d", counter_name(i), _counters_sum[i]);
6457 if (base_counter(i) != invalid_counter) {
6458 tty->print(" (%5.1f%%) ", _counters_sum[i] * 100.0 / _counters_sum[base_counter(i)]);
6459 } else {
6460 tty->print(" ");
6461 }
6463 if (_counters_max[i] >= 0) {
6464 tty->print("%8d", _counters_max[i]);
6465 }
6466 }
6467 tty->cr();
6468 }
6469 }
6470 }
6472 void LinearScanStatistic::collect(LinearScan* allocator) {
6473 inc_counter(counter_method);
6474 if (allocator->has_fpu_registers()) {
6475 inc_counter(counter_fpu_method);
6476 }
6477 if (allocator->num_loops() > 0) {
6478 inc_counter(counter_loop_method);
6479 }
6480 inc_counter(counter_loop, allocator->num_loops());
6481 inc_counter(counter_spill_slots, allocator->max_spills());
6483 int i;
6484 for (i = 0; i < allocator->interval_count(); i++) {
6485 Interval* cur = allocator->interval_at(i);
6487 if (cur != NULL) {
6488 inc_counter(counter_interval);
6489 inc_counter(counter_use_pos, cur->num_use_positions());
6490 if (LinearScan::is_precolored_interval(cur)) {
6491 inc_counter(counter_fixed_interval);
6492 inc_counter(counter_fixed_use_pos, cur->num_use_positions());
6493 }
6495 Range* range = cur->first();
6496 while (range != Range::end()) {
6497 inc_counter(counter_range);
6498 if (LinearScan::is_precolored_interval(cur)) {
6499 inc_counter(counter_fixed_range);
6500 }
6501 range = range->next();
6502 }
6503 }
6504 }
6506 bool has_xhandlers = false;
6507 // Note: only count blocks that are in code-emit order
6508 for (i = 0; i < allocator->ir()->code()->length(); i++) {
6509 BlockBegin* cur = allocator->ir()->code()->at(i);
6511 inc_counter(counter_block);
6512 if (cur->loop_depth() > 0) {
6513 inc_counter(counter_loop_block);
6514 }
6515 if (cur->is_set(BlockBegin::exception_entry_flag)) {
6516 inc_counter(counter_exception_block);
6517 has_xhandlers = true;
6518 }
6520 LIR_OpList* instructions = cur->lir()->instructions_list();
6521 for (int j = 0; j < instructions->length(); j++) {
6522 LIR_Op* op = instructions->at(j);
6524 inc_counter(counter_instruction);
6526 switch (op->code()) {
6527 case lir_label: inc_counter(counter_label); break;
6528 case lir_std_entry:
6529 case lir_osr_entry: inc_counter(counter_entry); break;
6530 case lir_return: inc_counter(counter_return); break;
6532 case lir_rtcall:
6533 case lir_static_call:
6534 case lir_optvirtual_call:
6535 case lir_virtual_call: inc_counter(counter_call); break;
6537 case lir_move: {
6538 inc_counter(counter_move);
6539 inc_counter(counter_move_total);
6541 LIR_Opr in = op->as_Op1()->in_opr();
6542 LIR_Opr res = op->as_Op1()->result_opr();
6543 if (in->is_register()) {
6544 if (res->is_register()) {
6545 inc_counter(counter_move_reg_reg);
6546 } else if (res->is_stack()) {
6547 inc_counter(counter_move_reg_stack);
6548 } else if (res->is_address()) {
6549 inc_counter(counter_move_reg_mem);
6550 } else {
6551 ShouldNotReachHere();
6552 }
6553 } else if (in->is_stack()) {
6554 if (res->is_register()) {
6555 inc_counter(counter_move_stack_reg);
6556 } else {
6557 inc_counter(counter_move_stack_stack);
6558 }
6559 } else if (in->is_address()) {
6560 assert(res->is_register(), "must be");
6561 inc_counter(counter_move_mem_reg);
6562 } else if (in->is_constant()) {
6563 inc_counter(counter_move_const_any);
6564 } else {
6565 ShouldNotReachHere();
6566 }
6567 break;
6568 }
6570 #ifndef MIPS64
6571 case lir_cmp: inc_counter(counter_cmp); break;
6573 #endif
6574 case lir_branch:
6575 case lir_cond_float_branch: {
6576 LIR_OpBranch* branch = op->as_OpBranch();
6577 if (branch->block() == NULL) {
6578 inc_counter(counter_stub_branch);
6579 } else if (branch->cond() == lir_cond_always) {
6580 inc_counter(counter_uncond_branch);
6581 } else {
6582 inc_counter(counter_cond_branch);
6583 }
6584 break;
6585 }
6587 case lir_neg:
6588 case lir_add:
6589 case lir_sub:
6590 case lir_mul:
6591 case lir_mul_strictfp:
6592 case lir_div:
6593 case lir_div_strictfp:
6594 case lir_rem:
6595 case lir_sqrt:
6596 case lir_sin:
6597 case lir_cos:
6598 case lir_abs:
6599 case lir_log10:
6600 case lir_log:
6601 case lir_pow:
6602 case lir_exp:
6603 case lir_logic_and:
6604 case lir_logic_or:
6605 case lir_logic_xor:
6606 case lir_shl:
6607 case lir_shr:
6608 case lir_ushr: inc_counter(counter_alu); break;
6610 case lir_alloc_object:
6611 case lir_alloc_array: inc_counter(counter_alloc); break;
6613 case lir_monaddr:
6614 case lir_lock:
6615 case lir_unlock: inc_counter(counter_sync); break;
6617 case lir_throw: inc_counter(counter_throw); break;
6619 case lir_unwind: inc_counter(counter_unwind); break;
6621 case lir_null_check:
6622 case lir_leal:
6623 case lir_instanceof:
6624 case lir_checkcast:
6625 case lir_store_check: inc_counter(counter_typecheck); break;
6627 case lir_fpop_raw:
6628 case lir_fxch:
6629 case lir_fld: inc_counter(counter_fpu_stack); break;
6631 case lir_nop:
6632 case lir_push:
6633 case lir_pop:
6634 case lir_convert:
6635 case lir_roundfp:
6636 case lir_cmove: inc_counter(counter_misc_inst); break;
6638 default: inc_counter(counter_other_inst); break;
6639 }
6640 }
6641 }
6643 if (has_xhandlers) {
6644 inc_counter(counter_exception_method);
6645 }
6646 }
6648 void LinearScanStatistic::compute(LinearScan* allocator, LinearScanStatistic &global_statistic) {
6649 if (CountLinearScan || TraceLinearScanLevel > 0) {
6651 LinearScanStatistic local_statistic = LinearScanStatistic();
6653 local_statistic.collect(allocator);
6654 global_statistic.sum_up(local_statistic);
6656 if (TraceLinearScanLevel > 2) {
6657 local_statistic.print("current local statistic");
6658 }
6659 }
6660 }
6663 // Implementation of LinearTimers
6665 LinearScanTimers::LinearScanTimers() {
6666 for (int i = 0; i < number_of_timers; i++) {
6667 timer(i)->reset();
6668 }
6669 }
6671 const char* LinearScanTimers::timer_name(int idx) {
6672 switch (idx) {
6673 case timer_do_nothing: return "Nothing (Time Check)";
6674 case timer_number_instructions: return "Number Instructions";
6675 case timer_compute_local_live_sets: return "Local Live Sets";
6676 case timer_compute_global_live_sets: return "Global Live Sets";
6677 case timer_build_intervals: return "Build Intervals";
6678 case timer_sort_intervals_before: return "Sort Intervals Before";
6679 case timer_allocate_registers: return "Allocate Registers";
6680 case timer_resolve_data_flow: return "Resolve Data Flow";
6681 case timer_sort_intervals_after: return "Sort Intervals After";
6682 case timer_eliminate_spill_moves: return "Spill optimization";
6683 case timer_assign_reg_num: return "Assign Reg Num";
6684 case timer_allocate_fpu_stack: return "Allocate FPU Stack";
6685 case timer_optimize_lir: return "Optimize LIR";
6686 default: ShouldNotReachHere(); return "";
6687 }
6688 }
6690 void LinearScanTimers::begin_method() {
6691 if (TimeEachLinearScan) {
6692 // reset all timers to measure only current method
6693 for (int i = 0; i < number_of_timers; i++) {
6694 timer(i)->reset();
6695 }
6696 }
6697 }
6699 void LinearScanTimers::end_method(LinearScan* allocator) {
6700 if (TimeEachLinearScan) {
6702 double c = timer(timer_do_nothing)->seconds();
6703 double total = 0;
6704 for (int i = 1; i < number_of_timers; i++) {
6705 total += timer(i)->seconds() - c;
6706 }
6708 if (total >= 0.0005) {
6709 // print all information in one line for automatic processing
6710 tty->print("@"); allocator->compilation()->method()->print_name();
6712 tty->print("@ %d ", allocator->compilation()->method()->code_size());
6713 tty->print("@ %d ", allocator->block_at(allocator->block_count() - 1)->last_lir_instruction_id() / 2);
6714 tty->print("@ %d ", allocator->block_count());
6715 tty->print("@ %d ", allocator->num_virtual_regs());
6716 tty->print("@ %d ", allocator->interval_count());
6717 tty->print("@ %d ", allocator->_num_calls);
6718 tty->print("@ %d ", allocator->num_loops());
6720 tty->print("@ %6.6f ", total);
6721 for (int i = 1; i < number_of_timers; i++) {
6722 tty->print("@ %4.1f ", ((timer(i)->seconds() - c) / total) * 100);
6723 }
6724 tty->cr();
6725 }
6726 }
6727 }
6729 void LinearScanTimers::print(double total_time) {
6730 if (TimeLinearScan) {
6731 // correction value: sum of dummy-timer that only measures the time that
6732 // is necesary to start and stop itself
6733 double c = timer(timer_do_nothing)->seconds();
6735 for (int i = 0; i < number_of_timers; i++) {
6736 double t = timer(i)->seconds();
6737 tty->print_cr(" %25s: %6.3f s (%4.1f%%) corrected: %6.3f s (%4.1f%%)", timer_name(i), t, (t / total_time) * 100.0, t - c, (t - c) / (total_time - 2 * number_of_timers * c) * 100);
6738 }
6739 }
6740 }
6742 #endif // #ifndef PRODUCT