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