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