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