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