src/share/vm/c1/c1_LinearScan.cpp

Wed, 03 Jul 2019 20:42:37 +0800

author
aoqi
date
Wed, 03 Jul 2019 20:42:37 +0800
changeset 9637
eef07cd490d4
parent 9215
8843990f569c
permissions
-rw-r--r--

Merge

     1 /*
     2  * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 /*
    26  * This file has been modified by Loongson Technology in 2015. These
    27  * modifications are Copyright (c) 2015 Loongson Technology, and are made
    28  * available on the same license terms set forth above.
    29  */
    31 #include "precompiled.hpp"
    32 #include "c1/c1_CFGPrinter.hpp"
    33 #include "c1/c1_CodeStubs.hpp"
    34 #include "c1/c1_Compilation.hpp"
    35 #include "c1/c1_FrameMap.hpp"
    36 #include "c1/c1_IR.hpp"
    37 #include "c1/c1_LIRGenerator.hpp"
    38 #include "c1/c1_LinearScan.hpp"
    39 #include "c1/c1_ValueStack.hpp"
    40 #include "utilities/bitMap.inline.hpp"
    41 #ifdef TARGET_ARCH_x86
    42 # include "vmreg_x86.inline.hpp"
    43 #endif
    44 #ifdef TARGET_ARCH_mips
    45 # include "vmreg_mips.inline.hpp"
    46 #endif
    47 #ifdef TARGET_ARCH_sparc
    48 # include "vmreg_sparc.inline.hpp"
    49 #endif
    50 #ifdef TARGET_ARCH_zero
    51 # include "vmreg_zero.inline.hpp"
    52 #endif
    53 #ifdef TARGET_ARCH_arm
    54 # include "vmreg_arm.inline.hpp"
    55 #endif
    56 #ifdef TARGET_ARCH_ppc
    57 # include "vmreg_ppc.inline.hpp"
    58 #endif
    61 #ifndef PRODUCT
    63   static LinearScanStatistic _stat_before_alloc;
    64   static LinearScanStatistic _stat_after_asign;
    65   static LinearScanStatistic _stat_final;
    67   static LinearScanTimers _total_timer;
    69   // helper macro for short definition of timer
    70   #define TIME_LINEAR_SCAN(timer_name)  TraceTime _block_timer("", _total_timer.timer(LinearScanTimers::timer_name), TimeLinearScan || TimeEachLinearScan, Verbose);
    72   // helper macro for short definition of trace-output inside code
    73   #define TRACE_LINEAR_SCAN(level, code)       \
    74     if (TraceLinearScanLevel >= level) {       \
    75       code;                                    \
    76     }
    78 #else
    80   #define TIME_LINEAR_SCAN(timer_name)
    81   #define TRACE_LINEAR_SCAN(level, code)
    83 #endif
    85 // Map BasicType to spill size in 32-bit words, matching VMReg's notion of words
    86 #ifdef _LP64
    87 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 0, 2,  1, 2, 1, -1};
    88 #else
    89 static int type2spill_size[T_CONFLICT+1]={ -1, 0, 0, 0, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0, 1, -1, 1, 1, -1};
    90 #endif
    93 // Implementation of LinearScan
    95 LinearScan::LinearScan(IR* ir, LIRGenerator* gen, FrameMap* frame_map)
    96  : _compilation(ir->compilation())
    97  , _ir(ir)
    98  , _gen(gen)
    99  , _frame_map(frame_map)
   100  , _num_virtual_regs(gen->max_virtual_register_number())
   101  , _has_fpu_registers(false)
   102  , _num_calls(-1)
   103  , _max_spills(0)
   104  , _unused_spill_slot(-1)
   105  , _intervals(0)   // initialized later with correct length
   106  , _new_intervals_from_allocation(new IntervalList())
   107  , _sorted_intervals(NULL)
   108  , _needs_full_resort(false)
   109  , _lir_ops(0)     // initialized later with correct length
   110  , _block_of_op(0) // initialized later with correct length
   111  , _has_info(0)
   112  , _has_call(0)
   113  , _scope_value_cache(0) // initialized later with correct length
   114  , _interval_in_loop(0, 0) // initialized later with correct length
   115  , _cached_blocks(*ir->linear_scan_order())
   116 #ifdef X86
   117  , _fpu_stack_allocator(NULL)
   118 #endif
   119 {
   120   assert(this->ir() != NULL,          "check if valid");
   121   assert(this->compilation() != NULL, "check if valid");
   122   assert(this->gen() != NULL,         "check if valid");
   123   assert(this->frame_map() != NULL,   "check if valid");
   124 }
   127 // ********** functions for converting LIR-Operands to register numbers
   128 //
   129 // Emulate a flat register file comprising physical integer registers,
   130 // physical floating-point registers and virtual registers, in that order.
   131 // Virtual registers already have appropriate numbers, since V0 is
   132 // the number of physical registers.
   133 // Returns -1 for hi word if opr is a single word operand.
   134 //
   135 // Note: the inverse operation (calculating an operand for register numbers)
   136 //       is done in calc_operand_for_interval()
   138 int LinearScan::reg_num(LIR_Opr opr) {
   139   assert(opr->is_register(), "should not call this otherwise");
   141   if (opr->is_virtual_register()) {
   142     assert(opr->vreg_number() >= nof_regs, "found a virtual register with a fixed-register number");
   143     return opr->vreg_number();
   144   } else if (opr->is_single_cpu()) {
   145     return opr->cpu_regnr();
   146   } else if (opr->is_double_cpu()) {
   147     return opr->cpu_regnrLo();
   148 #ifdef X86
   149   } else if (opr->is_single_xmm()) {
   150     return opr->fpu_regnr() + pd_first_xmm_reg;
   151   } else if (opr->is_double_xmm()) {
   152     return opr->fpu_regnrLo() + pd_first_xmm_reg;
   153 #endif
   154   } else if (opr->is_single_fpu()) {
   155     return opr->fpu_regnr() + pd_first_fpu_reg;
   156   } else if (opr->is_double_fpu()) {
   157     return opr->fpu_regnrLo() + pd_first_fpu_reg;
   158   } else {
   159     ShouldNotReachHere();
   160     return -1;
   161   }
   162 }
   164 int LinearScan::reg_numHi(LIR_Opr opr) {
   165   assert(opr->is_register(), "should not call this otherwise");
   167   if (opr->is_virtual_register()) {
   168     return -1;
   169   } else if (opr->is_single_cpu()) {
   170     return -1;
   171   } else if (opr->is_double_cpu()) {
   172     return opr->cpu_regnrHi();
   173 #ifdef X86
   174   } else if (opr->is_single_xmm()) {
   175     return -1;
   176   } else if (opr->is_double_xmm()) {
   177     return -1;
   178 #endif
   179   } else if (opr->is_single_fpu()) {
   180     return -1;
   181   } else if (opr->is_double_fpu()) {
   182     return opr->fpu_regnrHi() + pd_first_fpu_reg;
   183   } else {
   184     ShouldNotReachHere();
   185     return -1;
   186   }
   187 }
   190 // ********** functions for classification of intervals
   192 bool LinearScan::is_precolored_interval(const Interval* i) {
   193   return i->reg_num() < LinearScan::nof_regs;
   194 }
   196 bool LinearScan::is_virtual_interval(const Interval* i) {
   197   return i->reg_num() >= LIR_OprDesc::vreg_base;
   198 }
   200 bool LinearScan::is_precolored_cpu_interval(const Interval* i) {
   201   return i->reg_num() < LinearScan::nof_cpu_regs;
   202 }
   204 bool LinearScan::is_virtual_cpu_interval(const Interval* i) {
   205 #if defined(__SOFTFP__) || defined(E500V2)
   206   return i->reg_num() >= LIR_OprDesc::vreg_base;
   207 #else
   208   return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() != T_FLOAT && i->type() != T_DOUBLE);
   209 #endif // __SOFTFP__ or E500V2
   210 }
   212 bool LinearScan::is_precolored_fpu_interval(const Interval* i) {
   213   return i->reg_num() >= LinearScan::nof_cpu_regs && i->reg_num() < LinearScan::nof_regs;
   214 }
   216 bool LinearScan::is_virtual_fpu_interval(const Interval* i) {
   217 #if defined(__SOFTFP__) || defined(E500V2)
   218   return false;
   219 #else
   220   return i->reg_num() >= LIR_OprDesc::vreg_base && (i->type() == T_FLOAT || i->type() == T_DOUBLE);
   221 #endif // __SOFTFP__ or E500V2
   222 }
   224 bool LinearScan::is_in_fpu_register(const Interval* i) {
   225   // fixed intervals not needed for FPU stack allocation
   226   return i->reg_num() >= nof_regs && pd_first_fpu_reg <= i->assigned_reg() && i->assigned_reg() <= pd_last_fpu_reg;
   227 }
   229 bool LinearScan::is_oop_interval(const Interval* i) {
   230   // fixed intervals never contain oops
   231   return i->reg_num() >= nof_regs && i->type() == T_OBJECT;
   232 }
   235 // ********** General helper functions
   237 // compute next unused stack index that can be used for spilling
   238 int LinearScan::allocate_spill_slot(bool double_word) {
   239   int spill_slot;
   240   if (double_word) {
   241     if ((_max_spills & 1) == 1) {
   242       // alignment of double-word values
   243       // the hole because of the alignment is filled with the next single-word value
   244       assert(_unused_spill_slot == -1, "wasting a spill slot");
   245       _unused_spill_slot = _max_spills;
   246       _max_spills++;
   247     }
   248     spill_slot = _max_spills;
   249     _max_spills += 2;
   251   } else if (_unused_spill_slot != -1) {
   252     // re-use hole that was the result of a previous double-word alignment
   253     spill_slot = _unused_spill_slot;
   254     _unused_spill_slot = -1;
   256   } else {
   257     spill_slot = _max_spills;
   258     _max_spills++;
   259   }
   261   int result = spill_slot + LinearScan::nof_regs + frame_map()->argcount();
   263   // the class OopMapValue uses only 11 bits for storing the name of the
   264   // oop location. So a stack slot bigger than 2^11 leads to an overflow
   265   // that is not reported in product builds. Prevent this by checking the
   266   // spill slot here (altough this value and the later used location name
   267   // are slightly different)
   268   if (result > 2000) {
   269     bailout("too many stack slots used");
   270   }
   272   return result;
   273 }
   275 void LinearScan::assign_spill_slot(Interval* it) {
   276   // assign the canonical spill slot of the parent (if a part of the interval
   277   // is already spilled) or allocate a new spill slot
   278   if (it->canonical_spill_slot() >= 0) {
   279     it->assign_reg(it->canonical_spill_slot());
   280   } else {
   281     int spill = allocate_spill_slot(type2spill_size[it->type()] == 2);
   282     it->set_canonical_spill_slot(spill);
   283     it->assign_reg(spill);
   284   }
   285 }
   287 void LinearScan::propagate_spill_slots() {
   288   if (!frame_map()->finalize_frame(max_spills())) {
   289     bailout("frame too large");
   290   }
   291 }
   293 // create a new interval with a predefined reg_num
   294 // (only used for parent intervals that are created during the building phase)
   295 Interval* LinearScan::create_interval(int reg_num) {
   296   assert(_intervals.at(reg_num) == NULL, "overwriting exisiting interval");
   298   Interval* interval = new Interval(reg_num);
   299   _intervals.at_put(reg_num, interval);
   301   // assign register number for precolored intervals
   302   if (reg_num < LIR_OprDesc::vreg_base) {
   303     interval->assign_reg(reg_num);
   304   }
   305   return interval;
   306 }
   308 // assign a new reg_num to the interval and append it to the list of intervals
   309 // (only used for child intervals that are created during register allocation)
   310 void LinearScan::append_interval(Interval* it) {
   311   it->set_reg_num(_intervals.length());
   312   _intervals.append(it);
   313   _new_intervals_from_allocation->append(it);
   314 }
   316 // copy the vreg-flags if an interval is split
   317 void LinearScan::copy_register_flags(Interval* from, Interval* to) {
   318   if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::byte_reg)) {
   319     gen()->set_vreg_flag(to->reg_num(), LIRGenerator::byte_reg);
   320   }
   321   if (gen()->is_vreg_flag_set(from->reg_num(), LIRGenerator::callee_saved)) {
   322     gen()->set_vreg_flag(to->reg_num(), LIRGenerator::callee_saved);
   323   }
   325   // Note: do not copy the must_start_in_memory flag because it is not necessary for child
   326   //       intervals (only the very beginning of the interval must be in memory)
   327 }
   330 // ********** spill move optimization
   331 // eliminate moves from register to stack if stack slot is known to be correct
   333 // called during building of intervals
   334 void LinearScan::change_spill_definition_pos(Interval* interval, int def_pos) {
   335   assert(interval->is_split_parent(), "can only be called for split parents");
   337   switch (interval->spill_state()) {
   338     case noDefinitionFound:
   339       assert(interval->spill_definition_pos() == -1, "must no be set before");
   340       interval->set_spill_definition_pos(def_pos);
   341       interval->set_spill_state(oneDefinitionFound);
   342       break;
   344     case oneDefinitionFound:
   345       assert(def_pos <= interval->spill_definition_pos(), "positions are processed in reverse order when intervals are created");
   346       if (def_pos < interval->spill_definition_pos() - 2) {
   347         // second definition found, so no spill optimization possible for this interval
   348         interval->set_spill_state(noOptimization);
   349       } else {
   350         // two consecutive definitions (because of two-operand LIR form)
   351         assert(block_of_op_with_id(def_pos) == block_of_op_with_id(interval->spill_definition_pos()), "block must be equal");
   352       }
   353       break;
   355     case noOptimization:
   356       // nothing to do
   357       break;
   359     default:
   360       assert(false, "other states not allowed at this time");
   361   }
   362 }
   364 // called during register allocation
   365 void LinearScan::change_spill_state(Interval* interval, int spill_pos) {
   366   switch (interval->spill_state()) {
   367     case oneDefinitionFound: {
   368       int def_loop_depth = block_of_op_with_id(interval->spill_definition_pos())->loop_depth();
   369       int spill_loop_depth = block_of_op_with_id(spill_pos)->loop_depth();
   371       if (def_loop_depth < spill_loop_depth) {
   372         // the loop depth of the spilling position is higher then the loop depth
   373         // at the definition of the interval -> move write to memory out of loop
   374         // by storing at definitin of the interval
   375         interval->set_spill_state(storeAtDefinition);
   376       } else {
   377         // the interval is currently spilled only once, so for now there is no
   378         // reason to store the interval at the definition
   379         interval->set_spill_state(oneMoveInserted);
   380       }
   381       break;
   382     }
   384     case oneMoveInserted: {
   385       // the interval is spilled more then once, so it is better to store it to
   386       // memory at the definition
   387       interval->set_spill_state(storeAtDefinition);
   388       break;
   389     }
   391     case storeAtDefinition:
   392     case startInMemory:
   393     case noOptimization:
   394     case noDefinitionFound:
   395       // nothing to do
   396       break;
   398     default:
   399       assert(false, "other states not allowed at this time");
   400   }
   401 }
   404 bool LinearScan::must_store_at_definition(const Interval* i) {
   405   return i->is_split_parent() && i->spill_state() == storeAtDefinition;
   406 }
   408 // called once before asignment of register numbers
   409 void LinearScan::eliminate_spill_moves() {
   410   TIME_LINEAR_SCAN(timer_eliminate_spill_moves);
   411   TRACE_LINEAR_SCAN(3, tty->print_cr("***** Eliminating unnecessary spill moves"));
   413   // collect all intervals that must be stored after their definion.
   414   // the list is sorted by Interval::spill_definition_pos
   415   Interval* interval;
   416   Interval* temp_list;
   417   create_unhandled_lists(&interval, &temp_list, must_store_at_definition, NULL);
   419 #ifdef ASSERT
   420   Interval* prev = NULL;
   421   Interval* temp = interval;
   422   while (temp != Interval::end()) {
   423     assert(temp->spill_definition_pos() > 0, "invalid spill definition pos");
   424     if (prev != NULL) {
   425       assert(temp->from() >= prev->from(), "intervals not sorted");
   426       assert(temp->spill_definition_pos() >= prev->spill_definition_pos(), "when intervals are sorted by from, then they must also be sorted by spill_definition_pos");
   427     }
   429     assert(temp->canonical_spill_slot() >= LinearScan::nof_regs, "interval has no spill slot assigned");
   430     assert(temp->spill_definition_pos() >= temp->from(), "invalid order");
   431     assert(temp->spill_definition_pos() <= temp->from() + 2, "only intervals defined once at their start-pos can be optimized");
   433     TRACE_LINEAR_SCAN(4, tty->print_cr("interval %d (from %d to %d) must be stored at %d", temp->reg_num(), temp->from(), temp->to(), temp->spill_definition_pos()));
   435     temp = temp->next();
   436   }
   437 #endif
   439   LIR_InsertionBuffer insertion_buffer;
   440   int num_blocks = block_count();
   441   for (int i = 0; i < num_blocks; i++) {
   442     BlockBegin* block = block_at(i);
   443     LIR_OpList* instructions = block->lir()->instructions_list();
   444     int         num_inst = instructions->length();
   445     bool        has_new = false;
   447     // iterate all instructions of the block. skip the first because it is always a label
   448     for (int j = 1; j < num_inst; j++) {
   449       LIR_Op* op = instructions->at(j);
   450       int op_id = op->id();
   452       if (op_id == -1) {
   453         // remove move from register to stack if the stack slot is guaranteed to be correct.
   454         // only moves that have been inserted by LinearScan can be removed.
   455         assert(op->code() == lir_move, "only moves can have a op_id of -1");
   456         assert(op->as_Op1() != NULL, "move must be LIR_Op1");
   457         assert(op->as_Op1()->result_opr()->is_virtual(), "LinearScan inserts only moves to virtual registers");
   459         LIR_Op1* op1 = (LIR_Op1*)op;
   460         Interval* interval = interval_at(op1->result_opr()->vreg_number());
   462         if (interval->assigned_reg() >= LinearScan::nof_regs && interval->always_in_memory()) {
   463           // move target is a stack slot that is always correct, so eliminate instruction
   464           TRACE_LINEAR_SCAN(4, tty->print_cr("eliminating move from interval %d to %d", op1->in_opr()->vreg_number(), op1->result_opr()->vreg_number()));
   465           instructions->at_put(j, NULL); // NULL-instructions are deleted by assign_reg_num
   466         }
   468       } else {
   469         // insert move from register to stack just after the beginning of the interval
   470         assert(interval == Interval::end() || interval->spill_definition_pos() >= op_id, "invalid order");
   471         assert(interval == Interval::end() || (interval->is_split_parent() && interval->spill_state() == storeAtDefinition), "invalid interval");
   473         while (interval != Interval::end() && interval->spill_definition_pos() == op_id) {
   474           if (!has_new) {
   475             // prepare insertion buffer (appended when all instructions of the block are processed)
   476             insertion_buffer.init(block->lir());
   477             has_new = true;
   478           }
   480           LIR_Opr from_opr = operand_for_interval(interval);
   481           LIR_Opr to_opr = canonical_spill_opr(interval);
   482           assert(from_opr->is_fixed_cpu() || from_opr->is_fixed_fpu(), "from operand must be a register");
   483           assert(to_opr->is_stack(), "to operand must be a stack slot");
   485           insertion_buffer.move(j, from_opr, to_opr);
   486           TRACE_LINEAR_SCAN(4, tty->print_cr("inserting move after definition of interval %d to stack slot %d at op_id %d", interval->reg_num(), interval->canonical_spill_slot() - LinearScan::nof_regs, op_id));
   488           interval = interval->next();
   489         }
   490       }
   491     } // end of instruction iteration
   493     if (has_new) {
   494       block->lir()->append(&insertion_buffer);
   495     }
   496   } // end of block iteration
   498   assert(interval == Interval::end(), "missed an interval");
   499 }
   502 // ********** Phase 1: number all instructions in all blocks
   503 // Compute depth-first and linear scan block orders, and number LIR_Op nodes for linear scan.
   505 void LinearScan::number_instructions() {
   506   {
   507     // dummy-timer to measure the cost of the timer itself
   508     // (this time is then subtracted from all other timers to get the real value)
   509     TIME_LINEAR_SCAN(timer_do_nothing);
   510   }
   511   TIME_LINEAR_SCAN(timer_number_instructions);
   513   // Assign IDs to LIR nodes and build a mapping, lir_ops, from ID to LIR_Op node.
   514   int num_blocks = block_count();
   515   int num_instructions = 0;
   516   int i;
   517   for (i = 0; i < num_blocks; i++) {
   518     num_instructions += block_at(i)->lir()->instructions_list()->length();
   519   }
   521   // initialize with correct length
   522   _lir_ops = LIR_OpArray(num_instructions);
   523   _block_of_op = BlockBeginArray(num_instructions);
   525   int op_id = 0;
   526   int idx = 0;
   528   for (i = 0; i < num_blocks; i++) {
   529     BlockBegin* block = block_at(i);
   530     block->set_first_lir_instruction_id(op_id);
   531     LIR_OpList* instructions = block->lir()->instructions_list();
   533     int num_inst = instructions->length();
   534     for (int j = 0; j < num_inst; j++) {
   535       LIR_Op* op = instructions->at(j);
   536       op->set_id(op_id);
   538       _lir_ops.at_put(idx, op);
   539       _block_of_op.at_put(idx, block);
   540       assert(lir_op_with_id(op_id) == op, "must match");
   542       idx++;
   543       op_id += 2; // numbering of lir_ops by two
   544     }
   545     block->set_last_lir_instruction_id(op_id - 2);
   546   }
   547   assert(idx == num_instructions, "must match");
   548   assert(idx * 2 == op_id, "must match");
   550   _has_call = BitMap(num_instructions); _has_call.clear();
   551   _has_info = BitMap(num_instructions); _has_info.clear();
   552 }
   555 // ********** Phase 2: compute local live sets separately for each block
   556 // (sets live_gen and live_kill for each block)
   558 void LinearScan::set_live_gen_kill(Value value, LIR_Op* op, BitMap& live_gen, BitMap& live_kill) {
   559   LIR_Opr opr = value->operand();
   560   Constant* con = value->as_Constant();
   562   // check some asumptions about debug information
   563   assert(!value->type()->is_illegal(), "if this local is used by the interpreter it shouldn't be of indeterminate type");
   564   assert(con == NULL || opr->is_virtual() || opr->is_constant() || opr->is_illegal(), "asumption: Constant instructions have only constant operands");
   565   assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");
   567   if ((con == NULL || con->is_pinned()) && opr->is_register()) {
   568     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   569     int reg = opr->vreg_number();
   570     if (!live_kill.at(reg)) {
   571       live_gen.set_bit(reg);
   572       TRACE_LINEAR_SCAN(4, tty->print_cr("  Setting live_gen for value %c%d, LIR op_id %d, register number %d", value->type()->tchar(), value->id(), op->id(), reg));
   573     }
   574   }
   575 }
   578 void LinearScan::compute_local_live_sets() {
   579   TIME_LINEAR_SCAN(timer_compute_local_live_sets);
   581   int  num_blocks = block_count();
   582   int  live_size = live_set_size();
   583   bool local_has_fpu_registers = false;
   584   int  local_num_calls = 0;
   585   LIR_OpVisitState visitor;
   587   BitMap2D local_interval_in_loop = BitMap2D(_num_virtual_regs, num_loops());
   588   local_interval_in_loop.clear();
   590   // iterate all blocks
   591   for (int i = 0; i < num_blocks; i++) {
   592     BlockBegin* block = block_at(i);
   594     BitMap live_gen(live_size);  live_gen.clear();
   595     BitMap live_kill(live_size); live_kill.clear();
   597     if (block->is_set(BlockBegin::exception_entry_flag)) {
   598       // Phi functions at the begin of an exception handler are
   599       // implicitly defined (= killed) at the beginning of the block.
   600       for_each_phi_fun(block, phi,
   601         live_kill.set_bit(phi->operand()->vreg_number())
   602       );
   603     }
   605     LIR_OpList* instructions = block->lir()->instructions_list();
   606     int num_inst = instructions->length();
   608     // iterate all instructions of the block. skip the first because it is always a label
   609     assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
   610     for (int j = 1; j < num_inst; j++) {
   611       LIR_Op* op = instructions->at(j);
   613       // visit operation to collect all operands
   614       visitor.visit(op);
   616       if (visitor.has_call()) {
   617         _has_call.set_bit(op->id() >> 1);
   618         local_num_calls++;
   619       }
   620       if (visitor.info_count() > 0) {
   621         _has_info.set_bit(op->id() >> 1);
   622       }
   624       // iterate input operands of instruction
   625       int k, n, reg;
   626       n = visitor.opr_count(LIR_OpVisitState::inputMode);
   627       for (k = 0; k < n; k++) {
   628         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
   629         assert(opr->is_register(), "visitor should only return register operands");
   631         if (opr->is_virtual_register()) {
   632           assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   633           reg = opr->vreg_number();
   634           if (!live_kill.at(reg)) {
   635             live_gen.set_bit(reg);
   636             TRACE_LINEAR_SCAN(4, tty->print_cr("  Setting live_gen for register %d at instruction %d", reg, op->id()));
   637           }
   638           if (block->loop_index() >= 0) {
   639             local_interval_in_loop.set_bit(reg, block->loop_index());
   640           }
   641           local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
   642         }
   644 #ifdef ASSERT
   645         // fixed intervals are never live at block boundaries, so
   646         // they need not be processed in live sets.
   647         // this is checked by these assertions to be sure about it.
   648         // the entry block may have incoming values in registers, which is ok.
   649         if (!opr->is_virtual_register() && block != ir()->start()) {
   650           reg = reg_num(opr);
   651           if (is_processed_reg_num(reg)) {
   652             assert(live_kill.at(reg), "using fixed register that is not defined in this block");
   653           }
   654           reg = reg_numHi(opr);
   655           if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   656             assert(live_kill.at(reg), "using fixed register that is not defined in this block");
   657           }
   658         }
   659 #endif
   660       }
   662       // Add uses of live locals from interpreter's point of view for proper debug information generation
   663       n = visitor.info_count();
   664       for (k = 0; k < n; k++) {
   665         CodeEmitInfo* info = visitor.info_at(k);
   666         ValueStack* stack = info->stack();
   667         for_each_state_value(stack, value,
   668           set_live_gen_kill(value, op, live_gen, live_kill)
   669         );
   670       }
   672       // iterate temp operands of instruction
   673       n = visitor.opr_count(LIR_OpVisitState::tempMode);
   674       for (k = 0; k < n; k++) {
   675         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
   676         assert(opr->is_register(), "visitor should only return register operands");
   678         if (opr->is_virtual_register()) {
   679           assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   680           reg = opr->vreg_number();
   681           live_kill.set_bit(reg);
   682           if (block->loop_index() >= 0) {
   683             local_interval_in_loop.set_bit(reg, block->loop_index());
   684           }
   685           local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
   686         }
   688 #ifdef ASSERT
   689         // fixed intervals are never live at block boundaries, so
   690         // they need not be processed in live sets
   691         // process them only in debug mode so that this can be checked
   692         if (!opr->is_virtual_register()) {
   693           reg = reg_num(opr);
   694           if (is_processed_reg_num(reg)) {
   695             live_kill.set_bit(reg_num(opr));
   696           }
   697           reg = reg_numHi(opr);
   698           if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   699             live_kill.set_bit(reg);
   700           }
   701         }
   702 #endif
   703       }
   705       // iterate output operands of instruction
   706       n = visitor.opr_count(LIR_OpVisitState::outputMode);
   707       for (k = 0; k < n; k++) {
   708         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
   709         assert(opr->is_register(), "visitor should only return register operands");
   711         if (opr->is_virtual_register()) {
   712           assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   713           reg = opr->vreg_number();
   714           live_kill.set_bit(reg);
   715           if (block->loop_index() >= 0) {
   716             local_interval_in_loop.set_bit(reg, block->loop_index());
   717           }
   718           local_has_fpu_registers = local_has_fpu_registers || opr->is_virtual_fpu();
   719         }
   721 #ifdef ASSERT
   722         // fixed intervals are never live at block boundaries, so
   723         // they need not be processed in live sets
   724         // process them only in debug mode so that this can be checked
   725         if (!opr->is_virtual_register()) {
   726           reg = reg_num(opr);
   727           if (is_processed_reg_num(reg)) {
   728             live_kill.set_bit(reg_num(opr));
   729           }
   730           reg = reg_numHi(opr);
   731           if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   732             live_kill.set_bit(reg);
   733           }
   734         }
   735 #endif
   736       }
   737     } // end of instruction iteration
   739     block->set_live_gen (live_gen);
   740     block->set_live_kill(live_kill);
   741     block->set_live_in  (BitMap(live_size)); block->live_in().clear();
   742     block->set_live_out (BitMap(live_size)); block->live_out().clear();
   744     TRACE_LINEAR_SCAN(4, tty->print("live_gen  B%d ", block->block_id()); print_bitmap(block->live_gen()));
   745     TRACE_LINEAR_SCAN(4, tty->print("live_kill B%d ", block->block_id()); print_bitmap(block->live_kill()));
   746   } // end of block iteration
   748   // propagate local calculated information into LinearScan object
   749   _has_fpu_registers = local_has_fpu_registers;
   750   compilation()->set_has_fpu_code(local_has_fpu_registers);
   752   _num_calls = local_num_calls;
   753   _interval_in_loop = local_interval_in_loop;
   754 }
   757 // ********** Phase 3: perform a backward dataflow analysis to compute global live sets
   758 // (sets live_in and live_out for each block)
   760 void LinearScan::compute_global_live_sets() {
   761   TIME_LINEAR_SCAN(timer_compute_global_live_sets);
   763   int  num_blocks = block_count();
   764   bool change_occurred;
   765   bool change_occurred_in_block;
   766   int  iteration_count = 0;
   767   BitMap live_out(live_set_size()); live_out.clear(); // scratch set for calculations
   769   // Perform a backward dataflow analysis to compute live_out and live_in for each block.
   770   // The loop is executed until a fixpoint is reached (no changes in an iteration)
   771   // Exception handlers must be processed because not all live values are
   772   // present in the state array, e.g. because of global value numbering
   773   do {
   774     change_occurred = false;
   776     // iterate all blocks in reverse order
   777     for (int i = num_blocks - 1; i >= 0; i--) {
   778       BlockBegin* block = block_at(i);
   780       change_occurred_in_block = false;
   782       // live_out(block) is the union of live_in(sux), for successors sux of block
   783       int n = block->number_of_sux();
   784       int e = block->number_of_exception_handlers();
   785       if (n + e > 0) {
   786         // block has successors
   787         if (n > 0) {
   788           live_out.set_from(block->sux_at(0)->live_in());
   789           for (int j = 1; j < n; j++) {
   790             live_out.set_union(block->sux_at(j)->live_in());
   791           }
   792         } else {
   793           live_out.clear();
   794         }
   795         for (int j = 0; j < e; j++) {
   796           live_out.set_union(block->exception_handler_at(j)->live_in());
   797         }
   799         if (!block->live_out().is_same(live_out)) {
   800           // A change occurred.  Swap the old and new live out sets to avoid copying.
   801           BitMap temp = block->live_out();
   802           block->set_live_out(live_out);
   803           live_out = temp;
   805           change_occurred = true;
   806           change_occurred_in_block = true;
   807         }
   808       }
   810       if (iteration_count == 0 || change_occurred_in_block) {
   811         // live_in(block) is the union of live_gen(block) with (live_out(block) & !live_kill(block))
   812         // note: live_in has to be computed only in first iteration or if live_out has changed!
   813         BitMap live_in = block->live_in();
   814         live_in.set_from(block->live_out());
   815         live_in.set_difference(block->live_kill());
   816         live_in.set_union(block->live_gen());
   817       }
   819 #ifndef PRODUCT
   820       if (TraceLinearScanLevel >= 4) {
   821         char c = ' ';
   822         if (iteration_count == 0 || change_occurred_in_block) {
   823           c = '*';
   824         }
   825         tty->print("(%d) live_in%c  B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_in());
   826         tty->print("(%d) live_out%c B%d ", iteration_count, c, block->block_id()); print_bitmap(block->live_out());
   827       }
   828 #endif
   829     }
   830     iteration_count++;
   832     if (change_occurred && iteration_count > 50) {
   833       BAILOUT("too many iterations in compute_global_live_sets");
   834     }
   835   } while (change_occurred);
   838 #ifdef ASSERT
   839   // check that fixed intervals are not live at block boundaries
   840   // (live set must be empty at fixed intervals)
   841   for (int i = 0; i < num_blocks; i++) {
   842     BlockBegin* block = block_at(i);
   843     for (int j = 0; j < LIR_OprDesc::vreg_base; j++) {
   844       assert(block->live_in().at(j)  == false, "live_in  set of fixed register must be empty");
   845       assert(block->live_out().at(j) == false, "live_out set of fixed register must be empty");
   846       assert(block->live_gen().at(j) == false, "live_gen set of fixed register must be empty");
   847     }
   848   }
   849 #endif
   851   // check that the live_in set of the first block is empty
   852   BitMap live_in_args(ir()->start()->live_in().size());
   853   live_in_args.clear();
   854   if (!ir()->start()->live_in().is_same(live_in_args)) {
   855 #ifdef ASSERT
   856     tty->print_cr("Error: live_in set of first block must be empty (when this fails, virtual registers are used before they are defined)");
   857     tty->print_cr("affected registers:");
   858     print_bitmap(ir()->start()->live_in());
   860     // print some additional information to simplify debugging
   861     for (unsigned int i = 0; i < ir()->start()->live_in().size(); i++) {
   862       if (ir()->start()->live_in().at(i)) {
   863         Instruction* instr = gen()->instruction_for_vreg(i);
   864         tty->print_cr("* vreg %d (HIR instruction %c%d)", i, instr == NULL ? ' ' : instr->type()->tchar(), instr == NULL ? 0 : instr->id());
   866         for (int j = 0; j < num_blocks; j++) {
   867           BlockBegin* block = block_at(j);
   868           if (block->live_gen().at(i)) {
   869             tty->print_cr("  used in block B%d", block->block_id());
   870           }
   871           if (block->live_kill().at(i)) {
   872             tty->print_cr("  defined in block B%d", block->block_id());
   873           }
   874         }
   875       }
   876     }
   878 #endif
   879     // when this fails, virtual registers are used before they are defined.
   880     assert(false, "live_in set of first block must be empty");
   881     // bailout of if this occurs in product mode.
   882     bailout("live_in set of first block not empty");
   883   }
   884 }
   887 // ********** Phase 4: build intervals
   888 // (fills the list _intervals)
   890 void LinearScan::add_use(Value value, int from, int to, IntervalUseKind use_kind) {
   891   assert(!value->type()->is_illegal(), "if this value is used by the interpreter it shouldn't be of indeterminate type");
   892   LIR_Opr opr = value->operand();
   893   Constant* con = value->as_Constant();
   895   if ((con == NULL || con->is_pinned()) && opr->is_register()) {
   896     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   897     add_use(opr, from, to, use_kind);
   898   }
   899 }
   902 void LinearScan::add_def(LIR_Opr opr, int def_pos, IntervalUseKind use_kind) {
   903   TRACE_LINEAR_SCAN(2, tty->print(" def "); opr->print(tty); tty->print_cr(" def_pos %d (%d)", def_pos, use_kind));
   904   assert(opr->is_register(), "should not be called otherwise");
   906   if (opr->is_virtual_register()) {
   907     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   908     add_def(opr->vreg_number(), def_pos, use_kind, opr->type_register());
   910   } else {
   911     int reg = reg_num(opr);
   912     if (is_processed_reg_num(reg)) {
   913       add_def(reg, def_pos, use_kind, opr->type_register());
   914     }
   915     reg = reg_numHi(opr);
   916     if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   917       add_def(reg, def_pos, use_kind, opr->type_register());
   918     }
   919   }
   920 }
   922 void LinearScan::add_use(LIR_Opr opr, int from, int to, IntervalUseKind use_kind) {
   923   TRACE_LINEAR_SCAN(2, tty->print(" use "); opr->print(tty); tty->print_cr(" from %d to %d (%d)", from, to, use_kind));
   924   assert(opr->is_register(), "should not be called otherwise");
   926   if (opr->is_virtual_register()) {
   927     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   928     add_use(opr->vreg_number(), from, to, use_kind, opr->type_register());
   930   } else {
   931     int reg = reg_num(opr);
   932     if (is_processed_reg_num(reg)) {
   933       add_use(reg, from, to, use_kind, opr->type_register());
   934     }
   935     reg = reg_numHi(opr);
   936     if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   937       add_use(reg, from, to, use_kind, opr->type_register());
   938     }
   939   }
   940 }
   942 void LinearScan::add_temp(LIR_Opr opr, int temp_pos, IntervalUseKind use_kind) {
   943   TRACE_LINEAR_SCAN(2, tty->print(" temp "); opr->print(tty); tty->print_cr(" temp_pos %d (%d)", temp_pos, use_kind));
   944   assert(opr->is_register(), "should not be called otherwise");
   946   if (opr->is_virtual_register()) {
   947     assert(reg_num(opr) == opr->vreg_number() && !is_valid_reg_num(reg_numHi(opr)), "invalid optimization below");
   948     add_temp(opr->vreg_number(), temp_pos, use_kind, opr->type_register());
   950   } else {
   951     int reg = reg_num(opr);
   952     if (is_processed_reg_num(reg)) {
   953       add_temp(reg, temp_pos, use_kind, opr->type_register());
   954     }
   955     reg = reg_numHi(opr);
   956     if (is_valid_reg_num(reg) && is_processed_reg_num(reg)) {
   957       add_temp(reg, temp_pos, use_kind, opr->type_register());
   958     }
   959   }
   960 }
   963 void LinearScan::add_def(int reg_num, int def_pos, IntervalUseKind use_kind, BasicType type) {
   964   Interval* interval = interval_at(reg_num);
   965   if (interval != NULL) {
   966     assert(interval->reg_num() == reg_num, "wrong interval");
   968     if (type != T_ILLEGAL) {
   969       interval->set_type(type);
   970     }
   972     Range* r = interval->first();
   973     if (r->from() <= def_pos) {
   974       // Update the starting point (when a range is first created for a use, its
   975       // start is the beginning of the current block until a def is encountered.)
   976       r->set_from(def_pos);
   977       interval->add_use_pos(def_pos, use_kind);
   979     } else {
   980       // Dead value - make vacuous interval
   981       // also add use_kind for dead intervals
   982       interval->add_range(def_pos, def_pos + 1);
   983       interval->add_use_pos(def_pos, use_kind);
   984       TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: def of reg %d at %d occurs without use", reg_num, def_pos));
   985     }
   987   } else {
   988     // Dead value - make vacuous interval
   989     // also add use_kind for dead intervals
   990     interval = create_interval(reg_num);
   991     if (type != T_ILLEGAL) {
   992       interval->set_type(type);
   993     }
   995     interval->add_range(def_pos, def_pos + 1);
   996     interval->add_use_pos(def_pos, use_kind);
   997     TRACE_LINEAR_SCAN(2, tty->print_cr("Warning: dead value %d at %d in live intervals", reg_num, def_pos));
   998   }
  1000   change_spill_definition_pos(interval, def_pos);
  1001   if (use_kind == noUse && interval->spill_state() <= startInMemory) {
  1002         // detection of method-parameters and roundfp-results
  1003         // TODO: move this directly to position where use-kind is computed
  1004     interval->set_spill_state(startInMemory);
  1008 void LinearScan::add_use(int reg_num, int from, int to, IntervalUseKind use_kind, BasicType type) {
  1009   Interval* interval = interval_at(reg_num);
  1010   if (interval == NULL) {
  1011     interval = create_interval(reg_num);
  1013   assert(interval->reg_num() == reg_num, "wrong interval");
  1015   if (type != T_ILLEGAL) {
  1016     interval->set_type(type);
  1019   interval->add_range(from, to);
  1020   interval->add_use_pos(to, use_kind);
  1023 void LinearScan::add_temp(int reg_num, int temp_pos, IntervalUseKind use_kind, BasicType type) {
  1024   Interval* interval = interval_at(reg_num);
  1025   if (interval == NULL) {
  1026     interval = create_interval(reg_num);
  1028   assert(interval->reg_num() == reg_num, "wrong interval");
  1030   if (type != T_ILLEGAL) {
  1031     interval->set_type(type);
  1034   interval->add_range(temp_pos, temp_pos + 1);
  1035   interval->add_use_pos(temp_pos, use_kind);
  1039 // the results of this functions are used for optimizing spilling and reloading
  1040 // if the functions return shouldHaveRegister and the interval is spilled,
  1041 // it is not reloaded to a register.
  1042 IntervalUseKind LinearScan::use_kind_of_output_operand(LIR_Op* op, LIR_Opr opr) {
  1043   if (op->code() == lir_move) {
  1044     assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");
  1045     LIR_Op1* move = (LIR_Op1*)op;
  1046     LIR_Opr res = move->result_opr();
  1047     bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
  1049     if (result_in_memory) {
  1050       // Begin of an interval with must_start_in_memory set.
  1051       // This interval will always get a stack slot first, so return noUse.
  1052       return noUse;
  1054     } else if (move->in_opr()->is_stack()) {
  1055       // method argument (condition must be equal to handle_method_arguments)
  1056       return noUse;
  1058     } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
  1059       // Move from register to register
  1060       if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
  1061         // special handling of phi-function moves inside osr-entry blocks
  1062         // input operand must have a register instead of output operand (leads to better register allocation)
  1063         return shouldHaveRegister;
  1068   if (opr->is_virtual() &&
  1069       gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::must_start_in_memory)) {
  1070     // result is a stack-slot, so prevent immediate reloading
  1071     return noUse;
  1074   // all other operands require a register
  1075   return mustHaveRegister;
  1078 IntervalUseKind LinearScan::use_kind_of_input_operand(LIR_Op* op, LIR_Opr opr) {
  1079   if (op->code() == lir_move) {
  1080     assert(op->as_Op1() != NULL, "lir_move must be LIR_Op1");
  1081     LIR_Op1* move = (LIR_Op1*)op;
  1082     LIR_Opr res = move->result_opr();
  1083     bool result_in_memory = res->is_virtual() && gen()->is_vreg_flag_set(res->vreg_number(), LIRGenerator::must_start_in_memory);
  1085     if (result_in_memory) {
  1086       // Move to an interval with must_start_in_memory set.
  1087       // To avoid moves from stack to stack (not allowed) force the input operand to a register
  1088       return mustHaveRegister;
  1090     } else if (move->in_opr()->is_register() && move->result_opr()->is_register()) {
  1091       // Move from register to register
  1092       if (block_of_op_with_id(op->id())->is_set(BlockBegin::osr_entry_flag)) {
  1093         // special handling of phi-function moves inside osr-entry blocks
  1094         // input operand must have a register instead of output operand (leads to better register allocation)
  1095         return mustHaveRegister;
  1098       // The input operand is not forced to a register (moves from stack to register are allowed),
  1099       // but it is faster if the input operand is in a register
  1100       return shouldHaveRegister;
  1105 #ifdef X86
  1106   if (op->code() == lir_cmove) {
  1107     // conditional moves can handle stack operands
  1108     assert(op->result_opr()->is_register(), "result must always be in a register");
  1109     return shouldHaveRegister;
  1112   // optimizations for second input operand of arithmehtic operations on Intel
  1113   // this operand is allowed to be on the stack in some cases
  1114   BasicType opr_type = opr->type_register();
  1115   if (opr_type == T_FLOAT || opr_type == T_DOUBLE) {
  1116     if ((UseSSE == 1 && opr_type == T_FLOAT) || UseSSE >= 2) {
  1117       // SSE float instruction (T_DOUBLE only supported with SSE2)
  1118       switch (op->code()) {
  1119         case lir_cmp:
  1120         case lir_add:
  1121         case lir_sub:
  1122         case lir_mul:
  1123         case lir_div:
  1125           assert(op->as_Op2() != NULL, "must be LIR_Op2");
  1126           LIR_Op2* op2 = (LIR_Op2*)op;
  1127           if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
  1128             assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
  1129             return shouldHaveRegister;
  1133     } else {
  1134       // FPU stack float instruction
  1135       switch (op->code()) {
  1136         case lir_add:
  1137         case lir_sub:
  1138         case lir_mul:
  1139         case lir_div:
  1141           assert(op->as_Op2() != NULL, "must be LIR_Op2");
  1142           LIR_Op2* op2 = (LIR_Op2*)op;
  1143           if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
  1144             assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
  1145             return shouldHaveRegister;
  1150     // We want to sometimes use logical operations on pointers, in particular in GC barriers.
  1151     // Since 64bit logical operations do not current support operands on stack, we have to make sure
  1152     // T_OBJECT doesn't get spilled along with T_LONG.
  1153   } else if (opr_type != T_LONG LP64_ONLY(&& opr_type != T_OBJECT)) {
  1154     // integer instruction (note: long operands must always be in register)
  1155     switch (op->code()) {
  1156       case lir_cmp:
  1157       case lir_add:
  1158       case lir_sub:
  1159       case lir_logic_and:
  1160       case lir_logic_or:
  1161       case lir_logic_xor:
  1163         assert(op->as_Op2() != NULL, "must be LIR_Op2");
  1164         LIR_Op2* op2 = (LIR_Op2*)op;
  1165         if (op2->in_opr1() != op2->in_opr2() && op2->in_opr2() == opr) {
  1166           assert((op2->result_opr()->is_register() || op->code() == lir_cmp) && op2->in_opr1()->is_register(), "cannot mark second operand as stack if others are not in register");
  1167           return shouldHaveRegister;
  1172 #endif // X86
  1174   // all other operands require a register
  1175   return mustHaveRegister;
  1179 void LinearScan::handle_method_arguments(LIR_Op* op) {
  1180   // special handling for method arguments (moves from stack to virtual register):
  1181   // the interval gets no register assigned, but the stack slot.
  1182   // it is split before the first use by the register allocator.
  1184   if (op->code() == lir_move) {
  1185     assert(op->as_Op1() != NULL, "must be LIR_Op1");
  1186     LIR_Op1* move = (LIR_Op1*)op;
  1188     if (move->in_opr()->is_stack()) {
  1189 #ifdef ASSERT
  1190       int arg_size = compilation()->method()->arg_size();
  1191       LIR_Opr o = move->in_opr();
  1192       if (o->is_single_stack()) {
  1193         assert(o->single_stack_ix() >= 0 && o->single_stack_ix() < arg_size, "out of range");
  1194       } else if (o->is_double_stack()) {
  1195         assert(o->double_stack_ix() >= 0 && o->double_stack_ix() < arg_size, "out of range");
  1196       } else {
  1197         ShouldNotReachHere();
  1200       assert(move->id() > 0, "invalid id");
  1201       assert(block_of_op_with_id(move->id())->number_of_preds() == 0, "move from stack must be in first block");
  1202       assert(move->result_opr()->is_virtual(), "result of move must be a virtual register");
  1204       TRACE_LINEAR_SCAN(4, tty->print_cr("found move from stack slot %d to vreg %d", o->is_single_stack() ? o->single_stack_ix() : o->double_stack_ix(), reg_num(move->result_opr())));
  1205 #endif
  1207       Interval* interval = interval_at(reg_num(move->result_opr()));
  1209       int stack_slot = LinearScan::nof_regs + (move->in_opr()->is_single_stack() ? move->in_opr()->single_stack_ix() : move->in_opr()->double_stack_ix());
  1210       interval->set_canonical_spill_slot(stack_slot);
  1211       interval->assign_reg(stack_slot);
  1216 void LinearScan::handle_doubleword_moves(LIR_Op* op) {
  1217   // special handling for doubleword move from memory to register:
  1218   // in this case the registers of the input address and the result
  1219   // registers must not overlap -> add a temp range for the input registers
  1220   if (op->code() == lir_move) {
  1221     assert(op->as_Op1() != NULL, "must be LIR_Op1");
  1222     LIR_Op1* move = (LIR_Op1*)op;
  1224     if (move->result_opr()->is_double_cpu() && move->in_opr()->is_pointer()) {
  1225       LIR_Address* address = move->in_opr()->as_address_ptr();
  1226       if (address != NULL) {
  1227         if (address->base()->is_valid()) {
  1228           add_temp(address->base(), op->id(), noUse);
  1230         if (address->index()->is_valid()) {
  1231           add_temp(address->index(), op->id(), noUse);
  1238 void LinearScan::add_register_hints(LIR_Op* op) {
  1239   switch (op->code()) {
  1240     case lir_move:      // fall through
  1241     case lir_convert: {
  1242       assert(op->as_Op1() != NULL, "lir_move, lir_convert must be LIR_Op1");
  1243       LIR_Op1* move = (LIR_Op1*)op;
  1245       LIR_Opr move_from = move->in_opr();
  1246       LIR_Opr move_to = move->result_opr();
  1248       if (move_to->is_register() && move_from->is_register()) {
  1249         Interval* from = interval_at(reg_num(move_from));
  1250         Interval* to = interval_at(reg_num(move_to));
  1251         if (from != NULL && to != NULL) {
  1252           to->set_register_hint(from);
  1253           TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", move->id(), from->reg_num(), to->reg_num()));
  1256       break;
  1258     case lir_cmove: {
  1259       assert(op->as_Op2() != NULL, "lir_cmove must be LIR_Op2");
  1260       LIR_Op2* cmove = (LIR_Op2*)op;
  1262       LIR_Opr move_from = cmove->in_opr1();
  1263       LIR_Opr move_to = cmove->result_opr();
  1265       if (move_to->is_register() && move_from->is_register()) {
  1266         Interval* from = interval_at(reg_num(move_from));
  1267         Interval* to = interval_at(reg_num(move_to));
  1268         if (from != NULL && to != NULL) {
  1269           to->set_register_hint(from);
  1270           TRACE_LINEAR_SCAN(4, tty->print_cr("operation at op_id %d: added hint from interval %d to %d", cmove->id(), from->reg_num(), to->reg_num()));
  1273       break;
  1279 void LinearScan::build_intervals() {
  1280   TIME_LINEAR_SCAN(timer_build_intervals);
  1282   // initialize interval list with expected number of intervals
  1283   // (32 is added to have some space for split children without having to resize the list)
  1284   _intervals = IntervalList(num_virtual_regs() + 32);
  1285   // initialize all slots that are used by build_intervals
  1286   _intervals.at_put_grow(num_virtual_regs() - 1, NULL, NULL);
  1288   // create a list with all caller-save registers (cpu, fpu, xmm)
  1289   // when an instruction is a call, a temp range is created for all these registers
  1290   int num_caller_save_registers = 0;
  1291   int caller_save_registers[LinearScan::nof_regs];
  1293   int i;
  1294   for (i = 0; i < FrameMap::nof_caller_save_cpu_regs(); i++) {
  1295     LIR_Opr opr = FrameMap::caller_save_cpu_reg_at(i);
  1296     assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
  1297     assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
  1298     caller_save_registers[num_caller_save_registers++] = reg_num(opr);
  1301   // temp ranges for fpu registers are only created when the method has
  1302   // virtual fpu operands. Otherwise no allocation for fpu registers is
  1303   // perfomed and so the temp ranges would be useless
  1304   if (has_fpu_registers()) {
  1305 #ifdef X86
  1306     if (UseSSE < 2) {
  1307 #endif
  1308       for (i = 0; i < FrameMap::nof_caller_save_fpu_regs; i++) {
  1309         LIR_Opr opr = FrameMap::caller_save_fpu_reg_at(i);
  1310         assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
  1311         assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
  1312         caller_save_registers[num_caller_save_registers++] = reg_num(opr);
  1314 #ifdef X86
  1316     if (UseSSE > 0) {
  1317       for (i = 0; i < FrameMap::nof_caller_save_xmm_regs; i++) {
  1318         LIR_Opr opr = FrameMap::caller_save_xmm_reg_at(i);
  1319         assert(opr->is_valid() && opr->is_register(), "FrameMap should not return invalid operands");
  1320         assert(reg_numHi(opr) == -1, "missing addition of range for hi-register");
  1321         caller_save_registers[num_caller_save_registers++] = reg_num(opr);
  1324 #endif
  1326   assert(num_caller_save_registers <= LinearScan::nof_regs, "out of bounds");
  1329   LIR_OpVisitState visitor;
  1331   // iterate all blocks in reverse order
  1332   for (i = block_count() - 1; i >= 0; i--) {
  1333     BlockBegin* block = block_at(i);
  1334     LIR_OpList* instructions = block->lir()->instructions_list();
  1335     int         block_from =   block->first_lir_instruction_id();
  1336     int         block_to =     block->last_lir_instruction_id();
  1338     assert(block_from == instructions->at(0)->id(), "must be");
  1339     assert(block_to   == instructions->at(instructions->length() - 1)->id(), "must be");
  1341     // Update intervals for registers live at the end of this block;
  1342     BitMap live = block->live_out();
  1343     int size = (int)live.size();
  1344     for (int number = (int)live.get_next_one_offset(0, size); number < size; number = (int)live.get_next_one_offset(number + 1, size)) {
  1345       assert(live.at(number), "should not stop here otherwise");
  1346       assert(number >= LIR_OprDesc::vreg_base, "fixed intervals must not be live on block bounds");
  1347       TRACE_LINEAR_SCAN(2, tty->print_cr("live in %d to %d", number, block_to + 2));
  1349       add_use(number, block_from, block_to + 2, noUse, T_ILLEGAL);
  1351       // add special use positions for loop-end blocks when the
  1352       // interval is used anywhere inside this loop.  It's possible
  1353       // that the block was part of a non-natural loop, so it might
  1354       // have an invalid loop index.
  1355       if (block->is_set(BlockBegin::linear_scan_loop_end_flag) &&
  1356           block->loop_index() != -1 &&
  1357           is_interval_in_loop(number, block->loop_index())) {
  1358         interval_at(number)->add_use_pos(block_to + 1, loopEndMarker);
  1362     // iterate all instructions of the block in reverse order.
  1363     // skip the first instruction because it is always a label
  1364     // definitions of intervals are processed before uses
  1365     assert(visitor.no_operands(instructions->at(0)), "first operation must always be a label");
  1366     for (int j = instructions->length() - 1; j >= 1; j--) {
  1367       LIR_Op* op = instructions->at(j);
  1368       int op_id = op->id();
  1370       // visit operation to collect all operands
  1371       visitor.visit(op);
  1373       // add a temp range for each register if operation destroys caller-save registers
  1374       if (visitor.has_call()) {
  1375         for (int k = 0; k < num_caller_save_registers; k++) {
  1376           add_temp(caller_save_registers[k], op_id, noUse, T_ILLEGAL);
  1378         TRACE_LINEAR_SCAN(4, tty->print_cr("operation destroys all caller-save registers"));
  1381       // Add any platform dependent temps
  1382       pd_add_temps(op);
  1384       // visit definitions (output and temp operands)
  1385       int k, n;
  1386       n = visitor.opr_count(LIR_OpVisitState::outputMode);
  1387       for (k = 0; k < n; k++) {
  1388         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, k);
  1389         assert(opr->is_register(), "visitor should only return register operands");
  1390         add_def(opr, op_id, use_kind_of_output_operand(op, opr));
  1393       n = visitor.opr_count(LIR_OpVisitState::tempMode);
  1394       for (k = 0; k < n; k++) {
  1395         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, k);
  1396         assert(opr->is_register(), "visitor should only return register operands");
  1397         add_temp(opr, op_id, mustHaveRegister);
  1400       // visit uses (input operands)
  1401       n = visitor.opr_count(LIR_OpVisitState::inputMode);
  1402       for (k = 0; k < n; k++) {
  1403         LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, k);
  1404         assert(opr->is_register(), "visitor should only return register operands");
  1405         add_use(opr, block_from, op_id, use_kind_of_input_operand(op, opr));
  1408       // Add uses of live locals from interpreter's point of view for proper
  1409       // debug information generation
  1410       // Treat these operands as temp values (if the life range is extended
  1411       // to a call site, the value would be in a register at the call otherwise)
  1412       n = visitor.info_count();
  1413       for (k = 0; k < n; k++) {
  1414         CodeEmitInfo* info = visitor.info_at(k);
  1415         ValueStack* stack = info->stack();
  1416         for_each_state_value(stack, value,
  1417           add_use(value, block_from, op_id + 1, noUse);
  1418         );
  1421       // special steps for some instructions (especially moves)
  1422       handle_method_arguments(op);
  1423       handle_doubleword_moves(op);
  1424       add_register_hints(op);
  1426     } // end of instruction iteration
  1427   } // end of block iteration
  1430   // add the range [0, 1[ to all fixed intervals
  1431   // -> the register allocator need not handle unhandled fixed intervals
  1432   for (int n = 0; n < LinearScan::nof_regs; n++) {
  1433     Interval* interval = interval_at(n);
  1434     if (interval != NULL) {
  1435       interval->add_range(0, 1);
  1441 // ********** Phase 5: actual register allocation
  1443 int LinearScan::interval_cmp(Interval** a, Interval** b) {
  1444   if (*a != NULL) {
  1445     if (*b != NULL) {
  1446       return (*a)->from() - (*b)->from();
  1447     } else {
  1448       return -1;
  1450   } else {
  1451     if (*b != NULL) {
  1452       return 1;
  1453     } else {
  1454       return 0;
  1459 #ifndef PRODUCT
  1460 bool LinearScan::is_sorted(IntervalArray* intervals) {
  1461   int from = -1;
  1462   int i, j;
  1463   for (i = 0; i < intervals->length(); i ++) {
  1464     Interval* it = intervals->at(i);
  1465     if (it != NULL) {
  1466       if (from > it->from()) {
  1467         assert(false, "");
  1468         return false;
  1470       from = it->from();
  1474   // check in both directions if sorted list and unsorted list contain same intervals
  1475   for (i = 0; i < interval_count(); i++) {
  1476     if (interval_at(i) != NULL) {
  1477       int num_found = 0;
  1478       for (j = 0; j < intervals->length(); j++) {
  1479         if (interval_at(i) == intervals->at(j)) {
  1480           num_found++;
  1483       assert(num_found == 1, "lists do not contain same intervals");
  1486   for (j = 0; j < intervals->length(); j++) {
  1487     int num_found = 0;
  1488     for (i = 0; i < interval_count(); i++) {
  1489       if (interval_at(i) == intervals->at(j)) {
  1490         num_found++;
  1493     assert(num_found == 1, "lists do not contain same intervals");
  1496   return true;
  1498 #endif
  1500 void LinearScan::add_to_list(Interval** first, Interval** prev, Interval* interval) {
  1501   if (*prev != NULL) {
  1502     (*prev)->set_next(interval);
  1503   } else {
  1504     *first = interval;
  1506   *prev = interval;
  1509 void LinearScan::create_unhandled_lists(Interval** list1, Interval** list2, bool (is_list1)(const Interval* i), bool (is_list2)(const Interval* i)) {
  1510   assert(is_sorted(_sorted_intervals), "interval list is not sorted");
  1512   *list1 = *list2 = Interval::end();
  1514   Interval* list1_prev = NULL;
  1515   Interval* list2_prev = NULL;
  1516   Interval* v;
  1518   const int n = _sorted_intervals->length();
  1519   for (int i = 0; i < n; i++) {
  1520     v = _sorted_intervals->at(i);
  1521     if (v == NULL) continue;
  1523     if (is_list1(v)) {
  1524       add_to_list(list1, &list1_prev, v);
  1525     } else if (is_list2 == NULL || is_list2(v)) {
  1526       add_to_list(list2, &list2_prev, v);
  1530   if (list1_prev != NULL) list1_prev->set_next(Interval::end());
  1531   if (list2_prev != NULL) list2_prev->set_next(Interval::end());
  1533   assert(list1_prev == NULL || list1_prev->next() == Interval::end(), "linear list ends not with sentinel");
  1534   assert(list2_prev == NULL || list2_prev->next() == Interval::end(), "linear list ends not with sentinel");
  1538 void LinearScan::sort_intervals_before_allocation() {
  1539   TIME_LINEAR_SCAN(timer_sort_intervals_before);
  1541   if (_needs_full_resort) {
  1542     // There is no known reason why this should occur but just in case...
  1543     assert(false, "should never occur");
  1544     // Re-sort existing interval list because an Interval::from() has changed
  1545     _sorted_intervals->sort(interval_cmp);
  1546     _needs_full_resort = false;
  1549   IntervalList* unsorted_list = &_intervals;
  1550   int unsorted_len = unsorted_list->length();
  1551   int sorted_len = 0;
  1552   int unsorted_idx;
  1553   int sorted_idx = 0;
  1554   int sorted_from_max = -1;
  1556   // calc number of items for sorted list (sorted list must not contain NULL values)
  1557   for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
  1558     if (unsorted_list->at(unsorted_idx) != NULL) {
  1559       sorted_len++;
  1562   IntervalArray* sorted_list = new IntervalArray(sorted_len);
  1564   // special sorting algorithm: the original interval-list is almost sorted,
  1565   // only some intervals are swapped. So this is much faster than a complete QuickSort
  1566   for (unsorted_idx = 0; unsorted_idx < unsorted_len; unsorted_idx++) {
  1567     Interval* cur_interval = unsorted_list->at(unsorted_idx);
  1569     if (cur_interval != NULL) {
  1570       int cur_from = cur_interval->from();
  1572       if (sorted_from_max <= cur_from) {
  1573         sorted_list->at_put(sorted_idx++, cur_interval);
  1574         sorted_from_max = cur_interval->from();
  1575       } else {
  1576         // the asumption that the intervals are already sorted failed,
  1577         // so this interval must be sorted in manually
  1578         int j;
  1579         for (j = sorted_idx - 1; j >= 0 && cur_from < sorted_list->at(j)->from(); j--) {
  1580           sorted_list->at_put(j + 1, sorted_list->at(j));
  1582         sorted_list->at_put(j + 1, cur_interval);
  1583         sorted_idx++;
  1587   _sorted_intervals = sorted_list;
  1588   assert(is_sorted(_sorted_intervals), "intervals unsorted");
  1591 void LinearScan::sort_intervals_after_allocation() {
  1592   TIME_LINEAR_SCAN(timer_sort_intervals_after);
  1594   if (_needs_full_resort) {
  1595     // Re-sort existing interval list because an Interval::from() has changed
  1596     _sorted_intervals->sort(interval_cmp);
  1597     _needs_full_resort = false;
  1600   IntervalArray* old_list      = _sorted_intervals;
  1601   IntervalList*  new_list      = _new_intervals_from_allocation;
  1602   int old_len = old_list->length();
  1603   int new_len = new_list->length();
  1605   if (new_len == 0) {
  1606     // no intervals have been added during allocation, so sorted list is already up to date
  1607     assert(is_sorted(_sorted_intervals), "intervals unsorted");
  1608     return;
  1611   // conventional sort-algorithm for new intervals
  1612   new_list->sort(interval_cmp);
  1614   // merge old and new list (both already sorted) into one combined list
  1615   IntervalArray* combined_list = new IntervalArray(old_len + new_len);
  1616   int old_idx = 0;
  1617   int new_idx = 0;
  1619   while (old_idx + new_idx < old_len + new_len) {
  1620     if (new_idx >= new_len || (old_idx < old_len && old_list->at(old_idx)->from() <= new_list->at(new_idx)->from())) {
  1621       combined_list->at_put(old_idx + new_idx, old_list->at(old_idx));
  1622       old_idx++;
  1623     } else {
  1624       combined_list->at_put(old_idx + new_idx, new_list->at(new_idx));
  1625       new_idx++;
  1629   _sorted_intervals = combined_list;
  1630   assert(is_sorted(_sorted_intervals), "intervals unsorted");
  1634 void LinearScan::allocate_registers() {
  1635   TIME_LINEAR_SCAN(timer_allocate_registers);
  1637   Interval* precolored_cpu_intervals, *not_precolored_cpu_intervals;
  1638   Interval* precolored_fpu_intervals, *not_precolored_fpu_intervals;
  1640   // allocate cpu registers
  1641   create_unhandled_lists(&precolored_cpu_intervals, &not_precolored_cpu_intervals,
  1642                          is_precolored_cpu_interval, is_virtual_cpu_interval);
  1644   // allocate fpu registers
  1645   create_unhandled_lists(&precolored_fpu_intervals, &not_precolored_fpu_intervals,
  1646                          is_precolored_fpu_interval, is_virtual_fpu_interval);
  1648   // the fpu interval allocation cannot be moved down below with the fpu section as
  1649   // the cpu_lsw.walk() changes interval positions.
  1651   LinearScanWalker cpu_lsw(this, precolored_cpu_intervals, not_precolored_cpu_intervals);
  1652   cpu_lsw.walk();
  1653   cpu_lsw.finish_allocation();
  1655   if (has_fpu_registers()) {
  1656     LinearScanWalker fpu_lsw(this, precolored_fpu_intervals, not_precolored_fpu_intervals);
  1657     fpu_lsw.walk();
  1658     fpu_lsw.finish_allocation();
  1663 // ********** Phase 6: resolve data flow
  1664 // (insert moves at edges between blocks if intervals have been split)
  1666 // wrapper for Interval::split_child_at_op_id that performs a bailout in product mode
  1667 // instead of returning NULL
  1668 Interval* LinearScan::split_child_at_op_id(Interval* interval, int op_id, LIR_OpVisitState::OprMode mode) {
  1669   Interval* result = interval->split_child_at_op_id(op_id, mode);
  1670   if (result != NULL) {
  1671     return result;
  1674   assert(false, "must find an interval, but do a clean bailout in product mode");
  1675   result = new Interval(LIR_OprDesc::vreg_base);
  1676   result->assign_reg(0);
  1677   result->set_type(T_INT);
  1678   BAILOUT_("LinearScan: interval is NULL", result);
  1682 Interval* LinearScan::interval_at_block_begin(BlockBegin* block, int reg_num) {
  1683   assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
  1684   assert(interval_at(reg_num) != NULL, "no interval found");
  1686   return split_child_at_op_id(interval_at(reg_num), block->first_lir_instruction_id(), LIR_OpVisitState::outputMode);
  1689 Interval* LinearScan::interval_at_block_end(BlockBegin* block, int reg_num) {
  1690   assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
  1691   assert(interval_at(reg_num) != NULL, "no interval found");
  1693   return split_child_at_op_id(interval_at(reg_num), block->last_lir_instruction_id() + 1, LIR_OpVisitState::outputMode);
  1696 Interval* LinearScan::interval_at_op_id(int reg_num, int op_id) {
  1697   assert(LinearScan::nof_regs <= reg_num && reg_num < num_virtual_regs(), "register number out of bounds");
  1698   assert(interval_at(reg_num) != NULL, "no interval found");
  1700   return split_child_at_op_id(interval_at(reg_num), op_id, LIR_OpVisitState::inputMode);
  1704 void LinearScan::resolve_collect_mappings(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
  1705   DEBUG_ONLY(move_resolver.check_empty());
  1707   const int num_regs = num_virtual_regs();
  1708   const int size = live_set_size();
  1709   const BitMap live_at_edge = to_block->live_in();
  1711   // visit all registers where the live_at_edge bit is set
  1712   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)) {
  1713     assert(r < num_regs, "live information set for not exisiting interval");
  1714     assert(from_block->live_out().at(r) && to_block->live_in().at(r), "interval not live at this edge");
  1716     Interval* from_interval = interval_at_block_end(from_block, r);
  1717     Interval* to_interval = interval_at_block_begin(to_block, r);
  1719     if (from_interval != to_interval && (from_interval->assigned_reg() != to_interval->assigned_reg() || from_interval->assigned_regHi() != to_interval->assigned_regHi())) {
  1720       // need to insert move instruction
  1721       move_resolver.add_mapping(from_interval, to_interval);
  1727 void LinearScan::resolve_find_insert_pos(BlockBegin* from_block, BlockBegin* to_block, MoveResolver &move_resolver) {
  1728   if (from_block->number_of_sux() <= 1) {
  1729     TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at end of from_block B%d", from_block->block_id()));
  1731     LIR_OpList* instructions = from_block->lir()->instructions_list();
  1732     LIR_OpBranch* branch = instructions->last()->as_OpBranch();
  1733     if (branch != NULL) {
  1734       // insert moves before branch
  1735       assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
  1736       move_resolver.set_insert_position(from_block->lir(), instructions->length() - 2);
  1737     } else {
  1738       move_resolver.set_insert_position(from_block->lir(), instructions->length() - 1);
  1741   } else {
  1742     TRACE_LINEAR_SCAN(4, tty->print_cr("inserting moves at beginning of to_block B%d", to_block->block_id()));
  1743 #ifdef ASSERT
  1744     assert(from_block->lir()->instructions_list()->at(0)->as_OpLabel() != NULL, "block does not start with a label");
  1746     // because the number of predecessor edges matches the number of
  1747     // successor edges, blocks which are reached by switch statements
  1748     // may have be more than one predecessor but it will be guaranteed
  1749     // that all predecessors will be the same.
  1750     for (int i = 0; i < to_block->number_of_preds(); i++) {
  1751       assert(from_block == to_block->pred_at(i), "all critical edges must be broken");
  1753 #endif
  1755     move_resolver.set_insert_position(to_block->lir(), 0);
  1760 // insert necessary moves (spilling or reloading) at edges between blocks if interval has been split
  1761 void LinearScan::resolve_data_flow() {
  1762   TIME_LINEAR_SCAN(timer_resolve_data_flow);
  1764   int num_blocks = block_count();
  1765   MoveResolver move_resolver(this);
  1766   BitMap block_completed(num_blocks);  block_completed.clear();
  1767   BitMap already_resolved(num_blocks); already_resolved.clear();
  1769   int i;
  1770   for (i = 0; i < num_blocks; i++) {
  1771     BlockBegin* block = block_at(i);
  1773     // check if block has only one predecessor and only one successor
  1774     if (block->number_of_preds() == 1 && block->number_of_sux() == 1 && block->number_of_exception_handlers() == 0) {
  1775       LIR_OpList* instructions = block->lir()->instructions_list();
  1776       assert(instructions->at(0)->code() == lir_label, "block must start with label");
  1777       assert(instructions->last()->code() == lir_branch, "block with successors must end with branch");
  1778       assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block with successor must end with unconditional branch");
  1780       // check if block is empty (only label and branch)
  1781       if (instructions->length() == 2) {
  1782         BlockBegin* pred = block->pred_at(0);
  1783         BlockBegin* sux = block->sux_at(0);
  1785         // prevent optimization of two consecutive blocks
  1786         if (!block_completed.at(pred->linear_scan_number()) && !block_completed.at(sux->linear_scan_number())) {
  1787           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()));
  1788           block_completed.set_bit(block->linear_scan_number());
  1790           // directly resolve between pred and sux (without looking at the empty block between)
  1791           resolve_collect_mappings(pred, sux, move_resolver);
  1792           if (move_resolver.has_mappings()) {
  1793             move_resolver.set_insert_position(block->lir(), 0);
  1794             move_resolver.resolve_and_append_moves();
  1802   for (i = 0; i < num_blocks; i++) {
  1803     if (!block_completed.at(i)) {
  1804       BlockBegin* from_block = block_at(i);
  1805       already_resolved.set_from(block_completed);
  1807       int num_sux = from_block->number_of_sux();
  1808       for (int s = 0; s < num_sux; s++) {
  1809         BlockBegin* to_block = from_block->sux_at(s);
  1811         // check for duplicate edges between the same blocks (can happen with switch blocks)
  1812         if (!already_resolved.at(to_block->linear_scan_number())) {
  1813           TRACE_LINEAR_SCAN(3, tty->print_cr("**** processing edge between B%d and B%d", from_block->block_id(), to_block->block_id()));
  1814           already_resolved.set_bit(to_block->linear_scan_number());
  1816           // collect all intervals that have been split between from_block and to_block
  1817           resolve_collect_mappings(from_block, to_block, move_resolver);
  1818           if (move_resolver.has_mappings()) {
  1819             resolve_find_insert_pos(from_block, to_block, move_resolver);
  1820             move_resolver.resolve_and_append_moves();
  1829 void LinearScan::resolve_exception_entry(BlockBegin* block, int reg_num, MoveResolver &move_resolver) {
  1830   if (interval_at(reg_num) == NULL) {
  1831     // if a phi function is never used, no interval is created -> ignore this
  1832     return;
  1835   Interval* interval = interval_at_block_begin(block, reg_num);
  1836   int reg = interval->assigned_reg();
  1837   int regHi = interval->assigned_regHi();
  1839   if ((reg < nof_regs && interval->always_in_memory()) ||
  1840       (use_fpu_stack_allocation() && reg >= pd_first_fpu_reg && reg <= pd_last_fpu_reg)) {
  1841     // the interval is split to get a short range that is located on the stack
  1842     // in the following two cases:
  1843     // * the interval started in memory (e.g. method parameter), but is currently in a register
  1844     //   this is an optimization for exception handling that reduces the number of moves that
  1845     //   are necessary for resolving the states when an exception uses this exception handler
  1846     // * the interval would be on the fpu stack at the begin of the exception handler
  1847     //   this is not allowed because of the complicated fpu stack handling on Intel
  1849     // range that will be spilled to memory
  1850     int from_op_id = block->first_lir_instruction_id();
  1851     int to_op_id = from_op_id + 1;  // short live range of length 1
  1852     assert(interval->from() <= from_op_id && interval->to() >= to_op_id,
  1853            "no split allowed between exception entry and first instruction");
  1855     if (interval->from() != from_op_id) {
  1856       // the part before from_op_id is unchanged
  1857       interval = interval->split(from_op_id);
  1858       interval->assign_reg(reg, regHi);
  1859       append_interval(interval);
  1860     } else {
  1861       _needs_full_resort = true;
  1863     assert(interval->from() == from_op_id, "must be true now");
  1865     Interval* spilled_part = interval;
  1866     if (interval->to() != to_op_id) {
  1867       // the part after to_op_id is unchanged
  1868       spilled_part = interval->split_from_start(to_op_id);
  1869       append_interval(spilled_part);
  1870       move_resolver.add_mapping(spilled_part, interval);
  1872     assign_spill_slot(spilled_part);
  1874     assert(spilled_part->from() == from_op_id && spilled_part->to() == to_op_id, "just checking");
  1878 void LinearScan::resolve_exception_entry(BlockBegin* block, MoveResolver &move_resolver) {
  1879   assert(block->is_set(BlockBegin::exception_entry_flag), "should not call otherwise");
  1880   DEBUG_ONLY(move_resolver.check_empty());
  1882   // visit all registers where the live_in bit is set
  1883   int size = live_set_size();
  1884   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)) {
  1885     resolve_exception_entry(block, r, move_resolver);
  1888   // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
  1889   for_each_phi_fun(block, phi,
  1890     resolve_exception_entry(block, phi->operand()->vreg_number(), move_resolver)
  1891   );
  1893   if (move_resolver.has_mappings()) {
  1894     // insert moves after first instruction
  1895     move_resolver.set_insert_position(block->lir(), 0);
  1896     move_resolver.resolve_and_append_moves();
  1901 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, int reg_num, Phi* phi, MoveResolver &move_resolver) {
  1902   if (interval_at(reg_num) == NULL) {
  1903     // if a phi function is never used, no interval is created -> ignore this
  1904     return;
  1907   // the computation of to_interval is equal to resolve_collect_mappings,
  1908   // but from_interval is more complicated because of phi functions
  1909   BlockBegin* to_block = handler->entry_block();
  1910   Interval* to_interval = interval_at_block_begin(to_block, reg_num);
  1912   if (phi != NULL) {
  1913     // phi function of the exception entry block
  1914     // no moves are created for this phi function in the LIR_Generator, so the
  1915     // interval at the throwing instruction must be searched using the operands
  1916     // of the phi function
  1917     Value from_value = phi->operand_at(handler->phi_operand());
  1919     // with phi functions it can happen that the same from_value is used in
  1920     // multiple mappings, so notify move-resolver that this is allowed
  1921     move_resolver.set_multiple_reads_allowed();
  1923     Constant* con = from_value->as_Constant();
  1924     if (con != NULL && !con->is_pinned()) {
  1925       // unpinned constants may have no register, so add mapping from constant to interval
  1926       move_resolver.add_mapping(LIR_OprFact::value_type(con->type()), to_interval);
  1927     } else {
  1928       // search split child at the throwing op_id
  1929       Interval* from_interval = interval_at_op_id(from_value->operand()->vreg_number(), throwing_op_id);
  1930       move_resolver.add_mapping(from_interval, to_interval);
  1933   } else {
  1934     // no phi function, so use reg_num also for from_interval
  1935     // search split child at the throwing op_id
  1936     Interval* from_interval = interval_at_op_id(reg_num, throwing_op_id);
  1937     if (from_interval != to_interval) {
  1938       // optimization to reduce number of moves: when to_interval is on stack and
  1939       // the stack slot is known to be always correct, then no move is necessary
  1940       if (!from_interval->always_in_memory() || from_interval->canonical_spill_slot() != to_interval->assigned_reg()) {
  1941         move_resolver.add_mapping(from_interval, to_interval);
  1947 void LinearScan::resolve_exception_edge(XHandler* handler, int throwing_op_id, MoveResolver &move_resolver) {
  1948   TRACE_LINEAR_SCAN(4, tty->print_cr("resolving exception handler B%d: throwing_op_id=%d", handler->entry_block()->block_id(), throwing_op_id));
  1950   DEBUG_ONLY(move_resolver.check_empty());
  1951   assert(handler->lir_op_id() == -1, "already processed this xhandler");
  1952   DEBUG_ONLY(handler->set_lir_op_id(throwing_op_id));
  1953   assert(handler->entry_code() == NULL, "code already present");
  1955   // visit all registers where the live_in bit is set
  1956   BlockBegin* block = handler->entry_block();
  1957   int size = live_set_size();
  1958   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)) {
  1959     resolve_exception_edge(handler, throwing_op_id, r, NULL, move_resolver);
  1962   // the live_in bits are not set for phi functions of the xhandler entry, so iterate them separately
  1963   for_each_phi_fun(block, phi,
  1964     resolve_exception_edge(handler, throwing_op_id, phi->operand()->vreg_number(), phi, move_resolver)
  1965   );
  1967   if (move_resolver.has_mappings()) {
  1968     LIR_List* entry_code = new LIR_List(compilation());
  1969     move_resolver.set_insert_position(entry_code, 0);
  1970     move_resolver.resolve_and_append_moves();
  1972     entry_code->jump(handler->entry_block());
  1973     handler->set_entry_code(entry_code);
  1978 void LinearScan::resolve_exception_handlers() {
  1979   MoveResolver move_resolver(this);
  1980   LIR_OpVisitState visitor;
  1981   int num_blocks = block_count();
  1983   int i;
  1984   for (i = 0; i < num_blocks; i++) {
  1985     BlockBegin* block = block_at(i);
  1986     if (block->is_set(BlockBegin::exception_entry_flag)) {
  1987       resolve_exception_entry(block, move_resolver);
  1991   for (i = 0; i < num_blocks; i++) {
  1992     BlockBegin* block = block_at(i);
  1993     LIR_List* ops = block->lir();
  1994     int num_ops = ops->length();
  1996     // iterate all instructions of the block. skip the first because it is always a label
  1997     assert(visitor.no_operands(ops->at(0)), "first operation must always be a label");
  1998     for (int j = 1; j < num_ops; j++) {
  1999       LIR_Op* op = ops->at(j);
  2000       int op_id = op->id();
  2002       if (op_id != -1 && has_info(op_id)) {
  2003         // visit operation to collect all operands
  2004         visitor.visit(op);
  2005         assert(visitor.info_count() > 0, "should not visit otherwise");
  2007         XHandlers* xhandlers = visitor.all_xhandler();
  2008         int n = xhandlers->length();
  2009         for (int k = 0; k < n; k++) {
  2010           resolve_exception_edge(xhandlers->handler_at(k), op_id, move_resolver);
  2013 #ifdef ASSERT
  2014       } else {
  2015         visitor.visit(op);
  2016         assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
  2017 #endif
  2024 // ********** Phase 7: assign register numbers back to LIR
  2025 // (includes computation of debug information and oop maps)
  2027 VMReg LinearScan::vm_reg_for_interval(Interval* interval) {
  2028   VMReg reg = interval->cached_vm_reg();
  2029   if (!reg->is_valid() ) {
  2030     reg = vm_reg_for_operand(operand_for_interval(interval));
  2031     interval->set_cached_vm_reg(reg);
  2033   assert(reg == vm_reg_for_operand(operand_for_interval(interval)), "wrong cached value");
  2034   return reg;
  2037 VMReg LinearScan::vm_reg_for_operand(LIR_Opr opr) {
  2038   assert(opr->is_oop(), "currently only implemented for oop operands");
  2039   return frame_map()->regname(opr);
  2043 LIR_Opr LinearScan::operand_for_interval(Interval* interval) {
  2044   LIR_Opr opr = interval->cached_opr();
  2045   if (opr->is_illegal()) {
  2046     opr = calc_operand_for_interval(interval);
  2047     interval->set_cached_opr(opr);
  2050   assert(opr == calc_operand_for_interval(interval), "wrong cached value");
  2051   return opr;
  2054 LIR_Opr LinearScan::calc_operand_for_interval(const Interval* interval) {
  2055   int assigned_reg = interval->assigned_reg();
  2056   BasicType type = interval->type();
  2058   if (assigned_reg >= nof_regs) {
  2059     // stack slot
  2060     assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2061     return LIR_OprFact::stack(assigned_reg - nof_regs, type);
  2063   } else {
  2064     // register
  2065     switch (type) {
  2066       case T_OBJECT: {
  2067         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2068         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2069         return LIR_OprFact::single_cpu_oop(assigned_reg);
  2072       case T_ADDRESS: {
  2073         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2074         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2075         return LIR_OprFact::single_cpu_address(assigned_reg);
  2078       case T_METADATA: {
  2079         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2080         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2081         return LIR_OprFact::single_cpu_metadata(assigned_reg);
  2084 #ifdef __SOFTFP__
  2085       case T_FLOAT:  // fall through
  2086 #endif // __SOFTFP__
  2087       case T_INT: {
  2088         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2089         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2090         return LIR_OprFact::single_cpu(assigned_reg);
  2093 #ifdef __SOFTFP__
  2094       case T_DOUBLE:  // fall through
  2095 #endif // __SOFTFP__
  2096       case T_LONG: {
  2097         int assigned_regHi = interval->assigned_regHi();
  2098         assert(assigned_reg >= pd_first_cpu_reg && assigned_reg <= pd_last_cpu_reg, "no cpu register");
  2099         assert(num_physical_regs(T_LONG) == 1 ||
  2100                (assigned_regHi >= pd_first_cpu_reg && assigned_regHi <= pd_last_cpu_reg), "no cpu register");
  2102         assert(assigned_reg != assigned_regHi, "invalid allocation");
  2103         assert(num_physical_regs(T_LONG) == 1 || assigned_reg < assigned_regHi,
  2104                "register numbers must be sorted (ensure that e.g. a move from eax,ebx to ebx,eax can not occur)");
  2105         assert((assigned_regHi != any_reg) ^ (num_physical_regs(T_LONG) == 1), "must be match");
  2106         if (requires_adjacent_regs(T_LONG)) {
  2107           assert(assigned_reg % 2 == 0 && assigned_reg + 1 == assigned_regHi, "must be sequential and even");
  2110 #ifdef _LP64
  2111         return LIR_OprFact::double_cpu(assigned_reg, assigned_reg);
  2112 #else
  2113 #if defined(SPARC) || defined(PPC) || defined(MIPS)
  2114         return LIR_OprFact::double_cpu(assigned_regHi, assigned_reg);
  2115 #else
  2116         return LIR_OprFact::double_cpu(assigned_reg, assigned_regHi);
  2117 #endif // SPARC
  2118 #endif // LP64
  2121 #ifndef __SOFTFP__
  2122       case T_FLOAT: {
  2123 #ifdef X86
  2124         if (UseSSE >= 1) {
  2125           assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= pd_last_xmm_reg, "no xmm register");
  2126           assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2127           return LIR_OprFact::single_xmm(assigned_reg - pd_first_xmm_reg);
  2129 #endif
  2131         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2132         assert(interval->assigned_regHi() == any_reg, "must not have hi register");
  2133         return LIR_OprFact::single_fpu(assigned_reg - pd_first_fpu_reg);
  2136       case T_DOUBLE: {
  2137 #ifdef X86
  2138         if (UseSSE >= 2) {
  2139           assert(assigned_reg >= pd_first_xmm_reg && assigned_reg <= pd_last_xmm_reg, "no xmm register");
  2140           assert(interval->assigned_regHi() == any_reg, "must not have hi register (double xmm values are stored in one register)");
  2141           return LIR_OprFact::double_xmm(assigned_reg - pd_first_xmm_reg);
  2143 #endif
  2145 #ifdef SPARC
  2146         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2147         assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
  2148         assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
  2149         LIR_Opr result = LIR_OprFact::double_fpu(interval->assigned_regHi() - pd_first_fpu_reg, assigned_reg - pd_first_fpu_reg);
  2150 #elif defined(ARM32)
  2151         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2152         assert(interval->assigned_regHi() >= pd_first_fpu_reg && interval->assigned_regHi() <= pd_last_fpu_reg, "no fpu register");
  2153         assert(assigned_reg % 2 == 0 && assigned_reg + 1 == interval->assigned_regHi(), "must be sequential and even");
  2154         LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg, interval->assigned_regHi() - pd_first_fpu_reg);
  2155 #else
  2156         assert(assigned_reg >= pd_first_fpu_reg && assigned_reg <= pd_last_fpu_reg, "no fpu register");
  2157         assert(interval->assigned_regHi() == any_reg, "must not have hi register (double fpu values are stored in one register on Intel)");
  2158         LIR_Opr result = LIR_OprFact::double_fpu(assigned_reg - pd_first_fpu_reg);
  2159 #endif
  2160         return result;
  2162 #endif // __SOFTFP__
  2164       default: {
  2165         ShouldNotReachHere();
  2166         return LIR_OprFact::illegalOpr;
  2172 LIR_Opr LinearScan::canonical_spill_opr(Interval* interval) {
  2173   assert(interval->canonical_spill_slot() >= nof_regs, "canonical spill slot not set");
  2174   return LIR_OprFact::stack(interval->canonical_spill_slot() - nof_regs, interval->type());
  2177 LIR_Opr LinearScan::color_lir_opr(LIR_Opr opr, int op_id, LIR_OpVisitState::OprMode mode) {
  2178   assert(opr->is_virtual(), "should not call this otherwise");
  2180   Interval* interval = interval_at(opr->vreg_number());
  2181   assert(interval != NULL, "interval must exist");
  2183   if (op_id != -1) {
  2184 #ifdef ASSERT
  2185     BlockBegin* block = block_of_op_with_id(op_id);
  2186     if (block->number_of_sux() <= 1 && op_id == block->last_lir_instruction_id()) {
  2187       // check if spill moves could have been appended at the end of this block, but
  2188       // before the branch instruction. So the split child information for this branch would
  2189       // be incorrect.
  2190       LIR_OpBranch* branch = block->lir()->instructions_list()->last()->as_OpBranch();
  2191       if (branch != NULL) {
  2192         if (block->live_out().at(opr->vreg_number())) {
  2193           assert(branch->cond() == lir_cond_always, "block does not end with an unconditional jump");
  2194           assert(false, "can't get split child for the last branch of a block because the information would be incorrect (moves are inserted before the branch in resolve_data_flow)");
  2198 #endif
  2200     // operands are not changed when an interval is split during allocation,
  2201     // so search the right interval here
  2202     interval = split_child_at_op_id(interval, op_id, mode);
  2205   LIR_Opr res = operand_for_interval(interval);
  2207 #ifdef X86
  2208   // new semantic for is_last_use: not only set on definite end of interval,
  2209   // but also before hole
  2210   // This may still miss some cases (e.g. for dead values), but it is not necessary that the
  2211   // last use information is completely correct
  2212   // information is only needed for fpu stack allocation
  2213   if (res->is_fpu_register()) {
  2214     if (opr->is_last_use() || op_id == interval->to() || (op_id != -1 && interval->has_hole_between(op_id, op_id + 1))) {
  2215       assert(op_id == -1 || !is_block_begin(op_id), "holes at begin of block may also result from control flow");
  2216       res = res->make_last_use();
  2219 #endif
  2221   assert(!gen()->is_vreg_flag_set(opr->vreg_number(), LIRGenerator::callee_saved) || !FrameMap::is_caller_save_register(res), "bad allocation");
  2223   return res;
  2227 #ifdef ASSERT
  2228 // some methods used to check correctness of debug information
  2230 void assert_no_register_values(GrowableArray<ScopeValue*>* values) {
  2231   if (values == NULL) {
  2232     return;
  2235   for (int i = 0; i < values->length(); i++) {
  2236     ScopeValue* value = values->at(i);
  2238     if (value->is_location()) {
  2239       Location location = ((LocationValue*)value)->location();
  2240       assert(location.where() == Location::on_stack, "value is in register");
  2245 void assert_no_register_values(GrowableArray<MonitorValue*>* values) {
  2246   if (values == NULL) {
  2247     return;
  2250   for (int i = 0; i < values->length(); i++) {
  2251     MonitorValue* value = values->at(i);
  2253     if (value->owner()->is_location()) {
  2254       Location location = ((LocationValue*)value->owner())->location();
  2255       assert(location.where() == Location::on_stack, "owner is in register");
  2257     assert(value->basic_lock().where() == Location::on_stack, "basic_lock is in register");
  2261 void assert_equal(Location l1, Location l2) {
  2262   assert(l1.where() == l2.where() && l1.type() == l2.type() && l1.offset() == l2.offset(), "");
  2265 void assert_equal(ScopeValue* v1, ScopeValue* v2) {
  2266   if (v1->is_location()) {
  2267     assert(v2->is_location(), "");
  2268     assert_equal(((LocationValue*)v1)->location(), ((LocationValue*)v2)->location());
  2269   } else if (v1->is_constant_int()) {
  2270     assert(v2->is_constant_int(), "");
  2271     assert(((ConstantIntValue*)v1)->value() == ((ConstantIntValue*)v2)->value(), "");
  2272   } else if (v1->is_constant_double()) {
  2273     assert(v2->is_constant_double(), "");
  2274     assert(((ConstantDoubleValue*)v1)->value() == ((ConstantDoubleValue*)v2)->value(), "");
  2275   } else if (v1->is_constant_long()) {
  2276     assert(v2->is_constant_long(), "");
  2277     assert(((ConstantLongValue*)v1)->value() == ((ConstantLongValue*)v2)->value(), "");
  2278   } else if (v1->is_constant_oop()) {
  2279     assert(v2->is_constant_oop(), "");
  2280     assert(((ConstantOopWriteValue*)v1)->value() == ((ConstantOopWriteValue*)v2)->value(), "");
  2281   } else {
  2282     ShouldNotReachHere();
  2286 void assert_equal(MonitorValue* m1, MonitorValue* m2) {
  2287   assert_equal(m1->owner(), m2->owner());
  2288   assert_equal(m1->basic_lock(), m2->basic_lock());
  2291 void assert_equal(IRScopeDebugInfo* d1, IRScopeDebugInfo* d2) {
  2292   assert(d1->scope() == d2->scope(), "not equal");
  2293   assert(d1->bci() == d2->bci(), "not equal");
  2295   if (d1->locals() != NULL) {
  2296     assert(d1->locals() != NULL && d2->locals() != NULL, "not equal");
  2297     assert(d1->locals()->length() == d2->locals()->length(), "not equal");
  2298     for (int i = 0; i < d1->locals()->length(); i++) {
  2299       assert_equal(d1->locals()->at(i), d2->locals()->at(i));
  2301   } else {
  2302     assert(d1->locals() == NULL && d2->locals() == NULL, "not equal");
  2305   if (d1->expressions() != NULL) {
  2306     assert(d1->expressions() != NULL && d2->expressions() != NULL, "not equal");
  2307     assert(d1->expressions()->length() == d2->expressions()->length(), "not equal");
  2308     for (int i = 0; i < d1->expressions()->length(); i++) {
  2309       assert_equal(d1->expressions()->at(i), d2->expressions()->at(i));
  2311   } else {
  2312     assert(d1->expressions() == NULL && d2->expressions() == NULL, "not equal");
  2315   if (d1->monitors() != NULL) {
  2316     assert(d1->monitors() != NULL && d2->monitors() != NULL, "not equal");
  2317     assert(d1->monitors()->length() == d2->monitors()->length(), "not equal");
  2318     for (int i = 0; i < d1->monitors()->length(); i++) {
  2319       assert_equal(d1->monitors()->at(i), d2->monitors()->at(i));
  2321   } else {
  2322     assert(d1->monitors() == NULL && d2->monitors() == NULL, "not equal");
  2325   if (d1->caller() != NULL) {
  2326     assert(d1->caller() != NULL && d2->caller() != NULL, "not equal");
  2327     assert_equal(d1->caller(), d2->caller());
  2328   } else {
  2329     assert(d1->caller() == NULL && d2->caller() == NULL, "not equal");
  2333 void check_stack_depth(CodeEmitInfo* info, int stack_end) {
  2334   if (info->stack()->bci() != SynchronizationEntryBCI && !info->scope()->method()->is_native()) {
  2335     Bytecodes::Code code = info->scope()->method()->java_code_at_bci(info->stack()->bci());
  2336     switch (code) {
  2337       case Bytecodes::_ifnull    : // fall through
  2338       case Bytecodes::_ifnonnull : // fall through
  2339       case Bytecodes::_ifeq      : // fall through
  2340       case Bytecodes::_ifne      : // fall through
  2341       case Bytecodes::_iflt      : // fall through
  2342       case Bytecodes::_ifge      : // fall through
  2343       case Bytecodes::_ifgt      : // fall through
  2344       case Bytecodes::_ifle      : // fall through
  2345       case Bytecodes::_if_icmpeq : // fall through
  2346       case Bytecodes::_if_icmpne : // fall through
  2347       case Bytecodes::_if_icmplt : // fall through
  2348       case Bytecodes::_if_icmpge : // fall through
  2349       case Bytecodes::_if_icmpgt : // fall through
  2350       case Bytecodes::_if_icmple : // fall through
  2351       case Bytecodes::_if_acmpeq : // fall through
  2352       case Bytecodes::_if_acmpne :
  2353         assert(stack_end >= -Bytecodes::depth(code), "must have non-empty expression stack at if bytecode");
  2354         break;
  2359 #endif // ASSERT
  2362 IntervalWalker* LinearScan::init_compute_oop_maps() {
  2363   // setup lists of potential oops for walking
  2364   Interval* oop_intervals;
  2365   Interval* non_oop_intervals;
  2367   create_unhandled_lists(&oop_intervals, &non_oop_intervals, is_oop_interval, NULL);
  2369   // intervals that have no oops inside need not to be processed
  2370   // to ensure a walking until the last instruction id, add a dummy interval
  2371   // with a high operation id
  2372   non_oop_intervals = new Interval(any_reg);
  2373   non_oop_intervals->add_range(max_jint - 2, max_jint - 1);
  2375   return new IntervalWalker(this, oop_intervals, non_oop_intervals);
  2379 OopMap* LinearScan::compute_oop_map(IntervalWalker* iw, LIR_Op* op, CodeEmitInfo* info, bool is_call_site) {
  2380   TRACE_LINEAR_SCAN(3, tty->print_cr("creating oop map at op_id %d", op->id()));
  2382   // walk before the current operation -> intervals that start at
  2383   // the operation (= output operands of the operation) are not
  2384   // included in the oop map
  2385   iw->walk_before(op->id());
  2387   int frame_size = frame_map()->framesize();
  2388   int arg_count = frame_map()->oop_map_arg_count();
  2389   OopMap* map = new OopMap(frame_size, arg_count);
  2391   // Iterate through active intervals
  2392   for (Interval* interval = iw->active_first(fixedKind); interval != Interval::end(); interval = interval->next()) {
  2393     int assigned_reg = interval->assigned_reg();
  2395     assert(interval->current_from() <= op->id() && op->id() <= interval->current_to(), "interval should not be active otherwise");
  2396     assert(interval->assigned_regHi() == any_reg, "oop must be single word");
  2397     assert(interval->reg_num() >= LIR_OprDesc::vreg_base, "fixed interval found");
  2399     // Check if this range covers the instruction. Intervals that
  2400     // start or end at the current operation are not included in the
  2401     // oop map, except in the case of patching moves.  For patching
  2402     // moves, any intervals which end at this instruction are included
  2403     // in the oop map since we may safepoint while doing the patch
  2404     // before we've consumed the inputs.
  2405     if (op->is_patching() || op->id() < interval->current_to()) {
  2407       // caller-save registers must not be included into oop-maps at calls
  2408       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");
  2410       VMReg name = vm_reg_for_interval(interval);
  2411       set_oop(map, name);
  2413       // Spill optimization: when the stack value is guaranteed to be always correct,
  2414       // then it must be added to the oop map even if the interval is currently in a register
  2415       if (interval->always_in_memory() &&
  2416           op->id() > interval->spill_definition_pos() &&
  2417           interval->assigned_reg() != interval->canonical_spill_slot()) {
  2418         assert(interval->spill_definition_pos() > 0, "position not set correctly");
  2419         assert(interval->canonical_spill_slot() >= LinearScan::nof_regs, "no spill slot assigned");
  2420         assert(interval->assigned_reg() < LinearScan::nof_regs, "interval is on stack, so stack slot is registered twice");
  2422         set_oop(map, frame_map()->slot_regname(interval->canonical_spill_slot() - LinearScan::nof_regs));
  2427   // add oops from lock stack
  2428   assert(info->stack() != NULL, "CodeEmitInfo must always have a stack");
  2429   int locks_count = info->stack()->total_locks_size();
  2430   for (int i = 0; i < locks_count; i++) {
  2431     set_oop(map, frame_map()->monitor_object_regname(i));
  2434   return map;
  2438 void LinearScan::compute_oop_map(IntervalWalker* iw, const LIR_OpVisitState &visitor, LIR_Op* op) {
  2439   assert(visitor.info_count() > 0, "no oop map needed");
  2441   // compute oop_map only for first CodeEmitInfo
  2442   // because it is (in most cases) equal for all other infos of the same operation
  2443   CodeEmitInfo* first_info = visitor.info_at(0);
  2444   OopMap* first_oop_map = compute_oop_map(iw, op, first_info, visitor.has_call());
  2446   for (int i = 0; i < visitor.info_count(); i++) {
  2447     CodeEmitInfo* info = visitor.info_at(i);
  2448     OopMap* oop_map = first_oop_map;
  2450     // compute worst case interpreter size in case of a deoptimization
  2451     _compilation->update_interpreter_frame_size(info->interpreter_frame_size());
  2453     if (info->stack()->locks_size() != first_info->stack()->locks_size()) {
  2454       // this info has a different number of locks then the precomputed oop map
  2455       // (possible for lock and unlock instructions) -> compute oop map with
  2456       // correct lock information
  2457       oop_map = compute_oop_map(iw, op, info, visitor.has_call());
  2460     if (info->_oop_map == NULL) {
  2461       info->_oop_map = oop_map;
  2462     } else {
  2463       // a CodeEmitInfo can not be shared between different LIR-instructions
  2464       // because interval splitting can occur anywhere between two instructions
  2465       // and so the oop maps must be different
  2466       // -> check if the already set oop_map is exactly the one calculated for this operation
  2467       assert(info->_oop_map == oop_map, "same CodeEmitInfo used for multiple LIR instructions");
  2473 // frequently used constants
  2474 // Allocate them with new so they are never destroyed (otherwise, a
  2475 // forced exit could destroy these objects while they are still in
  2476 // use).
  2477 ConstantOopWriteValue* LinearScan::_oop_null_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantOopWriteValue(NULL);
  2478 ConstantIntValue*      LinearScan::_int_m1_scope_value = new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(-1);
  2479 ConstantIntValue*      LinearScan::_int_0_scope_value =  new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(0);
  2480 ConstantIntValue*      LinearScan::_int_1_scope_value =  new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(1);
  2481 ConstantIntValue*      LinearScan::_int_2_scope_value =  new (ResourceObj::C_HEAP, mtCompiler) ConstantIntValue(2);
  2482 LocationValue*         _illegal_value = new (ResourceObj::C_HEAP, mtCompiler) LocationValue(Location());
  2484 void LinearScan::init_compute_debug_info() {
  2485   // cache for frequently used scope values
  2486   // (cpu registers and stack slots)
  2487   _scope_value_cache = ScopeValueArray((LinearScan::nof_cpu_regs + frame_map()->argcount() + max_spills()) * 2, NULL);
  2490 MonitorValue* LinearScan::location_for_monitor_index(int monitor_index) {
  2491   Location loc;
  2492   if (!frame_map()->location_for_monitor_object(monitor_index, &loc)) {
  2493     bailout("too large frame");
  2495   ScopeValue* object_scope_value = new LocationValue(loc);
  2497   if (!frame_map()->location_for_monitor_lock(monitor_index, &loc)) {
  2498     bailout("too large frame");
  2500   return new MonitorValue(object_scope_value, loc);
  2503 LocationValue* LinearScan::location_for_name(int name, Location::Type loc_type) {
  2504   Location loc;
  2505   if (!frame_map()->locations_for_slot(name, loc_type, &loc)) {
  2506     bailout("too large frame");
  2508   return new LocationValue(loc);
  2512 int LinearScan::append_scope_value_for_constant(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
  2513   assert(opr->is_constant(), "should not be called otherwise");
  2515   LIR_Const* c = opr->as_constant_ptr();
  2516   BasicType t = c->type();
  2517   switch (t) {
  2518     case T_OBJECT: {
  2519       jobject value = c->as_jobject();
  2520       if (value == NULL) {
  2521         scope_values->append(_oop_null_scope_value);
  2522       } else {
  2523         scope_values->append(new ConstantOopWriteValue(c->as_jobject()));
  2525       return 1;
  2528     case T_INT: // fall through
  2529     case T_FLOAT: {
  2530       int value = c->as_jint_bits();
  2531       switch (value) {
  2532         case -1: scope_values->append(_int_m1_scope_value); break;
  2533         case 0:  scope_values->append(_int_0_scope_value); break;
  2534         case 1:  scope_values->append(_int_1_scope_value); break;
  2535         case 2:  scope_values->append(_int_2_scope_value); break;
  2536         default: scope_values->append(new ConstantIntValue(c->as_jint_bits())); break;
  2538       return 1;
  2541     case T_LONG: // fall through
  2542     case T_DOUBLE: {
  2543 #ifdef _LP64
  2544       scope_values->append(_int_0_scope_value);
  2545       scope_values->append(new ConstantLongValue(c->as_jlong_bits()));
  2546 #else
  2547       if (hi_word_offset_in_bytes > lo_word_offset_in_bytes) {
  2548         scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
  2549         scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
  2550       } else {
  2551         scope_values->append(new ConstantIntValue(c->as_jint_lo_bits()));
  2552         scope_values->append(new ConstantIntValue(c->as_jint_hi_bits()));
  2554 #endif
  2555       return 2;
  2558     case T_ADDRESS: {
  2559 #ifdef _LP64
  2560       scope_values->append(new ConstantLongValue(c->as_jint()));
  2561 #else
  2562       scope_values->append(new ConstantIntValue(c->as_jint()));
  2563 #endif
  2564       return 1;
  2567     default:
  2568       ShouldNotReachHere();
  2569       return -1;
  2573 int LinearScan::append_scope_value_for_operand(LIR_Opr opr, GrowableArray<ScopeValue*>* scope_values) {
  2574   if (opr->is_single_stack()) {
  2575     int stack_idx = opr->single_stack_ix();
  2576     bool is_oop = opr->is_oop_register();
  2577     int cache_idx = (stack_idx + LinearScan::nof_cpu_regs) * 2 + (is_oop ? 1 : 0);
  2579     ScopeValue* sv = _scope_value_cache.at(cache_idx);
  2580     if (sv == NULL) {
  2581       Location::Type loc_type = is_oop ? Location::oop : Location::normal;
  2582       sv = location_for_name(stack_idx, loc_type);
  2583       _scope_value_cache.at_put(cache_idx, sv);
  2586     // check if cached value is correct
  2587     DEBUG_ONLY(assert_equal(sv, location_for_name(stack_idx, is_oop ? Location::oop : Location::normal)));
  2589     scope_values->append(sv);
  2590     return 1;
  2592   } else if (opr->is_single_cpu()) {
  2593     bool is_oop = opr->is_oop_register();
  2594     int cache_idx = opr->cpu_regnr() * 2 + (is_oop ? 1 : 0);
  2595     Location::Type int_loc_type = NOT_LP64(Location::normal) LP64_ONLY(Location::int_in_long);
  2597     ScopeValue* sv = _scope_value_cache.at(cache_idx);
  2598     if (sv == NULL) {
  2599       Location::Type loc_type = is_oop ? Location::oop : int_loc_type;
  2600       VMReg rname = frame_map()->regname(opr);
  2601       sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
  2602       _scope_value_cache.at_put(cache_idx, sv);
  2605     // check if cached value is correct
  2606     DEBUG_ONLY(assert_equal(sv, new LocationValue(Location::new_reg_loc(is_oop ? Location::oop : int_loc_type, frame_map()->regname(opr)))));
  2608     scope_values->append(sv);
  2609     return 1;
  2611 #ifdef X86
  2612   } else if (opr->is_single_xmm()) {
  2613     VMReg rname = opr->as_xmm_float_reg()->as_VMReg();
  2614     LocationValue* sv = new LocationValue(Location::new_reg_loc(Location::normal, rname));
  2616     scope_values->append(sv);
  2617     return 1;
  2618 #endif
  2620   } else if (opr->is_single_fpu()) {
  2621 #ifdef X86
  2622     // the exact location of fpu stack values is only known
  2623     // during fpu stack allocation, so the stack allocator object
  2624     // must be present
  2625     assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");
  2626     assert(_fpu_stack_allocator != NULL, "must be present");
  2627     opr = _fpu_stack_allocator->to_fpu_stack(opr);
  2628 #endif
  2630     Location::Type loc_type = float_saved_as_double ? Location::float_in_dbl : Location::normal;
  2631     VMReg rname = frame_map()->fpu_regname(opr->fpu_regnr());
  2632 #ifndef __SOFTFP__
  2633 #ifndef VM_LITTLE_ENDIAN
  2634     if (! float_saved_as_double) {
  2635       // On big endian system, we may have an issue if float registers use only
  2636       // the low half of the (same) double registers.
  2637       // Both the float and the double could have the same regnr but would correspond
  2638       // to two different addresses once saved.
  2640       // get next safely (no assertion checks)
  2641       VMReg next = VMRegImpl::as_VMReg(1+rname->value());
  2642       if (next->is_reg() &&
  2643           (next->as_FloatRegister() == rname->as_FloatRegister())) {
  2644         // the back-end does use the same numbering for the double and the float
  2645         rname = next; // VMReg for the low bits, e.g. the real VMReg for the float
  2648 #endif
  2649 #endif
  2650     LocationValue* sv = new LocationValue(Location::new_reg_loc(loc_type, rname));
  2652     scope_values->append(sv);
  2653     return 1;
  2655   } else {
  2656     // double-size operands
  2658     ScopeValue* first;
  2659     ScopeValue* second;
  2661     if (opr->is_double_stack()) {
  2662 #ifdef _LP64
  2663       Location loc1;
  2664       Location::Type loc_type = opr->type() == T_LONG ? Location::lng : Location::dbl;
  2665       if (!frame_map()->locations_for_slot(opr->double_stack_ix(), loc_type, &loc1, NULL)) {
  2666         bailout("too large frame");
  2668       // Does this reverse on x86 vs. sparc?
  2669       first =  new LocationValue(loc1);
  2670       second = _int_0_scope_value;
  2671 #else
  2672       Location loc1, loc2;
  2673       if (!frame_map()->locations_for_slot(opr->double_stack_ix(), Location::normal, &loc1, &loc2)) {
  2674         bailout("too large frame");
  2676       first =  new LocationValue(loc1);
  2677       second = new LocationValue(loc2);
  2678 #endif // _LP64
  2680     } else if (opr->is_double_cpu()) {
  2681 #ifdef _LP64
  2682       VMReg rname_first = opr->as_register_lo()->as_VMReg();
  2683       first = new LocationValue(Location::new_reg_loc(Location::lng, rname_first));
  2684       second = _int_0_scope_value;
  2685 #else
  2686       VMReg rname_first = opr->as_register_lo()->as_VMReg();
  2687       VMReg rname_second = opr->as_register_hi()->as_VMReg();
  2689       if (hi_word_offset_in_bytes < lo_word_offset_in_bytes) {
  2690         // lo/hi and swapped relative to first and second, so swap them
  2691         VMReg tmp = rname_first;
  2692         rname_first = rname_second;
  2693         rname_second = tmp;
  2696       first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
  2697       second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
  2698 #endif //_LP64
  2701 #ifdef X86
  2702     } else if (opr->is_double_xmm()) {
  2703       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation");
  2704       VMReg rname_first  = opr->as_xmm_double_reg()->as_VMReg();
  2705 #  ifdef _LP64
  2706       first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
  2707       second = _int_0_scope_value;
  2708 #  else
  2709       first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
  2710       // %%% This is probably a waste but we'll keep things as they were for now
  2711       if (true) {
  2712         VMReg rname_second = rname_first->next();
  2713         second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
  2715 #  endif
  2716 #endif
  2718     } else if (opr->is_double_fpu()) {
  2719       // On SPARC, fpu_regnrLo/fpu_regnrHi represents the two halves of
  2720       // the double as float registers in the native ordering. On X86,
  2721       // fpu_regnrLo is a FPU stack slot whose VMReg represents
  2722       // the low-order word of the double and fpu_regnrLo + 1 is the
  2723       // name for the other half.  *first and *second must represent the
  2724       // least and most significant words, respectively.
  2726 #ifdef X86
  2727       // the exact location of fpu stack values is only known
  2728       // during fpu stack allocation, so the stack allocator object
  2729       // must be present
  2730       assert(use_fpu_stack_allocation(), "should not have float stack values without fpu stack allocation (all floats must be SSE2)");
  2731       assert(_fpu_stack_allocator != NULL, "must be present");
  2732       opr = _fpu_stack_allocator->to_fpu_stack(opr);
  2734       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrLo is used)");
  2735 #endif
  2736 #ifdef SPARC
  2737       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi() + 1, "assumed in calculation (only fpu_regnrHi is used)");
  2738 #endif
  2739 #ifdef ARM32
  2740       assert(opr->fpu_regnrHi() == opr->fpu_regnrLo() + 1, "assumed in calculation (only fpu_regnrLo is used)");
  2741 #endif
  2742 #ifdef PPC
  2743       assert(opr->fpu_regnrLo() == opr->fpu_regnrHi(), "assumed in calculation (only fpu_regnrHi is used)");
  2744 #endif
  2746 #ifdef VM_LITTLE_ENDIAN
  2747       VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrLo());
  2748 #else
  2749       VMReg rname_first = frame_map()->fpu_regname(opr->fpu_regnrHi());
  2750 #endif
  2752 #ifdef _LP64
  2753       first = new LocationValue(Location::new_reg_loc(Location::dbl, rname_first));
  2754       second = _int_0_scope_value;
  2755 #else
  2756       first = new LocationValue(Location::new_reg_loc(Location::normal, rname_first));
  2757       // %%% This is probably a waste but we'll keep things as they were for now
  2758       if (true) {
  2759         VMReg rname_second = rname_first->next();
  2760         second = new LocationValue(Location::new_reg_loc(Location::normal, rname_second));
  2762 #endif
  2764     } else {
  2765       ShouldNotReachHere();
  2766       first = NULL;
  2767       second = NULL;
  2770     assert(first != NULL && second != NULL, "must be set");
  2771     // The convention the interpreter uses is that the second local
  2772     // holds the first raw word of the native double representation.
  2773     // This is actually reasonable, since locals and stack arrays
  2774     // grow downwards in all implementations.
  2775     // (If, on some machine, the interpreter's Java locals or stack
  2776     // were to grow upwards, the embedded doubles would be word-swapped.)
  2777     scope_values->append(second);
  2778     scope_values->append(first);
  2779     return 2;
  2784 int LinearScan::append_scope_value(int op_id, Value value, GrowableArray<ScopeValue*>* scope_values) {
  2785   if (value != NULL) {
  2786     LIR_Opr opr = value->operand();
  2787     Constant* con = value->as_Constant();
  2789     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)");
  2790     assert(con != NULL || opr->is_virtual(), "asumption: non-Constant instructions have only virtual operands");
  2792     if (con != NULL && !con->is_pinned() && !opr->is_constant()) {
  2793       // Unpinned constants may have a virtual operand for a part of the lifetime
  2794       // or may be illegal when it was optimized away,
  2795       // so always use a constant operand
  2796       opr = LIR_OprFact::value_type(con->type());
  2798     assert(opr->is_virtual() || opr->is_constant(), "other cases not allowed here");
  2800     if (opr->is_virtual()) {
  2801       LIR_OpVisitState::OprMode mode = LIR_OpVisitState::inputMode;
  2803       BlockBegin* block = block_of_op_with_id(op_id);
  2804       if (block->number_of_sux() == 1 && op_id == block->last_lir_instruction_id()) {
  2805         // generating debug information for the last instruction of a block.
  2806         // if this instruction is a branch, spill moves are inserted before this branch
  2807         // and so the wrong operand would be returned (spill moves at block boundaries are not
  2808         // considered in the live ranges of intervals)
  2809         // Solution: use the first op_id of the branch target block instead.
  2810         if (block->lir()->instructions_list()->last()->as_OpBranch() != NULL) {
  2811           if (block->live_out().at(opr->vreg_number())) {
  2812             op_id = block->sux_at(0)->first_lir_instruction_id();
  2813             mode = LIR_OpVisitState::outputMode;
  2818       // Get current location of operand
  2819       // The operand must be live because debug information is considered when building the intervals
  2820       // if the interval is not live, color_lir_opr will cause an assertion failure
  2821       opr = color_lir_opr(opr, op_id, mode);
  2822       assert(!has_call(op_id) || opr->is_stack() || !is_caller_save(reg_num(opr)), "can not have caller-save register operands at calls");
  2824       // Append to ScopeValue array
  2825       return append_scope_value_for_operand(opr, scope_values);
  2827     } else {
  2828       assert(value->as_Constant() != NULL, "all other instructions have only virtual operands");
  2829       assert(opr->is_constant(), "operand must be constant");
  2831       return append_scope_value_for_constant(opr, scope_values);
  2833   } else {
  2834     // append a dummy value because real value not needed
  2835     scope_values->append(_illegal_value);
  2836     return 1;
  2841 IRScopeDebugInfo* LinearScan::compute_debug_info_for_scope(int op_id, IRScope* cur_scope, ValueStack* cur_state, ValueStack* innermost_state) {
  2842   IRScopeDebugInfo* caller_debug_info = NULL;
  2844   ValueStack* caller_state = cur_state->caller_state();
  2845   if (caller_state != NULL) {
  2846     // process recursively to compute outermost scope first
  2847     caller_debug_info = compute_debug_info_for_scope(op_id, cur_scope->caller(), caller_state, innermost_state);
  2850   // initialize these to null.
  2851   // If we don't need deopt info or there are no locals, expressions or monitors,
  2852   // then these get recorded as no information and avoids the allocation of 0 length arrays.
  2853   GrowableArray<ScopeValue*>*   locals      = NULL;
  2854   GrowableArray<ScopeValue*>*   expressions = NULL;
  2855   GrowableArray<MonitorValue*>* monitors    = NULL;
  2857   // describe local variable values
  2858   int nof_locals = cur_state->locals_size();
  2859   if (nof_locals > 0) {
  2860     locals = new GrowableArray<ScopeValue*>(nof_locals);
  2862     int pos = 0;
  2863     while (pos < nof_locals) {
  2864       assert(pos < cur_state->locals_size(), "why not?");
  2866       Value local = cur_state->local_at(pos);
  2867       pos += append_scope_value(op_id, local, locals);
  2869       assert(locals->length() == pos, "must match");
  2871     assert(locals->length() == cur_scope->method()->max_locals(), "wrong number of locals");
  2872     assert(locals->length() == cur_state->locals_size(), "wrong number of locals");
  2873   } else if (cur_scope->method()->max_locals() > 0) {
  2874     assert(cur_state->kind() == ValueStack::EmptyExceptionState, "should be");
  2875     nof_locals = cur_scope->method()->max_locals();
  2876     locals = new GrowableArray<ScopeValue*>(nof_locals);
  2877     for(int i = 0; i < nof_locals; i++) {
  2878       locals->append(_illegal_value);
  2882   // describe expression stack
  2883   int nof_stack = cur_state->stack_size();
  2884   if (nof_stack > 0) {
  2885     expressions = new GrowableArray<ScopeValue*>(nof_stack);
  2887     int pos = 0;
  2888     while (pos < nof_stack) {
  2889       Value expression = cur_state->stack_at_inc(pos);
  2890       append_scope_value(op_id, expression, expressions);
  2892       assert(expressions->length() == pos, "must match");
  2894     assert(expressions->length() == cur_state->stack_size(), "wrong number of stack entries");
  2897   // describe monitors
  2898   int nof_locks = cur_state->locks_size();
  2899   if (nof_locks > 0) {
  2900     int lock_offset = cur_state->caller_state() != NULL ? cur_state->caller_state()->total_locks_size() : 0;
  2901     monitors = new GrowableArray<MonitorValue*>(nof_locks);
  2902     for (int i = 0; i < nof_locks; i++) {
  2903       monitors->append(location_for_monitor_index(lock_offset + i));
  2907   return new IRScopeDebugInfo(cur_scope, cur_state->bci(), locals, expressions, monitors, caller_debug_info);
  2911 void LinearScan::compute_debug_info(CodeEmitInfo* info, int op_id) {
  2912   TRACE_LINEAR_SCAN(3, tty->print_cr("creating debug information at op_id %d", op_id));
  2914   IRScope* innermost_scope = info->scope();
  2915   ValueStack* innermost_state = info->stack();
  2917   assert(innermost_scope != NULL && innermost_state != NULL, "why is it missing?");
  2919   DEBUG_ONLY(check_stack_depth(info, innermost_state->stack_size()));
  2921   if (info->_scope_debug_info == NULL) {
  2922     // compute debug information
  2923     info->_scope_debug_info = compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state);
  2924   } else {
  2925     // debug information already set. Check that it is correct from the current point of view
  2926     DEBUG_ONLY(assert_equal(info->_scope_debug_info, compute_debug_info_for_scope(op_id, innermost_scope, innermost_state, innermost_state)));
  2931 void LinearScan::assign_reg_num(LIR_OpList* instructions, IntervalWalker* iw) {
  2932   LIR_OpVisitState visitor;
  2933   int num_inst = instructions->length();
  2934   bool has_dead = false;
  2936   for (int j = 0; j < num_inst; j++) {
  2937     LIR_Op* op = instructions->at(j);
  2938     if (op == NULL) {  // this can happen when spill-moves are removed in eliminate_spill_moves
  2939       has_dead = true;
  2940       continue;
  2942     int op_id = op->id();
  2944     // visit instruction to get list of operands
  2945     visitor.visit(op);
  2947     // iterate all modes of the visitor and process all virtual operands
  2948     for_each_visitor_mode(mode) {
  2949       int n = visitor.opr_count(mode);
  2950       for (int k = 0; k < n; k++) {
  2951         LIR_Opr opr = visitor.opr_at(mode, k);
  2952         if (opr->is_virtual_register()) {
  2953           visitor.set_opr_at(mode, k, color_lir_opr(opr, op_id, mode));
  2958     if (visitor.info_count() > 0) {
  2959       // exception handling
  2960       if (compilation()->has_exception_handlers()) {
  2961         XHandlers* xhandlers = visitor.all_xhandler();
  2962         int n = xhandlers->length();
  2963         for (int k = 0; k < n; k++) {
  2964           XHandler* handler = xhandlers->handler_at(k);
  2965           if (handler->entry_code() != NULL) {
  2966             assign_reg_num(handler->entry_code()->instructions_list(), NULL);
  2969       } else {
  2970         assert(visitor.all_xhandler()->length() == 0, "missed exception handler");
  2973       // compute oop map
  2974       assert(iw != NULL, "needed for compute_oop_map");
  2975       compute_oop_map(iw, visitor, op);
  2977       // compute debug information
  2978       if (!use_fpu_stack_allocation()) {
  2979         // compute debug information if fpu stack allocation is not needed.
  2980         // when fpu stack allocation is needed, the debug information can not
  2981         // be computed here because the exact location of fpu operands is not known
  2982         // -> debug information is created inside the fpu stack allocator
  2983         int n = visitor.info_count();
  2984         for (int k = 0; k < n; k++) {
  2985           compute_debug_info(visitor.info_at(k), op_id);
  2990 #ifdef ASSERT
  2991     // make sure we haven't made the op invalid.
  2992     op->verify();
  2993 #endif
  2995     // remove useless moves
  2996     if (op->code() == lir_move) {
  2997       assert(op->as_Op1() != NULL, "move must be LIR_Op1");
  2998       LIR_Op1* move = (LIR_Op1*)op;
  2999       LIR_Opr src = move->in_opr();
  3000       LIR_Opr dst = move->result_opr();
  3001       if (dst == src ||
  3002           !dst->is_pointer() && !src->is_pointer() &&
  3003           src->is_same_register(dst)) {
  3004         instructions->at_put(j, NULL);
  3005         has_dead = true;
  3010   if (has_dead) {
  3011     // iterate all instructions of the block and remove all null-values.
  3012     int insert_point = 0;
  3013     for (int j = 0; j < num_inst; j++) {
  3014       LIR_Op* op = instructions->at(j);
  3015       if (op != NULL) {
  3016         if (insert_point != j) {
  3017           instructions->at_put(insert_point, op);
  3019         insert_point++;
  3022     instructions->truncate(insert_point);
  3026 void LinearScan::assign_reg_num() {
  3027   TIME_LINEAR_SCAN(timer_assign_reg_num);
  3029   init_compute_debug_info();
  3030   IntervalWalker* iw = init_compute_oop_maps();
  3032   int num_blocks = block_count();
  3033   for (int i = 0; i < num_blocks; i++) {
  3034     BlockBegin* block = block_at(i);
  3035     assign_reg_num(block->lir()->instructions_list(), iw);
  3040 void LinearScan::do_linear_scan() {
  3041   NOT_PRODUCT(_total_timer.begin_method());
  3043   number_instructions();
  3045   NOT_PRODUCT(print_lir(1, "Before Register Allocation"));
  3047   compute_local_live_sets();
  3048   compute_global_live_sets();
  3049   CHECK_BAILOUT();
  3051   build_intervals();
  3052   CHECK_BAILOUT();
  3053   sort_intervals_before_allocation();
  3055   NOT_PRODUCT(print_intervals("Before Register Allocation"));
  3056   NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_before_alloc));
  3058   allocate_registers();
  3059   CHECK_BAILOUT();
  3061   resolve_data_flow();
  3062   if (compilation()->has_exception_handlers()) {
  3063     resolve_exception_handlers();
  3065   // fill in number of spill slots into frame_map
  3066   propagate_spill_slots();
  3067   CHECK_BAILOUT();
  3069   NOT_PRODUCT(print_intervals("After Register Allocation"));
  3070   NOT_PRODUCT(print_lir(2, "LIR after register allocation:"));
  3072   sort_intervals_after_allocation();
  3074   DEBUG_ONLY(verify());
  3076   eliminate_spill_moves();
  3077   assign_reg_num();
  3078   CHECK_BAILOUT();
  3080   NOT_PRODUCT(print_lir(2, "LIR after assignment of register numbers:"));
  3081   NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_after_asign));
  3083   { TIME_LINEAR_SCAN(timer_allocate_fpu_stack);
  3085     if (use_fpu_stack_allocation()) {
  3086       allocate_fpu_stack(); // Only has effect on Intel
  3087       NOT_PRODUCT(print_lir(2, "LIR after FPU stack allocation:"));
  3091   { TIME_LINEAR_SCAN(timer_optimize_lir);
  3093     EdgeMoveOptimizer::optimize(ir()->code());
  3094     ControlFlowOptimizer::optimize(ir()->code());
  3095     // check that cfg is still correct after optimizations
  3096     ir()->verify();
  3099   NOT_PRODUCT(print_lir(1, "Before Code Generation", false));
  3100   NOT_PRODUCT(LinearScanStatistic::compute(this, _stat_final));
  3101   NOT_PRODUCT(_total_timer.end_method(this));
  3105 // ********** Printing functions
  3107 #ifndef PRODUCT
  3109 void LinearScan::print_timers(double total) {
  3110   _total_timer.print(total);
  3113 void LinearScan::print_statistics() {
  3114   _stat_before_alloc.print("before allocation");
  3115   _stat_after_asign.print("after assignment of register");
  3116   _stat_final.print("after optimization");
  3119 void LinearScan::print_bitmap(BitMap& b) {
  3120   for (unsigned int i = 0; i < b.size(); i++) {
  3121     if (b.at(i)) tty->print("%d ", i);
  3123   tty->cr();
  3126 void LinearScan::print_intervals(const char* label) {
  3127   if (TraceLinearScanLevel >= 1) {
  3128     int i;
  3129     tty->cr();
  3130     tty->print_cr("%s", label);
  3132     for (i = 0; i < interval_count(); i++) {
  3133       Interval* interval = interval_at(i);
  3134       if (interval != NULL) {
  3135         interval->print();
  3139     tty->cr();
  3140     tty->print_cr("--- Basic Blocks ---");
  3141     for (i = 0; i < block_count(); i++) {
  3142       BlockBegin* block = block_at(i);
  3143       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());
  3145     tty->cr();
  3146     tty->cr();
  3149   if (PrintCFGToFile) {
  3150     CFGPrinter::print_intervals(&_intervals, label);
  3154 void LinearScan::print_lir(int level, const char* label, bool hir_valid) {
  3155   if (TraceLinearScanLevel >= level) {
  3156     tty->cr();
  3157     tty->print_cr("%s", label);
  3158     print_LIR(ir()->linear_scan_order());
  3159     tty->cr();
  3162   if (level == 1 && PrintCFGToFile) {
  3163     CFGPrinter::print_cfg(ir()->linear_scan_order(), label, hir_valid, true);
  3167 #endif //PRODUCT
  3170 // ********** verification functions for allocation
  3171 // (check that all intervals have a correct register and that no registers are overwritten)
  3172 #ifdef ASSERT
  3174 void LinearScan::verify() {
  3175   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying intervals ******************************************"));
  3176   verify_intervals();
  3178   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that no oops are in fixed intervals ****************"));
  3179   verify_no_oops_in_fixed_intervals();
  3181   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying that unpinned constants are not alive across block boundaries"));
  3182   verify_constants();
  3184   TRACE_LINEAR_SCAN(2, tty->print_cr("********* verifying register allocation ********************************"));
  3185   verify_registers();
  3187   TRACE_LINEAR_SCAN(2, tty->print_cr("********* no errors found **********************************************"));
  3190 void LinearScan::verify_intervals() {
  3191   int len = interval_count();
  3192   bool has_error = false;
  3194   for (int i = 0; i < len; i++) {
  3195     Interval* i1 = interval_at(i);
  3196     if (i1 == NULL) continue;
  3198     i1->check_split_children();
  3200     if (i1->reg_num() != i) {
  3201       tty->print_cr("Interval %d is on position %d in list", i1->reg_num(), i); i1->print(); tty->cr();
  3202       has_error = true;
  3205     if (i1->reg_num() >= LIR_OprDesc::vreg_base && i1->type() == T_ILLEGAL) {
  3206       tty->print_cr("Interval %d has no type assigned", i1->reg_num()); i1->print(); tty->cr();
  3207       has_error = true;
  3210     if (i1->assigned_reg() == any_reg) {
  3211       tty->print_cr("Interval %d has no register assigned", i1->reg_num()); i1->print(); tty->cr();
  3212       has_error = true;
  3215     if (i1->assigned_reg() == i1->assigned_regHi()) {
  3216       tty->print_cr("Interval %d: low and high register equal", i1->reg_num()); i1->print(); tty->cr();
  3217       has_error = true;
  3220     if (!is_processed_reg_num(i1->assigned_reg())) {
  3221       tty->print_cr("Can not have an Interval for an ignored register"); i1->print(); tty->cr();
  3222       has_error = true;
  3225     if (i1->first() == Range::end()) {
  3226       tty->print_cr("Interval %d has no Range", i1->reg_num()); i1->print(); tty->cr();
  3227       has_error = true;
  3230     for (Range* r = i1->first(); r != Range::end(); r = r->next()) {
  3231       if (r->from() >= r->to()) {
  3232         tty->print_cr("Interval %d has zero length range", i1->reg_num()); i1->print(); tty->cr();
  3233         has_error = true;
  3237     for (int j = i + 1; j < len; j++) {
  3238       Interval* i2 = interval_at(j);
  3239       if (i2 == NULL) continue;
  3241       // special intervals that are created in MoveResolver
  3242       // -> ignore them because the range information has no meaning there
  3243       if (i1->from() == 1 && i1->to() == 2) continue;
  3244       if (i2->from() == 1 && i2->to() == 2) continue;
  3246       int r1 = i1->assigned_reg();
  3247       int r1Hi = i1->assigned_regHi();
  3248       int r2 = i2->assigned_reg();
  3249       int r2Hi = i2->assigned_regHi();
  3250       if (i1->intersects(i2) && (r1 == r2 || r1 == r2Hi || (r1Hi != any_reg && (r1Hi == r2 || r1Hi == r2Hi)))) {
  3251         tty->print_cr("Intervals %d and %d overlap and have the same register assigned", i1->reg_num(), i2->reg_num());
  3252         i1->print(); tty->cr();
  3253         i2->print(); tty->cr();
  3254         has_error = true;
  3259   assert(has_error == false, "register allocation invalid");
  3263 void LinearScan::verify_no_oops_in_fixed_intervals() {
  3264   Interval* fixed_intervals;
  3265   Interval* other_intervals;
  3266   create_unhandled_lists(&fixed_intervals, &other_intervals, is_precolored_cpu_interval, NULL);
  3268   // to ensure a walking until the last instruction id, add a dummy interval
  3269   // with a high operation id
  3270   other_intervals = new Interval(any_reg);
  3271   other_intervals->add_range(max_jint - 2, max_jint - 1);
  3272   IntervalWalker* iw = new IntervalWalker(this, fixed_intervals, other_intervals);
  3274   LIR_OpVisitState visitor;
  3275   for (int i = 0; i < block_count(); i++) {
  3276     BlockBegin* block = block_at(i);
  3278     LIR_OpList* instructions = block->lir()->instructions_list();
  3280     for (int j = 0; j < instructions->length(); j++) {
  3281       LIR_Op* op = instructions->at(j);
  3282       int op_id = op->id();
  3284       visitor.visit(op);
  3286       if (visitor.info_count() > 0) {
  3287         iw->walk_before(op->id());
  3288         bool check_live = true;
  3289         if (op->code() == lir_move) {
  3290           LIR_Op1* move = (LIR_Op1*)op;
  3291           check_live = (move->patch_code() == lir_patch_none);
  3293         LIR_OpBranch* branch = op->as_OpBranch();
  3294         if (branch != NULL && branch->stub() != NULL && branch->stub()->is_exception_throw_stub()) {
  3295           // Don't bother checking the stub in this case since the
  3296           // exception stub will never return to normal control flow.
  3297           check_live = false;
  3300         // Make sure none of the fixed registers is live across an
  3301         // oopmap since we can't handle that correctly.
  3302         if (check_live) {
  3303           for (Interval* interval = iw->active_first(fixedKind);
  3304                interval != Interval::end();
  3305                interval = interval->next()) {
  3306             if (interval->current_to() > op->id() + 1) {
  3307               // This interval is live out of this op so make sure
  3308               // that this interval represents some value that's
  3309               // referenced by this op either as an input or output.
  3310               bool ok = false;
  3311               for_each_visitor_mode(mode) {
  3312                 int n = visitor.opr_count(mode);
  3313                 for (int k = 0; k < n; k++) {
  3314                   LIR_Opr opr = visitor.opr_at(mode, k);
  3315                   if (opr->is_fixed_cpu()) {
  3316                     if (interval_at(reg_num(opr)) == interval) {
  3317                       ok = true;
  3318                       break;
  3320                     int hi = reg_numHi(opr);
  3321                     if (hi != -1 && interval_at(hi) == interval) {
  3322                       ok = true;
  3323                       break;
  3328               assert(ok, "fixed intervals should never be live across an oopmap point");
  3334       // oop-maps at calls do not contain registers, so check is not needed
  3335       if (!visitor.has_call()) {
  3337         for_each_visitor_mode(mode) {
  3338           int n = visitor.opr_count(mode);
  3339           for (int k = 0; k < n; k++) {
  3340             LIR_Opr opr = visitor.opr_at(mode, k);
  3342             if (opr->is_fixed_cpu() && opr->is_oop()) {
  3343               // operand is a non-virtual cpu register and contains an oop
  3344               TRACE_LINEAR_SCAN(4, op->print_on(tty); tty->print("checking operand "); opr->print(); tty->cr());
  3346               Interval* interval = interval_at(reg_num(opr));
  3347               assert(interval != NULL, "no interval");
  3349               if (mode == LIR_OpVisitState::inputMode) {
  3350                 if (interval->to() >= op_id + 1) {
  3351                   assert(interval->to() < op_id + 2 ||
  3352                          interval->has_hole_between(op_id, op_id + 2),
  3353                          "oop input operand live after instruction");
  3355               } else if (mode == LIR_OpVisitState::outputMode) {
  3356                 if (interval->from() <= op_id - 1) {
  3357                   assert(interval->has_hole_between(op_id - 1, op_id),
  3358                          "oop input operand live after instruction");
  3370 void LinearScan::verify_constants() {
  3371   int num_regs = num_virtual_regs();
  3372   int size = live_set_size();
  3373   int num_blocks = block_count();
  3375   for (int i = 0; i < num_blocks; i++) {
  3376     BlockBegin* block = block_at(i);
  3377     BitMap live_at_edge = block->live_in();
  3379     // visit all registers where the live_at_edge bit is set
  3380     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)) {
  3381       TRACE_LINEAR_SCAN(4, tty->print("checking interval %d of block B%d", r, block->block_id()));
  3383       Value value = gen()->instruction_for_vreg(r);
  3385       assert(value != NULL, "all intervals live across block boundaries must have Value");
  3386       assert(value->operand()->is_register() && value->operand()->is_virtual(), "value must have virtual operand");
  3387       assert(value->operand()->vreg_number() == r, "register number must match");
  3388       // TKR assert(value->as_Constant() == NULL || value->is_pinned(), "only pinned constants can be alive accross block boundaries");
  3394 class RegisterVerifier: public StackObj {
  3395  private:
  3396   LinearScan*   _allocator;
  3397   BlockList     _work_list;      // all blocks that must be processed
  3398   IntervalsList _saved_states;   // saved information of previous check
  3400   // simplified access to methods of LinearScan
  3401   Compilation*  compilation() const              { return _allocator->compilation(); }
  3402   Interval*     interval_at(int reg_num) const   { return _allocator->interval_at(reg_num); }
  3403   int           reg_num(LIR_Opr opr) const       { return _allocator->reg_num(opr); }
  3405   // currently, only registers are processed
  3406   int           state_size()                     { return LinearScan::nof_regs; }
  3408   // accessors
  3409   IntervalList* state_for_block(BlockBegin* block) { return _saved_states.at(block->block_id()); }
  3410   void          set_state_for_block(BlockBegin* block, IntervalList* saved_state) { _saved_states.at_put(block->block_id(), saved_state); }
  3411   void          add_to_work_list(BlockBegin* block) { if (!_work_list.contains(block)) _work_list.append(block); }
  3413   // helper functions
  3414   IntervalList* copy(IntervalList* input_state);
  3415   void          state_put(IntervalList* input_state, int reg, Interval* interval);
  3416   bool          check_state(IntervalList* input_state, int reg, Interval* interval);
  3418   void process_block(BlockBegin* block);
  3419   void process_xhandler(XHandler* xhandler, IntervalList* input_state);
  3420   void process_successor(BlockBegin* block, IntervalList* input_state);
  3421   void process_operations(LIR_List* ops, IntervalList* input_state);
  3423  public:
  3424   RegisterVerifier(LinearScan* allocator)
  3425     : _allocator(allocator)
  3426     , _work_list(16)
  3427     , _saved_states(BlockBegin::number_of_blocks(), NULL)
  3428   { }
  3430   void verify(BlockBegin* start);
  3431 };
  3434 // entry function from LinearScan that starts the verification
  3435 void LinearScan::verify_registers() {
  3436   RegisterVerifier verifier(this);
  3437   verifier.verify(block_at(0));
  3441 void RegisterVerifier::verify(BlockBegin* start) {
  3442   // setup input registers (method arguments) for first block
  3443   IntervalList* input_state = new IntervalList(state_size(), NULL);
  3444   CallingConvention* args = compilation()->frame_map()->incoming_arguments();
  3445   for (int n = 0; n < args->length(); n++) {
  3446     LIR_Opr opr = args->at(n);
  3447     if (opr->is_register()) {
  3448       Interval* interval = interval_at(reg_num(opr));
  3450       if (interval->assigned_reg() < state_size()) {
  3451         input_state->at_put(interval->assigned_reg(), interval);
  3453       if (interval->assigned_regHi() != LinearScan::any_reg && interval->assigned_regHi() < state_size()) {
  3454         input_state->at_put(interval->assigned_regHi(), interval);
  3459   set_state_for_block(start, input_state);
  3460   add_to_work_list(start);
  3462   // main loop for verification
  3463   do {
  3464     BlockBegin* block = _work_list.at(0);
  3465     _work_list.remove_at(0);
  3467     process_block(block);
  3468   } while (!_work_list.is_empty());
  3471 void RegisterVerifier::process_block(BlockBegin* block) {
  3472   TRACE_LINEAR_SCAN(2, tty->cr(); tty->print_cr("process_block B%d", block->block_id()));
  3474   // must copy state because it is modified
  3475   IntervalList* input_state = copy(state_for_block(block));
  3477   if (TraceLinearScanLevel >= 4) {
  3478     tty->print_cr("Input-State of intervals:");
  3479     tty->print("    ");
  3480     for (int i = 0; i < state_size(); i++) {
  3481       if (input_state->at(i) != NULL) {
  3482         tty->print(" %4d", input_state->at(i)->reg_num());
  3483       } else {
  3484         tty->print("   __");
  3487     tty->cr();
  3488     tty->cr();
  3491   // process all operations of the block
  3492   process_operations(block->lir(), input_state);
  3494   // iterate all successors
  3495   for (int i = 0; i < block->number_of_sux(); i++) {
  3496     process_successor(block->sux_at(i), input_state);
  3500 void RegisterVerifier::process_xhandler(XHandler* xhandler, IntervalList* input_state) {
  3501   TRACE_LINEAR_SCAN(2, tty->print_cr("process_xhandler B%d", xhandler->entry_block()->block_id()));
  3503   // must copy state because it is modified
  3504   input_state = copy(input_state);
  3506   if (xhandler->entry_code() != NULL) {
  3507     process_operations(xhandler->entry_code(), input_state);
  3509   process_successor(xhandler->entry_block(), input_state);
  3512 void RegisterVerifier::process_successor(BlockBegin* block, IntervalList* input_state) {
  3513   IntervalList* saved_state = state_for_block(block);
  3515   if (saved_state != NULL) {
  3516     // this block was already processed before.
  3517     // check if new input_state is consistent with saved_state
  3519     bool saved_state_correct = true;
  3520     for (int i = 0; i < state_size(); i++) {
  3521       if (input_state->at(i) != saved_state->at(i)) {
  3522         // current input_state and previous saved_state assume a different
  3523         // interval in this register -> assume that this register is invalid
  3524         if (saved_state->at(i) != NULL) {
  3525           // invalidate old calculation only if it assumed that
  3526           // register was valid. when the register was already invalid,
  3527           // then the old calculation was correct.
  3528           saved_state_correct = false;
  3529           saved_state->at_put(i, NULL);
  3531           TRACE_LINEAR_SCAN(4, tty->print_cr("process_successor B%d: invalidating slot %d", block->block_id(), i));
  3536     if (saved_state_correct) {
  3537       // already processed block with correct input_state
  3538       TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: previous visit already correct", block->block_id()));
  3539     } else {
  3540       // must re-visit this block
  3541       TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: must re-visit because input state changed", block->block_id()));
  3542       add_to_work_list(block);
  3545   } else {
  3546     // block was not processed before, so set initial input_state
  3547     TRACE_LINEAR_SCAN(2, tty->print_cr("process_successor B%d: initial visit", block->block_id()));
  3549     set_state_for_block(block, copy(input_state));
  3550     add_to_work_list(block);
  3555 IntervalList* RegisterVerifier::copy(IntervalList* input_state) {
  3556   IntervalList* copy_state = new IntervalList(input_state->length());
  3557   copy_state->push_all(input_state);
  3558   return copy_state;
  3561 void RegisterVerifier::state_put(IntervalList* input_state, int reg, Interval* interval) {
  3562   if (reg != LinearScan::any_reg && reg < state_size()) {
  3563     if (interval != NULL) {
  3564       TRACE_LINEAR_SCAN(4, tty->print_cr("        reg[%d] = %d", reg, interval->reg_num()));
  3565     } else if (input_state->at(reg) != NULL) {
  3566       TRACE_LINEAR_SCAN(4, tty->print_cr("        reg[%d] = NULL", reg));
  3569     input_state->at_put(reg, interval);
  3573 bool RegisterVerifier::check_state(IntervalList* input_state, int reg, Interval* interval) {
  3574   if (reg != LinearScan::any_reg && reg < state_size()) {
  3575     if (input_state->at(reg) != interval) {
  3576       tty->print_cr("!! Error in register allocation: register %d does not contain interval %d", reg, interval->reg_num());
  3577       return true;
  3580   return false;
  3583 void RegisterVerifier::process_operations(LIR_List* ops, IntervalList* input_state) {
  3584   // visit all instructions of the block
  3585   LIR_OpVisitState visitor;
  3586   bool has_error = false;
  3588   for (int i = 0; i < ops->length(); i++) {
  3589     LIR_Op* op = ops->at(i);
  3590     visitor.visit(op);
  3592     TRACE_LINEAR_SCAN(4, op->print_on(tty));
  3594     // check if input operands are correct
  3595     int j;
  3596     int n = visitor.opr_count(LIR_OpVisitState::inputMode);
  3597     for (j = 0; j < n; j++) {
  3598       LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::inputMode, j);
  3599       if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
  3600         Interval* interval = interval_at(reg_num(opr));
  3601         if (op->id() != -1) {
  3602           interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::inputMode);
  3605         has_error |= check_state(input_state, interval->assigned_reg(),   interval->split_parent());
  3606         has_error |= check_state(input_state, interval->assigned_regHi(), interval->split_parent());
  3608         // When an operand is marked with is_last_use, then the fpu stack allocator
  3609         // removes the register from the fpu stack -> the register contains no value
  3610         if (opr->is_last_use()) {
  3611           state_put(input_state, interval->assigned_reg(),   NULL);
  3612           state_put(input_state, interval->assigned_regHi(), NULL);
  3617     // invalidate all caller save registers at calls
  3618     if (visitor.has_call()) {
  3619       for (j = 0; j < FrameMap::nof_caller_save_cpu_regs(); j++) {
  3620         state_put(input_state, reg_num(FrameMap::caller_save_cpu_reg_at(j)), NULL);
  3622       for (j = 0; j < FrameMap::nof_caller_save_fpu_regs; j++) {
  3623         state_put(input_state, reg_num(FrameMap::caller_save_fpu_reg_at(j)), NULL);
  3626 #ifdef X86
  3627       for (j = 0; j < FrameMap::nof_caller_save_xmm_regs; j++) {
  3628         state_put(input_state, reg_num(FrameMap::caller_save_xmm_reg_at(j)), NULL);
  3630 #endif
  3633     // process xhandler before output and temp operands
  3634     XHandlers* xhandlers = visitor.all_xhandler();
  3635     n = xhandlers->length();
  3636     for (int k = 0; k < n; k++) {
  3637       process_xhandler(xhandlers->handler_at(k), input_state);
  3640     // set temp operands (some operations use temp operands also as output operands, so can't set them NULL)
  3641     n = visitor.opr_count(LIR_OpVisitState::tempMode);
  3642     for (j = 0; j < n; j++) {
  3643       LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::tempMode, j);
  3644       if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
  3645         Interval* interval = interval_at(reg_num(opr));
  3646         if (op->id() != -1) {
  3647           interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::tempMode);
  3650         state_put(input_state, interval->assigned_reg(),   interval->split_parent());
  3651         state_put(input_state, interval->assigned_regHi(), interval->split_parent());
  3655     // set output operands
  3656     n = visitor.opr_count(LIR_OpVisitState::outputMode);
  3657     for (j = 0; j < n; j++) {
  3658       LIR_Opr opr = visitor.opr_at(LIR_OpVisitState::outputMode, j);
  3659       if (opr->is_register() && LinearScan::is_processed_reg_num(reg_num(opr))) {
  3660         Interval* interval = interval_at(reg_num(opr));
  3661         if (op->id() != -1) {
  3662           interval = interval->split_child_at_op_id(op->id(), LIR_OpVisitState::outputMode);
  3665         state_put(input_state, interval->assigned_reg(),   interval->split_parent());
  3666         state_put(input_state, interval->assigned_regHi(), interval->split_parent());
  3670   assert(has_error == false, "Error in register allocation");
  3673 #endif // ASSERT
  3677 // **** Implementation of MoveResolver ******************************
  3679 MoveResolver::MoveResolver(LinearScan* allocator) :
  3680   _allocator(allocator),
  3681   _multiple_reads_allowed(false),
  3682   _mapping_from(8),
  3683   _mapping_from_opr(8),
  3684   _mapping_to(8),
  3685   _insert_list(NULL),
  3686   _insert_idx(-1),
  3687   _insertion_buffer()
  3689   for (int i = 0; i < LinearScan::nof_regs; i++) {
  3690     _register_blocked[i] = 0;
  3692   DEBUG_ONLY(check_empty());
  3696 #ifdef ASSERT
  3698 void MoveResolver::check_empty() {
  3699   assert(_mapping_from.length() == 0 && _mapping_from_opr.length() == 0 && _mapping_to.length() == 0, "list must be empty before and after processing");
  3700   for (int i = 0; i < LinearScan::nof_regs; i++) {
  3701     assert(register_blocked(i) == 0, "register map must be empty before and after processing");
  3703   assert(_multiple_reads_allowed == false, "must have default value");
  3706 void MoveResolver::verify_before_resolve() {
  3707   assert(_mapping_from.length() == _mapping_from_opr.length(), "length must be equal");
  3708   assert(_mapping_from.length() == _mapping_to.length(), "length must be equal");
  3709   assert(_insert_list != NULL && _insert_idx != -1, "insert position not set");
  3711   int i, j;
  3712   if (!_multiple_reads_allowed) {
  3713     for (i = 0; i < _mapping_from.length(); i++) {
  3714       for (j = i + 1; j < _mapping_from.length(); j++) {
  3715         assert(_mapping_from.at(i) == NULL || _mapping_from.at(i) != _mapping_from.at(j), "cannot read from same interval twice");
  3720   for (i = 0; i < _mapping_to.length(); i++) {
  3721     for (j = i + 1; j < _mapping_to.length(); j++) {
  3722       assert(_mapping_to.at(i) != _mapping_to.at(j), "cannot write to same interval twice");
  3727   BitMap used_regs(LinearScan::nof_regs + allocator()->frame_map()->argcount() + allocator()->max_spills());
  3728   used_regs.clear();
  3729   if (!_multiple_reads_allowed) {
  3730     for (i = 0; i < _mapping_from.length(); i++) {
  3731       Interval* it = _mapping_from.at(i);
  3732       if (it != NULL) {
  3733         assert(!used_regs.at(it->assigned_reg()), "cannot read from same register twice");
  3734         used_regs.set_bit(it->assigned_reg());
  3736         if (it->assigned_regHi() != LinearScan::any_reg) {
  3737           assert(!used_regs.at(it->assigned_regHi()), "cannot read from same register twice");
  3738           used_regs.set_bit(it->assigned_regHi());
  3744   used_regs.clear();
  3745   for (i = 0; i < _mapping_to.length(); i++) {
  3746     Interval* it = _mapping_to.at(i);
  3747     assert(!used_regs.at(it->assigned_reg()), "cannot write to same register twice");
  3748     used_regs.set_bit(it->assigned_reg());
  3750     if (it->assigned_regHi() != LinearScan::any_reg) {
  3751       assert(!used_regs.at(it->assigned_regHi()), "cannot write to same register twice");
  3752       used_regs.set_bit(it->assigned_regHi());
  3756   used_regs.clear();
  3757   for (i = 0; i < _mapping_from.length(); i++) {
  3758     Interval* it = _mapping_from.at(i);
  3759     if (it != NULL && it->assigned_reg() >= LinearScan::nof_regs) {
  3760       used_regs.set_bit(it->assigned_reg());
  3763   for (i = 0; i < _mapping_to.length(); i++) {
  3764     Interval* it = _mapping_to.at(i);
  3765     assert(!used_regs.at(it->assigned_reg()) || it->assigned_reg() == _mapping_from.at(i)->assigned_reg(), "stack slots used in _mapping_from must be disjoint to _mapping_to");
  3769 #endif // ASSERT
  3772 // mark assigned_reg and assigned_regHi of the interval as blocked
  3773 void MoveResolver::block_registers(Interval* it) {
  3774   int reg = it->assigned_reg();
  3775   if (reg < LinearScan::nof_regs) {
  3776     assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
  3777     set_register_blocked(reg, 1);
  3779   reg = it->assigned_regHi();
  3780   if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
  3781     assert(_multiple_reads_allowed || register_blocked(reg) == 0, "register already marked as used");
  3782     set_register_blocked(reg, 1);
  3786 // mark assigned_reg and assigned_regHi of the interval as unblocked
  3787 void MoveResolver::unblock_registers(Interval* it) {
  3788   int reg = it->assigned_reg();
  3789   if (reg < LinearScan::nof_regs) {
  3790     assert(register_blocked(reg) > 0, "register already marked as unused");
  3791     set_register_blocked(reg, -1);
  3793   reg = it->assigned_regHi();
  3794   if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
  3795     assert(register_blocked(reg) > 0, "register already marked as unused");
  3796     set_register_blocked(reg, -1);
  3800 // check if assigned_reg and assigned_regHi of the to-interval are not blocked (or only blocked by from)
  3801 bool MoveResolver::save_to_process_move(Interval* from, Interval* to) {
  3802   int from_reg = -1;
  3803   int from_regHi = -1;
  3804   if (from != NULL) {
  3805     from_reg = from->assigned_reg();
  3806     from_regHi = from->assigned_regHi();
  3809   int reg = to->assigned_reg();
  3810   if (reg < LinearScan::nof_regs) {
  3811     if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
  3812       return false;
  3815   reg = to->assigned_regHi();
  3816   if (reg != LinearScan::any_reg && reg < LinearScan::nof_regs) {
  3817     if (register_blocked(reg) > 1 || (register_blocked(reg) == 1 && reg != from_reg && reg != from_regHi)) {
  3818       return false;
  3822   return true;
  3826 void MoveResolver::create_insertion_buffer(LIR_List* list) {
  3827   assert(!_insertion_buffer.initialized(), "overwriting existing buffer");
  3828   _insertion_buffer.init(list);
  3831 void MoveResolver::append_insertion_buffer() {
  3832   if (_insertion_buffer.initialized()) {
  3833     _insertion_buffer.lir_list()->append(&_insertion_buffer);
  3835   assert(!_insertion_buffer.initialized(), "must be uninitialized now");
  3837   _insert_list = NULL;
  3838   _insert_idx = -1;
  3841 void MoveResolver::insert_move(Interval* from_interval, Interval* to_interval) {
  3842   assert(from_interval->reg_num() != to_interval->reg_num(), "from and to interval equal");
  3843   assert(from_interval->type() == to_interval->type(), "move between different types");
  3844   assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");
  3845   assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
  3847   LIR_Opr from_opr = LIR_OprFact::virtual_register(from_interval->reg_num(), from_interval->type());
  3848   LIR_Opr to_opr = LIR_OprFact::virtual_register(to_interval->reg_num(), to_interval->type());
  3850   if (!_multiple_reads_allowed) {
  3851     // the last_use flag is an optimization for FPU stack allocation. When the same
  3852     // input interval is used in more than one move, then it is too difficult to determine
  3853     // if this move is really the last use.
  3854     from_opr = from_opr->make_last_use();
  3856   _insertion_buffer.move(_insert_idx, from_opr, to_opr);
  3858   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()));
  3861 void MoveResolver::insert_move(LIR_Opr from_opr, Interval* to_interval) {
  3862   assert(from_opr->type() == to_interval->type(), "move between different types");
  3863   assert(_insert_list != NULL && _insert_idx != -1, "must setup insert position first");
  3864   assert(_insertion_buffer.lir_list() == _insert_list, "wrong insertion buffer");
  3866   LIR_Opr to_opr = LIR_OprFact::virtual_register(to_interval->reg_num(), to_interval->type());
  3867   _insertion_buffer.move(_insert_idx, from_opr, to_opr);
  3869   TRACE_LINEAR_SCAN(4, tty->print("MoveResolver: inserted move from constant "); from_opr->print(); tty->print_cr("  to %d (%d, %d)", to_interval->reg_num(), to_interval->assigned_reg(), to_interval->assigned_regHi()));
  3873 void MoveResolver::resolve_mappings() {
  3874   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));
  3875   DEBUG_ONLY(verify_before_resolve());
  3877   // Block all registers that are used as input operands of a move.
  3878   // When a register is blocked, no move to this register is emitted.
  3879   // This is necessary for detecting cycles in moves.
  3880   int i;
  3881   for (i = _mapping_from.length() - 1; i >= 0; i--) {
  3882     Interval* from_interval = _mapping_from.at(i);
  3883     if (from_interval != NULL) {
  3884       block_registers(from_interval);
  3888   int spill_candidate = -1;
  3889   while (_mapping_from.length() > 0) {
  3890     bool processed_interval = false;
  3892     for (i = _mapping_from.length() - 1; i >= 0; i--) {
  3893       Interval* from_interval = _mapping_from.at(i);
  3894       Interval* to_interval = _mapping_to.at(i);
  3896       if (save_to_process_move(from_interval, to_interval)) {
  3897         // this inverval can be processed because target is free
  3898         if (from_interval != NULL) {
  3899           insert_move(from_interval, to_interval);
  3900           unblock_registers(from_interval);
  3901         } else {
  3902           insert_move(_mapping_from_opr.at(i), to_interval);
  3904         _mapping_from.remove_at(i);
  3905         _mapping_from_opr.remove_at(i);
  3906         _mapping_to.remove_at(i);
  3908         processed_interval = true;
  3909       } else if (from_interval != NULL && from_interval->assigned_reg() < LinearScan::nof_regs) {
  3910         // this interval cannot be processed now because target is not free
  3911         // it starts in a register, so it is a possible candidate for spilling
  3912         spill_candidate = i;
  3916     if (!processed_interval) {
  3917       // no move could be processed because there is a cycle in the move list
  3918       // (e.g. r1 -> r2, r2 -> r1), so one interval must be spilled to memory
  3919       assert(spill_candidate != -1, "no interval in register for spilling found");
  3921       // create a new spill interval and assign a stack slot to it
  3922       Interval* from_interval = _mapping_from.at(spill_candidate);
  3923       Interval* spill_interval = new Interval(-1);
  3924       spill_interval->set_type(from_interval->type());
  3926       // add a dummy range because real position is difficult to calculate
  3927       // Note: this range is a special case when the integrity of the allocation is checked
  3928       spill_interval->add_range(1, 2);
  3930       //       do not allocate a new spill slot for temporary interval, but
  3931       //       use spill slot assigned to from_interval. Otherwise moves from
  3932       //       one stack slot to another can happen (not allowed by LIR_Assembler
  3933       int spill_slot = from_interval->canonical_spill_slot();
  3934       if (spill_slot < 0) {
  3935         spill_slot = allocator()->allocate_spill_slot(type2spill_size[spill_interval->type()] == 2);
  3936         from_interval->set_canonical_spill_slot(spill_slot);
  3938       spill_interval->assign_reg(spill_slot);
  3939       allocator()->append_interval(spill_interval);
  3941       TRACE_LINEAR_SCAN(4, tty->print_cr("created new Interval %d for spilling", spill_interval->reg_num()));
  3943       // insert a move from register to stack and update the mapping
  3944       insert_move(from_interval, spill_interval);
  3945       _mapping_from.at_put(spill_candidate, spill_interval);
  3946       unblock_registers(from_interval);
  3950   // reset to default value
  3951   _multiple_reads_allowed = false;
  3953   // check that all intervals have been processed
  3954   DEBUG_ONLY(check_empty());
  3958 void MoveResolver::set_insert_position(LIR_List* insert_list, int insert_idx) {
  3959   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));
  3960   assert(_insert_list == NULL && _insert_idx == -1, "use move_insert_position instead of set_insert_position when data already set");
  3962   create_insertion_buffer(insert_list);
  3963   _insert_list = insert_list;
  3964   _insert_idx = insert_idx;
  3967 void MoveResolver::move_insert_position(LIR_List* insert_list, int insert_idx) {
  3968   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));
  3970   if (_insert_list != NULL && (insert_list != _insert_list || insert_idx != _insert_idx)) {
  3971     // insert position changed -> resolve current mappings
  3972     resolve_mappings();
  3975   if (insert_list != _insert_list) {
  3976     // block changed -> append insertion_buffer because it is
  3977     // bound to a specific block and create a new insertion_buffer
  3978     append_insertion_buffer();
  3979     create_insertion_buffer(insert_list);
  3982   _insert_list = insert_list;
  3983   _insert_idx = insert_idx;
  3986 void MoveResolver::add_mapping(Interval* from_interval, Interval* to_interval) {
  3987   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()));
  3989   _mapping_from.append(from_interval);
  3990   _mapping_from_opr.append(LIR_OprFact::illegalOpr);
  3991   _mapping_to.append(to_interval);
  3995 void MoveResolver::add_mapping(LIR_Opr from_opr, Interval* to_interval) {
  3996   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()));
  3997   assert(from_opr->is_constant(), "only for constants");
  3999   _mapping_from.append(NULL);
  4000   _mapping_from_opr.append(from_opr);
  4001   _mapping_to.append(to_interval);
  4004 void MoveResolver::resolve_and_append_moves() {
  4005   if (has_mappings()) {
  4006     resolve_mappings();
  4008   append_insertion_buffer();
  4013 // **** Implementation of Range *************************************
  4015 Range::Range(int from, int to, Range* next) :
  4016   _from(from),
  4017   _to(to),
  4018   _next(next)
  4022 // initialize sentinel
  4023 Range* Range::_end = NULL;
  4024 void Range::initialize(Arena* arena) {
  4025   _end = new (arena) Range(max_jint, max_jint, NULL);
  4028 int Range::intersects_at(Range* r2) const {
  4029   const Range* r1 = this;
  4031   assert(r1 != NULL && r2 != NULL, "null ranges not allowed");
  4032   assert(r1 != _end && r2 != _end, "empty ranges not allowed");
  4034   do {
  4035     if (r1->from() < r2->from()) {
  4036       if (r1->to() <= r2->from()) {
  4037         r1 = r1->next(); if (r1 == _end) return -1;
  4038       } else {
  4039         return r2->from();
  4041     } else if (r2->from() < r1->from()) {
  4042       if (r2->to() <= r1->from()) {
  4043         r2 = r2->next(); if (r2 == _end) return -1;
  4044       } else {
  4045         return r1->from();
  4047     } else { // r1->from() == r2->from()
  4048       if (r1->from() == r1->to()) {
  4049         r1 = r1->next(); if (r1 == _end) return -1;
  4050       } else if (r2->from() == r2->to()) {
  4051         r2 = r2->next(); if (r2 == _end) return -1;
  4052       } else {
  4053         return r1->from();
  4056   } while (true);
  4059 #ifndef PRODUCT
  4060 void Range::print(outputStream* out) const {
  4061   out->print("[%d, %d[ ", _from, _to);
  4063 #endif
  4067 // **** Implementation of Interval **********************************
  4069 // initialize sentinel
  4070 Interval* Interval::_end = NULL;
  4071 void Interval::initialize(Arena* arena) {
  4072   Range::initialize(arena);
  4073   _end = new (arena) Interval(-1);
  4076 Interval::Interval(int reg_num) :
  4077   _reg_num(reg_num),
  4078   _type(T_ILLEGAL),
  4079   _first(Range::end()),
  4080   _use_pos_and_kinds(12),
  4081   _current(Range::end()),
  4082   _next(_end),
  4083   _state(invalidState),
  4084   _assigned_reg(LinearScan::any_reg),
  4085   _assigned_regHi(LinearScan::any_reg),
  4086   _cached_to(-1),
  4087   _cached_opr(LIR_OprFact::illegalOpr),
  4088   _cached_vm_reg(VMRegImpl::Bad()),
  4089   _split_children(0),
  4090   _canonical_spill_slot(-1),
  4091   _insert_move_when_activated(false),
  4092   _register_hint(NULL),
  4093   _spill_state(noDefinitionFound),
  4094   _spill_definition_pos(-1)
  4096   _split_parent = this;
  4097   _current_split_child = this;
  4100 int Interval::calc_to() {
  4101   assert(_first != Range::end(), "interval has no range");
  4103   Range* r = _first;
  4104   while (r->next() != Range::end()) {
  4105     r = r->next();
  4107   return r->to();
  4111 #ifdef ASSERT
  4112 // consistency check of split-children
  4113 void Interval::check_split_children() {
  4114   if (_split_children.length() > 0) {
  4115     assert(is_split_parent(), "only split parents can have children");
  4117     for (int i = 0; i < _split_children.length(); i++) {
  4118       Interval* i1 = _split_children.at(i);
  4120       assert(i1->split_parent() == this, "not a split child of this interval");
  4121       assert(i1->type() == type(), "must be equal for all split children");
  4122       assert(i1->canonical_spill_slot() == canonical_spill_slot(), "must be equal for all split children");
  4124       for (int j = i + 1; j < _split_children.length(); j++) {
  4125         Interval* i2 = _split_children.at(j);
  4127         assert(i1->reg_num() != i2->reg_num(), "same register number");
  4129         if (i1->from() < i2->from()) {
  4130           assert(i1->to() <= i2->from() && i1->to() < i2->to(), "intervals overlapping");
  4131         } else {
  4132           assert(i2->from() < i1->from(), "intervals start at same op_id");
  4133           assert(i2->to() <= i1->from() && i2->to() < i1->to(), "intervals overlapping");
  4139 #endif // ASSERT
  4141 Interval* Interval::register_hint(bool search_split_child) const {
  4142   if (!search_split_child) {
  4143     return _register_hint;
  4146   if (_register_hint != NULL) {
  4147     assert(_register_hint->is_split_parent(), "ony split parents are valid hint registers");
  4149     if (_register_hint->assigned_reg() >= 0 && _register_hint->assigned_reg() < LinearScan::nof_regs) {
  4150       return _register_hint;
  4152     } else if (_register_hint->_split_children.length() > 0) {
  4153       // search the first split child that has a register assigned
  4154       int len = _register_hint->_split_children.length();
  4155       for (int i = 0; i < len; i++) {
  4156         Interval* cur = _register_hint->_split_children.at(i);
  4158         if (cur->assigned_reg() >= 0 && cur->assigned_reg() < LinearScan::nof_regs) {
  4159           return cur;
  4165   // no hint interval found that has a register assigned
  4166   return NULL;
  4170 Interval* Interval::split_child_at_op_id(int op_id, LIR_OpVisitState::OprMode mode) {
  4171   assert(is_split_parent(), "can only be called for split parents");
  4172   assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
  4174   Interval* result;
  4175   if (_split_children.length() == 0) {
  4176     result = this;
  4177   } else {
  4178     result = NULL;
  4179     int len = _split_children.length();
  4181     // in outputMode, the end of the interval (op_id == cur->to()) is not valid
  4182     int to_offset = (mode == LIR_OpVisitState::outputMode ? 0 : 1);
  4184     int i;
  4185     for (i = 0; i < len; i++) {
  4186       Interval* cur = _split_children.at(i);
  4187       if (cur->from() <= op_id && op_id < cur->to() + to_offset) {
  4188         if (i > 0) {
  4189           // exchange current split child to start of list (faster access for next call)
  4190           _split_children.at_put(i, _split_children.at(0));
  4191           _split_children.at_put(0, cur);
  4194         // interval found
  4195         result = cur;
  4196         break;
  4200 #ifdef ASSERT
  4201     for (i = 0; i < len; i++) {
  4202       Interval* tmp = _split_children.at(i);
  4203       if (tmp != result && tmp->from() <= op_id && op_id < tmp->to() + to_offset) {
  4204         tty->print_cr("two valid result intervals found for op_id %d: %d and %d", op_id, result->reg_num(), tmp->reg_num());
  4205         result->print();
  4206         tmp->print();
  4207         assert(false, "two valid result intervals found");
  4210 #endif
  4213   assert(result != NULL, "no matching interval found");
  4214   assert(result->covers(op_id, mode), "op_id not covered by interval");
  4216   return result;
  4220 // returns the last split child that ends before the given op_id
  4221 Interval* Interval::split_child_before_op_id(int op_id) {
  4222   assert(op_id >= 0, "invalid op_id");
  4224   Interval* parent = split_parent();
  4225   Interval* result = NULL;
  4227   int len = parent->_split_children.length();
  4228   assert(len > 0, "no split children available");
  4230   for (int i = len - 1; i >= 0; i--) {
  4231     Interval* cur = parent->_split_children.at(i);
  4232     if (cur->to() <= op_id && (result == NULL || result->to() < cur->to())) {
  4233       result = cur;
  4237   assert(result != NULL, "no split child found");
  4238   return result;
  4242 // checks if op_id is covered by any split child
  4243 bool Interval::split_child_covers(int op_id, LIR_OpVisitState::OprMode mode) {
  4244   assert(is_split_parent(), "can only be called for split parents");
  4245   assert(op_id >= 0, "invalid op_id (method can not be called for spill moves)");
  4247   if (_split_children.length() == 0) {
  4248     // simple case if interval was not split
  4249     return covers(op_id, mode);
  4251   } else {
  4252     // extended case: check all split children
  4253     int len = _split_children.length();
  4254     for (int i = 0; i < len; i++) {
  4255       Interval* cur = _split_children.at(i);
  4256       if (cur->covers(op_id, mode)) {
  4257         return true;
  4260     return false;
  4265 // Note: use positions are sorted descending -> first use has highest index
  4266 int Interval::first_usage(IntervalUseKind min_use_kind) const {
  4267   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4269   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4270     if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
  4271       return _use_pos_and_kinds.at(i);
  4274   return max_jint;
  4277 int Interval::next_usage(IntervalUseKind min_use_kind, int from) const {
  4278   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4280   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4281     if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) >= min_use_kind) {
  4282       return _use_pos_and_kinds.at(i);
  4285   return max_jint;
  4288 int Interval::next_usage_exact(IntervalUseKind exact_use_kind, int from) const {
  4289   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4291   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4292     if (_use_pos_and_kinds.at(i) >= from && _use_pos_and_kinds.at(i + 1) == exact_use_kind) {
  4293       return _use_pos_and_kinds.at(i);
  4296   return max_jint;
  4299 int Interval::previous_usage(IntervalUseKind min_use_kind, int from) const {
  4300   assert(LinearScan::is_virtual_interval(this), "cannot access use positions for fixed intervals");
  4302   int prev = 0;
  4303   for (int i = _use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4304     if (_use_pos_and_kinds.at(i) > from) {
  4305       return prev;
  4307     if (_use_pos_and_kinds.at(i + 1) >= min_use_kind) {
  4308       prev = _use_pos_and_kinds.at(i);
  4311   return prev;
  4314 void Interval::add_use_pos(int pos, IntervalUseKind use_kind) {
  4315   assert(covers(pos, LIR_OpVisitState::inputMode), "use position not covered by live range");
  4317   // do not add use positions for precolored intervals because
  4318   // they are never used
  4319   if (use_kind != noUse && reg_num() >= LIR_OprDesc::vreg_base) {
  4320 #ifdef ASSERT
  4321     assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
  4322     for (int i = 0; i < _use_pos_and_kinds.length(); i += 2) {
  4323       assert(pos <= _use_pos_and_kinds.at(i), "already added a use-position with lower position");
  4324       assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4325       if (i > 0) {
  4326         assert(_use_pos_and_kinds.at(i) < _use_pos_and_kinds.at(i - 2), "not sorted descending");
  4329 #endif
  4331     // Note: add_use is called in descending order, so list gets sorted
  4332     //       automatically by just appending new use positions
  4333     int len = _use_pos_and_kinds.length();
  4334     if (len == 0 || _use_pos_and_kinds.at(len - 2) > pos) {
  4335       _use_pos_and_kinds.append(pos);
  4336       _use_pos_and_kinds.append(use_kind);
  4337     } else if (_use_pos_and_kinds.at(len - 1) < use_kind) {
  4338       assert(_use_pos_and_kinds.at(len - 2) == pos, "list not sorted correctly");
  4339       _use_pos_and_kinds.at_put(len - 1, use_kind);
  4344 void Interval::add_range(int from, int to) {
  4345   assert(from < to, "invalid range");
  4346   assert(first() == Range::end() || to < first()->next()->from(), "not inserting at begin of interval");
  4347   assert(from <= first()->to(), "not inserting at begin of interval");
  4349   if (first()->from() <= to) {
  4350     // join intersecting ranges
  4351     first()->set_from(MIN2(from, first()->from()));
  4352     first()->set_to  (MAX2(to,   first()->to()));
  4353   } else {
  4354     // insert new range
  4355     _first = new Range(from, to, first());
  4359 Interval* Interval::new_split_child() {
  4360   // allocate new interval
  4361   Interval* result = new Interval(-1);
  4362   result->set_type(type());
  4364   Interval* parent = split_parent();
  4365   result->_split_parent = parent;
  4366   result->set_register_hint(parent);
  4368   // insert new interval in children-list of parent
  4369   if (parent->_split_children.length() == 0) {
  4370     assert(is_split_parent(), "list must be initialized at first split");
  4372     parent->_split_children = IntervalList(4);
  4373     parent->_split_children.append(this);
  4375   parent->_split_children.append(result);
  4377   return result;
  4380 // split this interval at the specified position and return
  4381 // the remainder as a new interval.
  4382 //
  4383 // when an interval is split, a bi-directional link is established between the original interval
  4384 // (the split parent) and the intervals that are split off this interval (the split children)
  4385 // When a split child is split again, the new created interval is also a direct child
  4386 // of the original parent (there is no tree of split children stored, but a flat list)
  4387 // All split children are spilled to the same stack slot (stored in _canonical_spill_slot)
  4388 //
  4389 // Note: The new interval has no valid reg_num
  4390 Interval* Interval::split(int split_pos) {
  4391   assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
  4393   // allocate new interval
  4394   Interval* result = new_split_child();
  4396   // split the ranges
  4397   Range* prev = NULL;
  4398   Range* cur = _first;
  4399   while (cur != Range::end() && cur->to() <= split_pos) {
  4400     prev = cur;
  4401     cur = cur->next();
  4403   assert(cur != Range::end(), "split interval after end of last range");
  4405   if (cur->from() < split_pos) {
  4406     result->_first = new Range(split_pos, cur->to(), cur->next());
  4407     cur->set_to(split_pos);
  4408     cur->set_next(Range::end());
  4410   } else {
  4411     assert(prev != NULL, "split before start of first range");
  4412     result->_first = cur;
  4413     prev->set_next(Range::end());
  4415   result->_current = result->_first;
  4416   _cached_to = -1; // clear cached value
  4418   // split list of use positions
  4419   int total_len = _use_pos_and_kinds.length();
  4420   int start_idx = total_len - 2;
  4421   while (start_idx >= 0 && _use_pos_and_kinds.at(start_idx) < split_pos) {
  4422     start_idx -= 2;
  4425   intStack new_use_pos_and_kinds(total_len - start_idx);
  4426   int i;
  4427   for (i = start_idx + 2; i < total_len; i++) {
  4428     new_use_pos_and_kinds.append(_use_pos_and_kinds.at(i));
  4431   _use_pos_and_kinds.truncate(start_idx + 2);
  4432   result->_use_pos_and_kinds = _use_pos_and_kinds;
  4433   _use_pos_and_kinds = new_use_pos_and_kinds;
  4435 #ifdef ASSERT
  4436   assert(_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
  4437   assert(result->_use_pos_and_kinds.length() % 2 == 0, "must have use kind for each use pos");
  4438   assert(_use_pos_and_kinds.length() + result->_use_pos_and_kinds.length() == total_len, "missed some entries");
  4440   for (i = 0; i < _use_pos_and_kinds.length(); i += 2) {
  4441     assert(_use_pos_and_kinds.at(i) < split_pos, "must be");
  4442     assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4444   for (i = 0; i < result->_use_pos_and_kinds.length(); i += 2) {
  4445     assert(result->_use_pos_and_kinds.at(i) >= split_pos, "must be");
  4446     assert(result->_use_pos_and_kinds.at(i + 1) >= firstValidKind && result->_use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4448 #endif
  4450   return result;
  4453 // split this interval at the specified position and return
  4454 // the head as a new interval (the original interval is the tail)
  4455 //
  4456 // Currently, only the first range can be split, and the new interval
  4457 // must not have split positions
  4458 Interval* Interval::split_from_start(int split_pos) {
  4459   assert(LinearScan::is_virtual_interval(this), "cannot split fixed intervals");
  4460   assert(split_pos > from() && split_pos < to(), "can only split inside interval");
  4461   assert(split_pos > _first->from() && split_pos <= _first->to(), "can only split inside first range");
  4462   assert(first_usage(noUse) > split_pos, "can not split when use positions are present");
  4464   // allocate new interval
  4465   Interval* result = new_split_child();
  4467   // the new created interval has only one range (checked by assertion above),
  4468   // so the splitting of the ranges is very simple
  4469   result->add_range(_first->from(), split_pos);
  4471   if (split_pos == _first->to()) {
  4472     assert(_first->next() != Range::end(), "must not be at end");
  4473     _first = _first->next();
  4474   } else {
  4475     _first->set_from(split_pos);
  4478   return result;
  4482 // returns true if the op_id is inside the interval
  4483 bool Interval::covers(int op_id, LIR_OpVisitState::OprMode mode) const {
  4484   Range* cur  = _first;
  4486   while (cur != Range::end() && cur->to() < op_id) {
  4487     cur = cur->next();
  4489   if (cur != Range::end()) {
  4490     assert(cur->to() != cur->next()->from(), "ranges not separated");
  4492     if (mode == LIR_OpVisitState::outputMode) {
  4493       return cur->from() <= op_id && op_id < cur->to();
  4494     } else {
  4495       return cur->from() <= op_id && op_id <= cur->to();
  4498   return false;
  4501 // returns true if the interval has any hole between hole_from and hole_to
  4502 // (even if the hole has only the length 1)
  4503 bool Interval::has_hole_between(int hole_from, int hole_to) {
  4504   assert(hole_from < hole_to, "check");
  4505   assert(from() <= hole_from && hole_to <= to(), "index out of interval");
  4507   Range* cur  = _first;
  4508   while (cur != Range::end()) {
  4509     assert(cur->to() < cur->next()->from(), "no space between ranges");
  4511     // hole-range starts before this range -> hole
  4512     if (hole_from < cur->from()) {
  4513       return true;
  4515     // hole-range completely inside this range -> no hole
  4516     } else if (hole_to <= cur->to()) {
  4517       return false;
  4519     // overlapping of hole-range with this range -> hole
  4520     } else if (hole_from <= cur->to()) {
  4521       return true;
  4524     cur = cur->next();
  4527   return false;
  4531 #ifndef PRODUCT
  4532 void Interval::print(outputStream* out) const {
  4533   const char* SpillState2Name[] = { "no definition", "no spill store", "one spill store", "store at definition", "start in memory", "no optimization" };
  4534   const char* UseKind2Name[] = { "N", "L", "S", "M" };
  4536   const char* type_name;
  4537   LIR_Opr opr = LIR_OprFact::illegal();
  4538   if (reg_num() < LIR_OprDesc::vreg_base) {
  4539     type_name = "fixed";
  4540     // need a temporary operand for fixed intervals because type() cannot be called
  4541     if (assigned_reg() >= pd_first_cpu_reg && assigned_reg() <= pd_last_cpu_reg) {
  4542       opr = LIR_OprFact::single_cpu(assigned_reg());
  4543     } else if (assigned_reg() >= pd_first_fpu_reg && assigned_reg() <= pd_last_fpu_reg) {
  4544       opr = LIR_OprFact::single_fpu(assigned_reg() - pd_first_fpu_reg);
  4545 #ifdef X86
  4546     } else if (assigned_reg() >= pd_first_xmm_reg && assigned_reg() <= pd_last_xmm_reg) {
  4547       opr = LIR_OprFact::single_xmm(assigned_reg() - pd_first_xmm_reg);
  4548 #endif
  4549     } else {
  4550       ShouldNotReachHere();
  4552   } else {
  4553     type_name = type2name(type());
  4554     if (assigned_reg() != -1 &&
  4555         (LinearScan::num_physical_regs(type()) == 1 || assigned_regHi() != -1)) {
  4556       opr = LinearScan::calc_operand_for_interval(this);
  4560   out->print("%d %s ", reg_num(), type_name);
  4561   if (opr->is_valid()) {
  4562     out->print("\"");
  4563     opr->print(out);
  4564     out->print("\" ");
  4566   out->print("%d %d ", split_parent()->reg_num(), (register_hint(false) != NULL ? register_hint(false)->reg_num() : -1));
  4568   // print ranges
  4569   Range* cur = _first;
  4570   while (cur != Range::end()) {
  4571     cur->print(out);
  4572     cur = cur->next();
  4573     assert(cur != NULL, "range list not closed with range sentinel");
  4576   // print use positions
  4577   int prev = 0;
  4578   assert(_use_pos_and_kinds.length() % 2 == 0, "must be");
  4579   for (int i =_use_pos_and_kinds.length() - 2; i >= 0; i -= 2) {
  4580     assert(_use_pos_and_kinds.at(i + 1) >= firstValidKind && _use_pos_and_kinds.at(i + 1) <= lastValidKind, "invalid use kind");
  4581     assert(prev < _use_pos_and_kinds.at(i), "use positions not sorted");
  4583     out->print("%d %s ", _use_pos_and_kinds.at(i), UseKind2Name[_use_pos_and_kinds.at(i + 1)]);
  4584     prev = _use_pos_and_kinds.at(i);
  4587   out->print(" \"%s\"", SpillState2Name[spill_state()]);
  4588   out->cr();
  4590 #endif
  4594 // **** Implementation of IntervalWalker ****************************
  4596 IntervalWalker::IntervalWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
  4597  : _compilation(allocator->compilation())
  4598  , _allocator(allocator)
  4600   _unhandled_first[fixedKind] = unhandled_fixed_first;
  4601   _unhandled_first[anyKind]   = unhandled_any_first;
  4602   _active_first[fixedKind]    = Interval::end();
  4603   _inactive_first[fixedKind]  = Interval::end();
  4604   _active_first[anyKind]      = Interval::end();
  4605   _inactive_first[anyKind]    = Interval::end();
  4606   _current_position = -1;
  4607   _current = NULL;
  4608   next_interval();
  4612 // append interval at top of list
  4613 void IntervalWalker::append_unsorted(Interval** list, Interval* interval) {
  4614   interval->set_next(*list); *list = interval;
  4618 // append interval in order of current range from()
  4619 void IntervalWalker::append_sorted(Interval** list, Interval* interval) {
  4620   Interval* prev = NULL;
  4621   Interval* cur  = *list;
  4622   while (cur->current_from() < interval->current_from()) {
  4623     prev = cur; cur = cur->next();
  4625   if (prev == NULL) {
  4626     *list = interval;
  4627   } else {
  4628     prev->set_next(interval);
  4630   interval->set_next(cur);
  4633 void IntervalWalker::append_to_unhandled(Interval** list, Interval* interval) {
  4634   assert(interval->from() >= current()->current_from(), "cannot append new interval before current walk position");
  4636   Interval* prev = NULL;
  4637   Interval* cur  = *list;
  4638   while (cur->from() < interval->from() || (cur->from() == interval->from() && cur->first_usage(noUse) < interval->first_usage(noUse))) {
  4639     prev = cur; cur = cur->next();
  4641   if (prev == NULL) {
  4642     *list = interval;
  4643   } else {
  4644     prev->set_next(interval);
  4646   interval->set_next(cur);
  4650 inline bool IntervalWalker::remove_from_list(Interval** list, Interval* i) {
  4651   while (*list != Interval::end() && *list != i) {
  4652     list = (*list)->next_addr();
  4654   if (*list != Interval::end()) {
  4655     assert(*list == i, "check");
  4656     *list = (*list)->next();
  4657     return true;
  4658   } else {
  4659     return false;
  4663 void IntervalWalker::remove_from_list(Interval* i) {
  4664   bool deleted;
  4666   if (i->state() == activeState) {
  4667     deleted = remove_from_list(active_first_addr(anyKind), i);
  4668   } else {
  4669     assert(i->state() == inactiveState, "invalid state");
  4670     deleted = remove_from_list(inactive_first_addr(anyKind), i);
  4673   assert(deleted, "interval has not been found in list");
  4677 void IntervalWalker::walk_to(IntervalState state, int from) {
  4678   assert (state == activeState || state == inactiveState, "wrong state");
  4679   for_each_interval_kind(kind) {
  4680     Interval** prev = state == activeState ? active_first_addr(kind) : inactive_first_addr(kind);
  4681     Interval* next   = *prev;
  4682     while (next->current_from() <= from) {
  4683       Interval* cur = next;
  4684       next = cur->next();
  4686       bool range_has_changed = false;
  4687       while (cur->current_to() <= from) {
  4688         cur->next_range();
  4689         range_has_changed = true;
  4692       // also handle move from inactive list to active list
  4693       range_has_changed = range_has_changed || (state == inactiveState && cur->current_from() <= from);
  4695       if (range_has_changed) {
  4696         // remove cur from list
  4697         *prev = next;
  4698         if (cur->current_at_end()) {
  4699           // move to handled state (not maintained as a list)
  4700           cur->set_state(handledState);
  4701           interval_moved(cur, kind, state, handledState);
  4702         } else if (cur->current_from() <= from){
  4703           // sort into active list
  4704           append_sorted(active_first_addr(kind), cur);
  4705           cur->set_state(activeState);
  4706           if (*prev == cur) {
  4707             assert(state == activeState, "check");
  4708             prev = cur->next_addr();
  4710           interval_moved(cur, kind, state, activeState);
  4711         } else {
  4712           // sort into inactive list
  4713           append_sorted(inactive_first_addr(kind), cur);
  4714           cur->set_state(inactiveState);
  4715           if (*prev == cur) {
  4716             assert(state == inactiveState, "check");
  4717             prev = cur->next_addr();
  4719           interval_moved(cur, kind, state, inactiveState);
  4721       } else {
  4722         prev = cur->next_addr();
  4723         continue;
  4730 void IntervalWalker::next_interval() {
  4731   IntervalKind kind;
  4732   Interval* any   = _unhandled_first[anyKind];
  4733   Interval* fixed = _unhandled_first[fixedKind];
  4735   if (any != Interval::end()) {
  4736     // intervals may start at same position -> prefer fixed interval
  4737     kind = fixed != Interval::end() && fixed->from() <= any->from() ? fixedKind : anyKind;
  4739     assert (kind == fixedKind && fixed->from() <= any->from() ||
  4740             kind == anyKind   && any->from() <= fixed->from(), "wrong interval!!!");
  4741     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");
  4743   } else if (fixed != Interval::end()) {
  4744     kind = fixedKind;
  4745   } else {
  4746     _current = NULL; return;
  4748   _current_kind = kind;
  4749   _current = _unhandled_first[kind];
  4750   _unhandled_first[kind] = _current->next();
  4751   _current->set_next(Interval::end());
  4752   _current->rewind_range();
  4756 void IntervalWalker::walk_to(int lir_op_id) {
  4757   assert(_current_position <= lir_op_id, "can not walk backwards");
  4758   while (current() != NULL) {
  4759     bool is_active = current()->from() <= lir_op_id;
  4760     int id = is_active ? current()->from() : lir_op_id;
  4762     TRACE_LINEAR_SCAN(2, if (_current_position < id) { tty->cr(); tty->print_cr("walk_to(%d) **************************************************************", id); })
  4764     // set _current_position prior to call of walk_to
  4765     _current_position = id;
  4767     // call walk_to even if _current_position == id
  4768     walk_to(activeState, id);
  4769     walk_to(inactiveState, id);
  4771     if (is_active) {
  4772       current()->set_state(activeState);
  4773       if (activate_current()) {
  4774         append_sorted(active_first_addr(current_kind()), current());
  4775         interval_moved(current(), current_kind(), unhandledState, activeState);
  4778       next_interval();
  4779     } else {
  4780       return;
  4785 void IntervalWalker::interval_moved(Interval* interval, IntervalKind kind, IntervalState from, IntervalState to) {
  4786 #ifndef PRODUCT
  4787   if (TraceLinearScanLevel >= 4) {
  4788     #define print_state(state) \
  4789     switch(state) {\
  4790       case unhandledState: tty->print("unhandled"); break;\
  4791       case activeState: tty->print("active"); break;\
  4792       case inactiveState: tty->print("inactive"); break;\
  4793       case handledState: tty->print("handled"); break;\
  4794       default: ShouldNotReachHere(); \
  4797     print_state(from); tty->print(" to "); print_state(to);
  4798     tty->fill_to(23);
  4799     interval->print();
  4801     #undef print_state
  4803 #endif
  4808 // **** Implementation of LinearScanWalker **************************
  4810 LinearScanWalker::LinearScanWalker(LinearScan* allocator, Interval* unhandled_fixed_first, Interval* unhandled_any_first)
  4811   : IntervalWalker(allocator, unhandled_fixed_first, unhandled_any_first)
  4812   , _move_resolver(allocator)
  4814   for (int i = 0; i < LinearScan::nof_regs; i++) {
  4815     _spill_intervals[i] = new IntervalList(2);
  4820 inline void LinearScanWalker::init_use_lists(bool only_process_use_pos) {
  4821   for (int i = _first_reg; i <= _last_reg; i++) {
  4822     _use_pos[i] = max_jint;
  4824     if (!only_process_use_pos) {
  4825       _block_pos[i] = max_jint;
  4826       _spill_intervals[i]->clear();
  4831 inline void LinearScanWalker::exclude_from_use(int reg) {
  4832   assert(reg < LinearScan::nof_regs, "interval must have a register assigned (stack slots not allowed)");
  4833   if (reg >= _first_reg && reg <= _last_reg) {
  4834     _use_pos[reg] = 0;
  4837 inline void LinearScanWalker::exclude_from_use(Interval* i) {
  4838   assert(i->assigned_reg() != any_reg, "interval has no register assigned");
  4840   exclude_from_use(i->assigned_reg());
  4841   exclude_from_use(i->assigned_regHi());
  4844 inline void LinearScanWalker::set_use_pos(int reg, Interval* i, int use_pos, bool only_process_use_pos) {
  4845   assert(use_pos != 0, "must use exclude_from_use to set use_pos to 0");
  4847   if (reg >= _first_reg && reg <= _last_reg) {
  4848     if (_use_pos[reg] > use_pos) {
  4849       _use_pos[reg] = use_pos;
  4851     if (!only_process_use_pos) {
  4852       _spill_intervals[reg]->append(i);
  4856 inline void LinearScanWalker::set_use_pos(Interval* i, int use_pos, bool only_process_use_pos) {
  4857   assert(i->assigned_reg() != any_reg, "interval has no register assigned");
  4858   if (use_pos != -1) {
  4859     set_use_pos(i->assigned_reg(), i, use_pos, only_process_use_pos);
  4860     set_use_pos(i->assigned_regHi(), i, use_pos, only_process_use_pos);
  4864 inline void LinearScanWalker::set_block_pos(int reg, Interval* i, int block_pos) {
  4865   if (reg >= _first_reg && reg <= _last_reg) {
  4866     if (_block_pos[reg] > block_pos) {
  4867       _block_pos[reg] = block_pos;
  4869     if (_use_pos[reg] > block_pos) {
  4870       _use_pos[reg] = block_pos;
  4874 inline void LinearScanWalker::set_block_pos(Interval* i, int block_pos) {
  4875   assert(i->assigned_reg() != any_reg, "interval has no register assigned");
  4876   if (block_pos != -1) {
  4877     set_block_pos(i->assigned_reg(), i, block_pos);
  4878     set_block_pos(i->assigned_regHi(), i, block_pos);
  4883 void LinearScanWalker::free_exclude_active_fixed() {
  4884   Interval* list = active_first(fixedKind);
  4885   while (list != Interval::end()) {
  4886     assert(list->assigned_reg() < LinearScan::nof_regs, "active interval must have a register assigned");
  4887     exclude_from_use(list);
  4888     list = list->next();
  4892 void LinearScanWalker::free_exclude_active_any() {
  4893   Interval* list = active_first(anyKind);
  4894   while (list != Interval::end()) {
  4895     exclude_from_use(list);
  4896     list = list->next();
  4900 void LinearScanWalker::free_collect_inactive_fixed(Interval* cur) {
  4901   Interval* list = inactive_first(fixedKind);
  4902   while (list != Interval::end()) {
  4903     if (cur->to() <= list->current_from()) {
  4904       assert(list->current_intersects_at(cur) == -1, "must not intersect");
  4905       set_use_pos(list, list->current_from(), true);
  4906     } else {
  4907       set_use_pos(list, list->current_intersects_at(cur), true);
  4909     list = list->next();
  4913 void LinearScanWalker::free_collect_inactive_any(Interval* cur) {
  4914   Interval* list = inactive_first(anyKind);
  4915   while (list != Interval::end()) {
  4916     set_use_pos(list, list->current_intersects_at(cur), true);
  4917     list = list->next();
  4921 void LinearScanWalker::free_collect_unhandled(IntervalKind kind, Interval* cur) {
  4922   Interval* list = unhandled_first(kind);
  4923   while (list != Interval::end()) {
  4924     set_use_pos(list, list->intersects_at(cur), true);
  4925     if (kind == fixedKind && cur->to() <= list->from()) {
  4926       set_use_pos(list, list->from(), true);
  4928     list = list->next();
  4932 void LinearScanWalker::spill_exclude_active_fixed() {
  4933   Interval* list = active_first(fixedKind);
  4934   while (list != Interval::end()) {
  4935     exclude_from_use(list);
  4936     list = list->next();
  4940 void LinearScanWalker::spill_block_unhandled_fixed(Interval* cur) {
  4941   Interval* list = unhandled_first(fixedKind);
  4942   while (list != Interval::end()) {
  4943     set_block_pos(list, list->intersects_at(cur));
  4944     list = list->next();
  4948 void LinearScanWalker::spill_block_inactive_fixed(Interval* cur) {
  4949   Interval* list = inactive_first(fixedKind);
  4950   while (list != Interval::end()) {
  4951     if (cur->to() > list->current_from()) {
  4952       set_block_pos(list, list->current_intersects_at(cur));
  4953     } else {
  4954       assert(list->current_intersects_at(cur) == -1, "invalid optimization: intervals intersect");
  4957     list = list->next();
  4961 void LinearScanWalker::spill_collect_active_any() {
  4962   Interval* list = active_first(anyKind);
  4963   while (list != Interval::end()) {
  4964     set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
  4965     list = list->next();
  4969 void LinearScanWalker::spill_collect_inactive_any(Interval* cur) {
  4970   Interval* list = inactive_first(anyKind);
  4971   while (list != Interval::end()) {
  4972     if (list->current_intersects(cur)) {
  4973       set_use_pos(list, MIN2(list->next_usage(loopEndMarker, _current_position), list->to()), false);
  4975     list = list->next();
  4980 void LinearScanWalker::insert_move(int op_id, Interval* src_it, Interval* dst_it) {
  4981   // output all moves here. When source and target are equal, the move is
  4982   // optimized away later in assign_reg_nums
  4984   op_id = (op_id + 1) & ~1;
  4985   BlockBegin* op_block = allocator()->block_of_op_with_id(op_id);
  4986   assert(op_id > 0 && allocator()->block_of_op_with_id(op_id - 2) == op_block, "cannot insert move at block boundary");
  4988   // calculate index of instruction inside instruction list of current block
  4989   // the minimal index (for a block with no spill moves) can be calculated because the
  4990   // numbering of instructions is known.
  4991   // When the block already contains spill moves, the index must be increased until the
  4992   // correct index is reached.
  4993   LIR_OpList* list = op_block->lir()->instructions_list();
  4994   int index = (op_id - list->at(0)->id()) / 2;
  4995   assert(list->at(index)->id() <= op_id, "error in calculation");
  4997   while (list->at(index)->id() != op_id) {
  4998     index++;
  4999     assert(0 <= index && index < list->length(), "index out of bounds");
  5001   assert(1 <= index && index < list->length(), "index out of bounds");
  5002   assert(list->at(index)->id() == op_id, "error in calculation");
  5004   // insert new instruction before instruction at position index
  5005   _move_resolver.move_insert_position(op_block->lir(), index - 1);
  5006   _move_resolver.add_mapping(src_it, dst_it);
  5010 int LinearScanWalker::find_optimal_split_pos(BlockBegin* min_block, BlockBegin* max_block, int max_split_pos) {
  5011   int from_block_nr = min_block->linear_scan_number();
  5012   int to_block_nr = max_block->linear_scan_number();
  5014   assert(0 <= from_block_nr && from_block_nr < block_count(), "out of range");
  5015   assert(0 <= to_block_nr && to_block_nr < block_count(), "out of range");
  5016   assert(from_block_nr < to_block_nr, "must cross block boundary");
  5018   // Try to split at end of max_block. If this would be after
  5019   // max_split_pos, then use the begin of max_block
  5020   int optimal_split_pos = max_block->last_lir_instruction_id() + 2;
  5021   if (optimal_split_pos > max_split_pos) {
  5022     optimal_split_pos = max_block->first_lir_instruction_id();
  5025   int min_loop_depth = max_block->loop_depth();
  5026   for (int i = to_block_nr - 1; i >= from_block_nr; i--) {
  5027     BlockBegin* cur = block_at(i);
  5029     if (cur->loop_depth() < min_loop_depth) {
  5030       // block with lower loop-depth found -> split at the end of this block
  5031       min_loop_depth = cur->loop_depth();
  5032       optimal_split_pos = cur->last_lir_instruction_id() + 2;
  5035   assert(optimal_split_pos > allocator()->max_lir_op_id() || allocator()->is_block_begin(optimal_split_pos), "algorithm must move split pos to block boundary");
  5037   return optimal_split_pos;
  5041 int LinearScanWalker::find_optimal_split_pos(Interval* it, int min_split_pos, int max_split_pos, bool do_loop_optimization) {
  5042   int optimal_split_pos = -1;
  5043   if (min_split_pos == max_split_pos) {
  5044     // trivial case, no optimization of split position possible
  5045     TRACE_LINEAR_SCAN(4, tty->print_cr("      min-pos and max-pos are equal, no optimization possible"));
  5046     optimal_split_pos = min_split_pos;
  5048   } else {
  5049     assert(min_split_pos < max_split_pos, "must be true then");
  5050     assert(min_split_pos > 0, "cannot access min_split_pos - 1 otherwise");
  5052     // reason for using min_split_pos - 1: when the minimal split pos is exactly at the
  5053     // beginning of a block, then min_split_pos is also a possible split position.
  5054     // Use the block before as min_block, because then min_block->last_lir_instruction_id() + 2 == min_split_pos
  5055     BlockBegin* min_block = allocator()->block_of_op_with_id(min_split_pos - 1);
  5057     // reason for using max_split_pos - 1: otherwise there would be an assertion failure
  5058     // when an interval ends at the end of the last block of the method
  5059     // (in this case, max_split_pos == allocator()->max_lir_op_id() + 2, and there is no
  5060     // block at this op_id)
  5061     BlockBegin* max_block = allocator()->block_of_op_with_id(max_split_pos - 1);
  5063     assert(min_block->linear_scan_number() <= max_block->linear_scan_number(), "invalid order");
  5064     if (min_block == max_block) {
  5065       // split position cannot be moved to block boundary, so split as late as possible
  5066       TRACE_LINEAR_SCAN(4, tty->print_cr("      cannot move split pos to block boundary because min_pos and max_pos are in same block"));
  5067       optimal_split_pos = max_split_pos;
  5069     } else if (it->has_hole_between(max_split_pos - 1, max_split_pos) && !allocator()->is_block_begin(max_split_pos)) {
  5070       // Do not move split position if the interval has a hole before max_split_pos.
  5071       // Intervals resulting from Phi-Functions have more than one definition (marked
  5072       // as mustHaveRegister) with a hole before each definition. When the register is needed
  5073       // for the second definition, an earlier reloading is unnecessary.
  5074       TRACE_LINEAR_SCAN(4, tty->print_cr("      interval has hole just before max_split_pos, so splitting at max_split_pos"));
  5075       optimal_split_pos = max_split_pos;
  5077     } else {
  5078       // seach optimal block boundary between min_split_pos and max_split_pos
  5079       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()));
  5081       if (do_loop_optimization) {
  5082         // Loop optimization: if a loop-end marker is found between min- and max-position,
  5083         // then split before this loop
  5084         int loop_end_pos = it->next_usage_exact(loopEndMarker, min_block->last_lir_instruction_id() + 2);
  5085         TRACE_LINEAR_SCAN(4, tty->print_cr("      loop optimization: loop end found at pos %d", loop_end_pos));
  5087         assert(loop_end_pos > min_split_pos, "invalid order");
  5088         if (loop_end_pos < max_split_pos) {
  5089           // loop-end marker found between min- and max-position
  5090           // if it is not the end marker for the same loop as the min-position, then move
  5091           // the max-position to this loop block.
  5092           // Desired result: uses tagged as shouldHaveRegister inside a loop cause a reloading
  5093           // of the interval (normally, only mustHaveRegister causes a reloading)
  5094           BlockBegin* loop_block = allocator()->block_of_op_with_id(loop_end_pos);
  5096           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()));
  5097           assert(loop_block != min_block, "loop_block and min_block must be different because block boundary is needed between");
  5099           optimal_split_pos = find_optimal_split_pos(min_block, loop_block, loop_block->last_lir_instruction_id() + 2);
  5100           if (optimal_split_pos == loop_block->last_lir_instruction_id() + 2) {
  5101             optimal_split_pos = -1;
  5102             TRACE_LINEAR_SCAN(4, tty->print_cr("      loop optimization not necessary"));
  5103           } else {
  5104             TRACE_LINEAR_SCAN(4, tty->print_cr("      loop optimization successful"));
  5109       if (optimal_split_pos == -1) {
  5110         // not calculated by loop optimization
  5111         optimal_split_pos = find_optimal_split_pos(min_block, max_block, max_split_pos);
  5115   TRACE_LINEAR_SCAN(4, tty->print_cr("      optimal split position: %d", optimal_split_pos));
  5117   return optimal_split_pos;
  5121 /*
  5122   split an interval at the optimal position between min_split_pos and
  5123   max_split_pos in two parts:
  5124   1) the left part has already a location assigned
  5125   2) the right part is sorted into to the unhandled-list
  5126 */
  5127 void LinearScanWalker::split_before_usage(Interval* it, int min_split_pos, int max_split_pos) {
  5128   TRACE_LINEAR_SCAN(2, tty->print   ("----- splitting interval: "); it->print());
  5129   TRACE_LINEAR_SCAN(2, tty->print_cr("      between %d and %d", min_split_pos, max_split_pos));
  5131   assert(it->from() < min_split_pos,         "cannot split at start of interval");
  5132   assert(current_position() < min_split_pos, "cannot split before current position");
  5133   assert(min_split_pos <= max_split_pos,     "invalid order");
  5134   assert(max_split_pos <= it->to(),          "cannot split after end of interval");
  5136   int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, true);
  5138   assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
  5139   assert(optimal_split_pos <= it->to(),  "cannot split after end of interval");
  5140   assert(optimal_split_pos > it->from(), "cannot split at start of interval");
  5142   if (optimal_split_pos == it->to() && it->next_usage(mustHaveRegister, min_split_pos) == max_jint) {
  5143     // the split position would be just before the end of the interval
  5144     // -> no split at all necessary
  5145     TRACE_LINEAR_SCAN(4, tty->print_cr("      no split necessary because optimal split position is at end of interval"));
  5146     return;
  5149   // must calculate this before the actual split is performed and before split position is moved to odd op_id
  5150   bool move_necessary = !allocator()->is_block_begin(optimal_split_pos) && !it->has_hole_between(optimal_split_pos - 1, optimal_split_pos);
  5152   if (!allocator()->is_block_begin(optimal_split_pos)) {
  5153     // move position before actual instruction (odd op_id)
  5154     optimal_split_pos = (optimal_split_pos - 1) | 1;
  5157   TRACE_LINEAR_SCAN(4, tty->print_cr("      splitting at position %d", optimal_split_pos));
  5158   assert(allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
  5159   assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
  5161   Interval* split_part = it->split(optimal_split_pos);
  5163   allocator()->append_interval(split_part);
  5164   allocator()->copy_register_flags(it, split_part);
  5165   split_part->set_insert_move_when_activated(move_necessary);
  5166   append_to_unhandled(unhandled_first_addr(anyKind), split_part);
  5168   TRACE_LINEAR_SCAN(2, tty->print_cr("      split interval in two parts (insert_move_when_activated: %d)", move_necessary));
  5169   TRACE_LINEAR_SCAN(2, tty->print   ("      "); it->print());
  5170   TRACE_LINEAR_SCAN(2, tty->print   ("      "); split_part->print());
  5173 /*
  5174   split an interval at the optimal position between min_split_pos and
  5175   max_split_pos in two parts:
  5176   1) the left part has already a location assigned
  5177   2) the right part is always on the stack and therefore ignored in further processing
  5178 */
  5179 void LinearScanWalker::split_for_spilling(Interval* it) {
  5180   // calculate allowed range of splitting position
  5181   int max_split_pos = current_position();
  5182   int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, max_split_pos) + 1, it->from());
  5184   TRACE_LINEAR_SCAN(2, tty->print   ("----- splitting and spilling interval: "); it->print());
  5185   TRACE_LINEAR_SCAN(2, tty->print_cr("      between %d and %d", min_split_pos, max_split_pos));
  5187   assert(it->state() == activeState,     "why spill interval that is not active?");
  5188   assert(it->from() <= min_split_pos,    "cannot split before start of interval");
  5189   assert(min_split_pos <= max_split_pos, "invalid order");
  5190   assert(max_split_pos < it->to(),       "cannot split at end end of interval");
  5191   assert(current_position() < it->to(),  "interval must not end before current position");
  5193   if (min_split_pos == it->from()) {
  5194     // the whole interval is never used, so spill it entirely to memory
  5195     TRACE_LINEAR_SCAN(2, tty->print_cr("      spilling entire interval because split pos is at beginning of interval"));
  5196     assert(it->first_usage(shouldHaveRegister) > current_position(), "interval must not have use position before current_position");
  5198     allocator()->assign_spill_slot(it);
  5199     allocator()->change_spill_state(it, min_split_pos);
  5201     // Also kick parent intervals out of register to memory when they have no use
  5202     // position. This avoids short interval in register surrounded by intervals in
  5203     // memory -> avoid useless moves from memory to register and back
  5204     Interval* parent = it;
  5205     while (parent != NULL && parent->is_split_child()) {
  5206       parent = parent->split_child_before_op_id(parent->from());
  5208       if (parent->assigned_reg() < LinearScan::nof_regs) {
  5209         if (parent->first_usage(shouldHaveRegister) == max_jint) {
  5210           // parent is never used, so kick it out of its assigned register
  5211           TRACE_LINEAR_SCAN(4, tty->print_cr("      kicking out interval %d out of its register because it is never used", parent->reg_num()));
  5212           allocator()->assign_spill_slot(parent);
  5213         } else {
  5214           // do not go further back because the register is actually used by the interval
  5215           parent = NULL;
  5220   } else {
  5221     // search optimal split pos, split interval and spill only the right hand part
  5222     int optimal_split_pos = find_optimal_split_pos(it, min_split_pos, max_split_pos, false);
  5224     assert(min_split_pos <= optimal_split_pos && optimal_split_pos <= max_split_pos, "out of range");
  5225     assert(optimal_split_pos < it->to(), "cannot split at end of interval");
  5226     assert(optimal_split_pos >= it->from(), "cannot split before start of interval");
  5228     if (!allocator()->is_block_begin(optimal_split_pos)) {
  5229       // move position before actual instruction (odd op_id)
  5230       optimal_split_pos = (optimal_split_pos - 1) | 1;
  5233     TRACE_LINEAR_SCAN(4, tty->print_cr("      splitting at position %d", optimal_split_pos));
  5234     assert(allocator()->is_block_begin(optimal_split_pos)  || (optimal_split_pos % 2 == 1), "split pos must be odd when not on block boundary");
  5235     assert(!allocator()->is_block_begin(optimal_split_pos) || (optimal_split_pos % 2 == 0), "split pos must be even on block boundary");
  5237     Interval* spilled_part = it->split(optimal_split_pos);
  5238     allocator()->append_interval(spilled_part);
  5239     allocator()->assign_spill_slot(spilled_part);
  5240     allocator()->change_spill_state(spilled_part, optimal_split_pos);
  5242     if (!allocator()->is_block_begin(optimal_split_pos)) {
  5243       TRACE_LINEAR_SCAN(4, tty->print_cr("      inserting move from interval %d to %d", it->reg_num(), spilled_part->reg_num()));
  5244       insert_move(optimal_split_pos, it, spilled_part);
  5247     // the current_split_child is needed later when moves are inserted for reloading
  5248     assert(spilled_part->current_split_child() == it, "overwriting wrong current_split_child");
  5249     spilled_part->make_current_split_child();
  5251     TRACE_LINEAR_SCAN(2, tty->print_cr("      split interval in two parts"));
  5252     TRACE_LINEAR_SCAN(2, tty->print   ("      "); it->print());
  5253     TRACE_LINEAR_SCAN(2, tty->print   ("      "); spilled_part->print());
  5258 void LinearScanWalker::split_stack_interval(Interval* it) {
  5259   int min_split_pos = current_position() + 1;
  5260   int max_split_pos = MIN2(it->first_usage(shouldHaveRegister), it->to());
  5262   split_before_usage(it, min_split_pos, max_split_pos);
  5265 void LinearScanWalker::split_when_partial_register_available(Interval* it, int register_available_until) {
  5266   int min_split_pos = MAX2(it->previous_usage(shouldHaveRegister, register_available_until), it->from() + 1);
  5267   int max_split_pos = register_available_until;
  5269   split_before_usage(it, min_split_pos, max_split_pos);
  5272 void LinearScanWalker::split_and_spill_interval(Interval* it) {
  5273   assert(it->state() == activeState || it->state() == inactiveState, "other states not allowed");
  5275   int current_pos = current_position();
  5276   if (it->state() == inactiveState) {
  5277     // the interval is currently inactive, so no spill slot is needed for now.
  5278     // when the split part is activated, the interval has a new chance to get a register,
  5279     // so in the best case no stack slot is necessary
  5280     assert(it->has_hole_between(current_pos - 1, current_pos + 1), "interval can not be inactive otherwise");
  5281     split_before_usage(it, current_pos + 1, current_pos + 1);
  5283   } else {
  5284     // search the position where the interval must have a register and split
  5285     // at the optimal position before.
  5286     // The new created part is added to the unhandled list and will get a register
  5287     // when it is activated
  5288     int min_split_pos = current_pos + 1;
  5289     int max_split_pos = MIN2(it->next_usage(mustHaveRegister, min_split_pos), it->to());
  5291     split_before_usage(it, min_split_pos, max_split_pos);
  5293     assert(it->next_usage(mustHaveRegister, current_pos) == max_jint, "the remaining part is spilled to stack and therefore has no register");
  5294     split_for_spilling(it);
  5299 int LinearScanWalker::find_free_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
  5300   int min_full_reg = any_reg;
  5301   int max_partial_reg = any_reg;
  5303   for (int i = _first_reg; i <= _last_reg; i++) {
  5304     if (i == ignore_reg) {
  5305       // this register must be ignored
  5307     } else if (_use_pos[i] >= interval_to) {
  5308       // this register is free for the full interval
  5309       if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
  5310         min_full_reg = i;
  5312     } else if (_use_pos[i] > reg_needed_until) {
  5313       // this register is at least free until reg_needed_until
  5314       if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
  5315         max_partial_reg = i;
  5320   if (min_full_reg != any_reg) {
  5321     return min_full_reg;
  5322   } else if (max_partial_reg != any_reg) {
  5323     *need_split = true;
  5324     return max_partial_reg;
  5325   } else {
  5326     return any_reg;
  5330 int LinearScanWalker::find_free_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
  5331   assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
  5333   int min_full_reg = any_reg;
  5334   int max_partial_reg = any_reg;
  5336   for (int i = _first_reg; i < _last_reg; i+=2) {
  5337     if (_use_pos[i] >= interval_to && _use_pos[i + 1] >= interval_to) {
  5338       // this register is free for the full interval
  5339       if (min_full_reg == any_reg || i == hint_reg || (_use_pos[i] < _use_pos[min_full_reg] && min_full_reg != hint_reg)) {
  5340         min_full_reg = i;
  5342     } else if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
  5343       // this register is at least free until reg_needed_until
  5344       if (max_partial_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_partial_reg] && max_partial_reg != hint_reg)) {
  5345         max_partial_reg = i;
  5350   if (min_full_reg != any_reg) {
  5351     return min_full_reg;
  5352   } else if (max_partial_reg != any_reg) {
  5353     *need_split = true;
  5354     return max_partial_reg;
  5355   } else {
  5356     return any_reg;
  5361 bool LinearScanWalker::alloc_free_reg(Interval* cur) {
  5362   TRACE_LINEAR_SCAN(2, tty->print("trying to find free register for "); cur->print());
  5364   init_use_lists(true);
  5365   free_exclude_active_fixed();
  5366   free_exclude_active_any();
  5367   free_collect_inactive_fixed(cur);
  5368   free_collect_inactive_any(cur);
  5369 //  free_collect_unhandled(fixedKind, cur);
  5370   assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
  5372   // _use_pos contains the start of the next interval that has this register assigned
  5373   // (either as a fixed register or a normal allocated register in the past)
  5374   // only intervals overlapping with cur are processed, non-overlapping invervals can be ignored safely
  5375   TRACE_LINEAR_SCAN(4, tty->print_cr("      state of registers:"));
  5376   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]));
  5378   int hint_reg, hint_regHi;
  5379   Interval* register_hint = cur->register_hint();
  5380   if (register_hint != NULL) {
  5381     hint_reg = register_hint->assigned_reg();
  5382     hint_regHi = register_hint->assigned_regHi();
  5384     if (allocator()->is_precolored_cpu_interval(register_hint)) {
  5385       assert(hint_reg != any_reg && hint_regHi == any_reg, "must be for fixed intervals");
  5386       hint_regHi = hint_reg + 1;  // connect e.g. eax-edx
  5388     TRACE_LINEAR_SCAN(4, tty->print("      hint registers %d, %d from interval ", hint_reg, hint_regHi); register_hint->print());
  5390   } else {
  5391     hint_reg = any_reg;
  5392     hint_regHi = any_reg;
  5394   assert(hint_reg == any_reg || hint_reg != hint_regHi, "hint reg and regHi equal");
  5395   assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned to interval");
  5397   // the register must be free at least until this position
  5398   int reg_needed_until = cur->from() + 1;
  5399   int interval_to = cur->to();
  5401   bool need_split = false;
  5402   int split_pos = -1;
  5403   int reg = any_reg;
  5404   int regHi = any_reg;
  5406   if (_adjacent_regs) {
  5407     reg = find_free_double_reg(reg_needed_until, interval_to, hint_reg, &need_split);
  5408     regHi = reg + 1;
  5409     if (reg == any_reg) {
  5410       return false;
  5412     split_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
  5414   } else {
  5415     reg = find_free_reg(reg_needed_until, interval_to, hint_reg, any_reg, &need_split);
  5416     if (reg == any_reg) {
  5417       return false;
  5419     split_pos = _use_pos[reg];
  5421     if (_num_phys_regs == 2) {
  5422       regHi = find_free_reg(reg_needed_until, interval_to, hint_regHi, reg, &need_split);
  5424       if (_use_pos[reg] < interval_to && regHi == any_reg) {
  5425         // do not split interval if only one register can be assigned until the split pos
  5426         // (when one register is found for the whole interval, split&spill is only
  5427         // performed for the hi register)
  5428         return false;
  5430       } else if (regHi != any_reg) {
  5431         split_pos = MIN2(split_pos, _use_pos[regHi]);
  5433         // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
  5434         if (reg > regHi) {
  5435           int temp = reg;
  5436           reg = regHi;
  5437           regHi = temp;
  5443   cur->assign_reg(reg, regHi);
  5444   TRACE_LINEAR_SCAN(2, tty->print_cr("selected register %d, %d", reg, regHi));
  5446   assert(split_pos > 0, "invalid split_pos");
  5447   if (need_split) {
  5448     // register not available for full interval, so split it
  5449     split_when_partial_register_available(cur, split_pos);
  5452   // only return true if interval is completely assigned
  5453   return _num_phys_regs == 1 || regHi != any_reg;
  5457 int LinearScanWalker::find_locked_reg(int reg_needed_until, int interval_to, int hint_reg, int ignore_reg, bool* need_split) {
  5458   int max_reg = any_reg;
  5460   for (int i = _first_reg; i <= _last_reg; i++) {
  5461     if (i == ignore_reg) {
  5462       // this register must be ignored
  5464     } else if (_use_pos[i] > reg_needed_until) {
  5465       if (max_reg == any_reg || i == hint_reg || (_use_pos[i] > _use_pos[max_reg] && max_reg != hint_reg)) {
  5466         max_reg = i;
  5471   if (max_reg != any_reg && _block_pos[max_reg] <= interval_to) {
  5472     *need_split = true;
  5475   return max_reg;
  5478 int LinearScanWalker::find_locked_double_reg(int reg_needed_until, int interval_to, int hint_reg, bool* need_split) {
  5479   assert((_last_reg - _first_reg + 1) % 2 == 0, "adjust algorithm");
  5481   int max_reg = any_reg;
  5483   for (int i = _first_reg; i < _last_reg; i+=2) {
  5484     if (_use_pos[i] > reg_needed_until && _use_pos[i + 1] > reg_needed_until) {
  5485       if (max_reg == any_reg || _use_pos[i] > _use_pos[max_reg]) {
  5486         max_reg = i;
  5491   if (_block_pos[max_reg] <= interval_to || _block_pos[max_reg + 1] <= interval_to) {
  5492     *need_split = true;
  5495   return max_reg;
  5498 void LinearScanWalker::split_and_spill_intersecting_intervals(int reg, int regHi) {
  5499   assert(reg != any_reg, "no register assigned");
  5501   for (int i = 0; i < _spill_intervals[reg]->length(); i++) {
  5502     Interval* it = _spill_intervals[reg]->at(i);
  5503     remove_from_list(it);
  5504     split_and_spill_interval(it);
  5507   if (regHi != any_reg) {
  5508     IntervalList* processed = _spill_intervals[reg];
  5509     for (int i = 0; i < _spill_intervals[regHi]->length(); i++) {
  5510       Interval* it = _spill_intervals[regHi]->at(i);
  5511       if (processed->index_of(it) == -1) {
  5512         remove_from_list(it);
  5513         split_and_spill_interval(it);
  5520 // Split an Interval and spill it to memory so that cur can be placed in a register
  5521 void LinearScanWalker::alloc_locked_reg(Interval* cur) {
  5522   TRACE_LINEAR_SCAN(2, tty->print("need to split and spill to get register for "); cur->print());
  5524   // collect current usage of registers
  5525   init_use_lists(false);
  5526   spill_exclude_active_fixed();
  5527 //  spill_block_unhandled_fixed(cur);
  5528   assert(unhandled_first(fixedKind) == Interval::end(), "must not have unhandled fixed intervals because all fixed intervals have a use at position 0");
  5529   spill_block_inactive_fixed(cur);
  5530   spill_collect_active_any();
  5531   spill_collect_inactive_any(cur);
  5533 #ifndef PRODUCT
  5534   if (TraceLinearScanLevel >= 4) {
  5535     tty->print_cr("      state of registers:");
  5536     for (int i = _first_reg; i <= _last_reg; i++) {
  5537       tty->print("      reg %d: use_pos: %d, block_pos: %d, intervals: ", i, _use_pos[i], _block_pos[i]);
  5538       for (int j = 0; j < _spill_intervals[i]->length(); j++) {
  5539         tty->print("%d ", _spill_intervals[i]->at(j)->reg_num());
  5541       tty->cr();
  5544 #endif
  5546   // the register must be free at least until this position
  5547   int reg_needed_until = MIN2(cur->first_usage(mustHaveRegister), cur->from() + 1);
  5548   int interval_to = cur->to();
  5549   assert (reg_needed_until > 0 && reg_needed_until < max_jint, "interval has no use");
  5551   int split_pos = 0;
  5552   int use_pos = 0;
  5553   bool need_split = false;
  5554   int reg, regHi;
  5556   if (_adjacent_regs) {
  5557     reg = find_locked_double_reg(reg_needed_until, interval_to, any_reg, &need_split);
  5558     regHi = reg + 1;
  5560     if (reg != any_reg) {
  5561       use_pos = MIN2(_use_pos[reg], _use_pos[regHi]);
  5562       split_pos = MIN2(_block_pos[reg], _block_pos[regHi]);
  5564   } else {
  5565     reg = find_locked_reg(reg_needed_until, interval_to, any_reg, cur->assigned_reg(), &need_split);
  5566     regHi = any_reg;
  5568     if (reg != any_reg) {
  5569       use_pos = _use_pos[reg];
  5570       split_pos = _block_pos[reg];
  5572       if (_num_phys_regs == 2) {
  5573         if (cur->assigned_reg() != any_reg) {
  5574           regHi = reg;
  5575           reg = cur->assigned_reg();
  5576         } else {
  5577           regHi = find_locked_reg(reg_needed_until, interval_to, any_reg, reg, &need_split);
  5578           if (regHi != any_reg) {
  5579             use_pos = MIN2(use_pos, _use_pos[regHi]);
  5580             split_pos = MIN2(split_pos, _block_pos[regHi]);
  5584         if (regHi != any_reg && reg > regHi) {
  5585           // sort register numbers to prevent e.g. a move from eax,ebx to ebx,eax
  5586           int temp = reg;
  5587           reg = regHi;
  5588           regHi = temp;
  5594   if (reg == any_reg || (_num_phys_regs == 2 && regHi == any_reg) || use_pos <= cur->first_usage(mustHaveRegister)) {
  5595     // the first use of cur is later than the spilling position -> spill cur
  5596     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));
  5598     if (cur->first_usage(mustHaveRegister) <= cur->from() + 1) {
  5599       assert(false, "cannot spill interval that is used in first instruction (possible reason: no register found)");
  5600       // assign a reasonable register and do a bailout in product mode to avoid errors
  5601       allocator()->assign_spill_slot(cur);
  5602       BAILOUT("LinearScan: no register found");
  5605     split_and_spill_interval(cur);
  5606   } else {
  5607     TRACE_LINEAR_SCAN(4, tty->print_cr("decided to use register %d, %d", reg, regHi));
  5608     assert(reg != any_reg && (_num_phys_regs == 1 || regHi != any_reg), "no register found");
  5609     assert(split_pos > 0, "invalid split_pos");
  5610     assert(need_split == false || split_pos > cur->from(), "splitting interval at from");
  5612     cur->assign_reg(reg, regHi);
  5613     if (need_split) {
  5614       // register not available for full interval, so split it
  5615       split_when_partial_register_available(cur, split_pos);
  5618     // perform splitting and spilling for all affected intervalls
  5619     split_and_spill_intersecting_intervals(reg, regHi);
  5623 bool LinearScanWalker::no_allocation_possible(Interval* cur) {
  5624 #ifdef X86
  5625   // fast calculation of intervals that can never get a register because the
  5626   // the next instruction is a call that blocks all registers
  5627   // Note: this does not work if callee-saved registers are available (e.g. on Sparc)
  5629   // check if this interval is the result of a split operation
  5630   // (an interval got a register until this position)
  5631   int pos = cur->from();
  5632   if ((pos & 1) == 1) {
  5633     // the current instruction is a call that blocks all registers
  5634     if (pos < allocator()->max_lir_op_id() && allocator()->has_call(pos + 1)) {
  5635       TRACE_LINEAR_SCAN(4, tty->print_cr("      free register cannot be available because all registers blocked by following call"));
  5637       // safety check that there is really no register available
  5638       assert(alloc_free_reg(cur) == false, "found a register for this interval");
  5639       return true;
  5643 #endif
  5644   return false;
  5647 void LinearScanWalker::init_vars_for_alloc(Interval* cur) {
  5648   BasicType type = cur->type();
  5649   _num_phys_regs = LinearScan::num_physical_regs(type);
  5650   _adjacent_regs = LinearScan::requires_adjacent_regs(type);
  5652   if (pd_init_regs_for_alloc(cur)) {
  5653     // the appropriate register range was selected.
  5654   } else if (type == T_FLOAT || type == T_DOUBLE) {
  5655     _first_reg = pd_first_fpu_reg;
  5656     _last_reg = pd_last_fpu_reg;
  5657   } else {
  5658     _first_reg = pd_first_cpu_reg;
  5659     _last_reg = FrameMap::last_cpu_reg();
  5662   assert(0 <= _first_reg && _first_reg < LinearScan::nof_regs, "out of range");
  5663   assert(0 <= _last_reg && _last_reg < LinearScan::nof_regs, "out of range");
  5667 bool LinearScanWalker::is_move(LIR_Op* op, Interval* from, Interval* to) {
  5668   if (op->code() != lir_move) {
  5669     return false;
  5671   assert(op->as_Op1() != NULL, "move must be LIR_Op1");
  5673   LIR_Opr in = ((LIR_Op1*)op)->in_opr();
  5674   LIR_Opr res = ((LIR_Op1*)op)->result_opr();
  5675   return in->is_virtual() && res->is_virtual() && in->vreg_number() == from->reg_num() && res->vreg_number() == to->reg_num();
  5678 // optimization (especially for phi functions of nested loops):
  5679 // assign same spill slot to non-intersecting intervals
  5680 void LinearScanWalker::combine_spilled_intervals(Interval* cur) {
  5681   if (cur->is_split_child()) {
  5682     // optimization is only suitable for split parents
  5683     return;
  5686   Interval* register_hint = cur->register_hint(false);
  5687   if (register_hint == NULL) {
  5688     // cur is not the target of a move, otherwise register_hint would be set
  5689     return;
  5691   assert(register_hint->is_split_parent(), "register hint must be split parent");
  5693   if (cur->spill_state() != noOptimization || register_hint->spill_state() != noOptimization) {
  5694     // combining the stack slots for intervals where spill move optimization is applied
  5695     // is not benefitial and would cause problems
  5696     return;
  5699   int begin_pos = cur->from();
  5700   int end_pos = cur->to();
  5701   if (end_pos > allocator()->max_lir_op_id() || (begin_pos & 1) != 0 || (end_pos & 1) != 0) {
  5702     // safety check that lir_op_with_id is allowed
  5703     return;
  5706   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)) {
  5707     // cur and register_hint are not connected with two moves
  5708     return;
  5711   Interval* begin_hint = register_hint->split_child_at_op_id(begin_pos, LIR_OpVisitState::inputMode);
  5712   Interval* end_hint = register_hint->split_child_at_op_id(end_pos, LIR_OpVisitState::outputMode);
  5713   if (begin_hint == end_hint || begin_hint->to() != begin_pos || end_hint->from() != end_pos) {
  5714     // register_hint must be split, otherwise the re-writing of use positions does not work
  5715     return;
  5718   assert(begin_hint->assigned_reg() != any_reg, "must have register assigned");
  5719   assert(end_hint->assigned_reg() == any_reg, "must not have register assigned");
  5720   assert(cur->first_usage(mustHaveRegister) == begin_pos, "must have use position at begin of interval because of move");
  5721   assert(end_hint->first_usage(mustHaveRegister) == end_pos, "must have use position at begin of interval because of move");
  5723   if (begin_hint->assigned_reg() < LinearScan::nof_regs) {
  5724     // register_hint is not spilled at begin_pos, so it would not be benefitial to immediately spill cur
  5725     return;
  5727   assert(register_hint->canonical_spill_slot() != -1, "must be set when part of interval was spilled");
  5729   // modify intervals such that cur gets the same stack slot as register_hint
  5730   // delete use positions to prevent the intervals to get a register at beginning
  5731   cur->set_canonical_spill_slot(register_hint->canonical_spill_slot());
  5732   cur->remove_first_use_pos();
  5733   end_hint->remove_first_use_pos();
  5737 // allocate a physical register or memory location to an interval
  5738 bool LinearScanWalker::activate_current() {
  5739   Interval* cur = current();
  5740   bool result = true;
  5742   TRACE_LINEAR_SCAN(2, tty->print   ("+++++ activating interval "); cur->print());
  5743   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()));
  5745   if (cur->assigned_reg() >= LinearScan::nof_regs) {
  5746     // activating an interval that has a stack slot assigned -> split it at first use position
  5747     // used for method parameters
  5748     TRACE_LINEAR_SCAN(4, tty->print_cr("      interval has spill slot assigned (method parameter) -> split it before first use"));
  5750     split_stack_interval(cur);
  5751     result = false;
  5753   } else if (allocator()->gen()->is_vreg_flag_set(cur->reg_num(), LIRGenerator::must_start_in_memory)) {
  5754     // activating an interval that must start in a stack slot, but may get a register later
  5755     // used for lir_roundfp: rounding is done by store to stack and reload later
  5756     TRACE_LINEAR_SCAN(4, tty->print_cr("      interval must start in stack slot -> split it before first use"));
  5757     assert(cur->assigned_reg() == any_reg && cur->assigned_regHi() == any_reg, "register already assigned");
  5759     allocator()->assign_spill_slot(cur);
  5760     split_stack_interval(cur);
  5761     result = false;
  5763   } else if (cur->assigned_reg() == any_reg) {
  5764     // interval has not assigned register -> normal allocation
  5765     // (this is the normal case for most intervals)
  5766     TRACE_LINEAR_SCAN(4, tty->print_cr("      normal allocation of register"));
  5768     // assign same spill slot to non-intersecting intervals
  5769     combine_spilled_intervals(cur);
  5771     init_vars_for_alloc(cur);
  5772     if (no_allocation_possible(cur) || !alloc_free_reg(cur)) {
  5773       // no empty register available.
  5774       // split and spill another interval so that this interval gets a register
  5775       alloc_locked_reg(cur);
  5778     // spilled intervals need not be move to active-list
  5779     if (cur->assigned_reg() >= LinearScan::nof_regs) {
  5780       result = false;
  5784   // load spilled values that become active from stack slot to register
  5785   if (cur->insert_move_when_activated()) {
  5786     assert(cur->is_split_child(), "must be");
  5787     assert(cur->current_split_child() != NULL, "must be");
  5788     assert(cur->current_split_child()->reg_num() != cur->reg_num(), "cannot insert move between same interval");
  5789     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()));
  5791     insert_move(cur->from(), cur->current_split_child(), cur);
  5793   cur->make_current_split_child();
  5795   return result; // true = interval is moved to active list
  5799 // Implementation of EdgeMoveOptimizer
  5801 EdgeMoveOptimizer::EdgeMoveOptimizer() :
  5802   _edge_instructions(4),
  5803   _edge_instructions_idx(4)
  5807 void EdgeMoveOptimizer::optimize(BlockList* code) {
  5808   EdgeMoveOptimizer optimizer = EdgeMoveOptimizer();
  5810   // ignore the first block in the list (index 0 is not processed)
  5811   for (int i = code->length() - 1; i >= 1; i--) {
  5812     BlockBegin* block = code->at(i);
  5814     if (block->number_of_preds() > 1 && !block->is_set(BlockBegin::exception_entry_flag)) {
  5815       optimizer.optimize_moves_at_block_end(block);
  5817     if (block->number_of_sux() == 2) {
  5818       optimizer.optimize_moves_at_block_begin(block);
  5824 // clear all internal data structures
  5825 void EdgeMoveOptimizer::init_instructions() {
  5826   _edge_instructions.clear();
  5827   _edge_instructions_idx.clear();
  5830 // append a lir-instruction-list and the index of the current operation in to the list
  5831 void EdgeMoveOptimizer::append_instructions(LIR_OpList* instructions, int instructions_idx) {
  5832   _edge_instructions.append(instructions);
  5833   _edge_instructions_idx.append(instructions_idx);
  5836 // return the current operation of the given edge (predecessor or successor)
  5837 LIR_Op* EdgeMoveOptimizer::instruction_at(int edge) {
  5838   LIR_OpList* instructions = _edge_instructions.at(edge);
  5839   int idx = _edge_instructions_idx.at(edge);
  5841   if (idx < instructions->length()) {
  5842     return instructions->at(idx);
  5843   } else {
  5844     return NULL;
  5848 // removes the current operation of the given edge (predecessor or successor)
  5849 void EdgeMoveOptimizer::remove_cur_instruction(int edge, bool decrement_index) {
  5850   LIR_OpList* instructions = _edge_instructions.at(edge);
  5851   int idx = _edge_instructions_idx.at(edge);
  5852   instructions->remove_at(idx);
  5854   if (decrement_index) {
  5855     _edge_instructions_idx.at_put(edge, idx - 1);
  5860 bool EdgeMoveOptimizer::operations_different(LIR_Op* op1, LIR_Op* op2) {
  5861   if (op1 == NULL || op2 == NULL) {
  5862     // at least one block is already empty -> no optimization possible
  5863     return true;
  5866   if (op1->code() == lir_move && op2->code() == lir_move) {
  5867     assert(op1->as_Op1() != NULL, "move must be LIR_Op1");
  5868     assert(op2->as_Op1() != NULL, "move must be LIR_Op1");
  5869     LIR_Op1* move1 = (LIR_Op1*)op1;
  5870     LIR_Op1* move2 = (LIR_Op1*)op2;
  5871     if (move1->info() == move2->info() && move1->in_opr() == move2->in_opr() && move1->result_opr() == move2->result_opr()) {
  5872       // these moves are exactly equal and can be optimized
  5873       return false;
  5876   } else if (op1->code() == lir_fxch && op2->code() == lir_fxch) {
  5877     assert(op1->as_Op1() != NULL, "fxch must be LIR_Op1");
  5878     assert(op2->as_Op1() != NULL, "fxch must be LIR_Op1");
  5879     LIR_Op1* fxch1 = (LIR_Op1*)op1;
  5880     LIR_Op1* fxch2 = (LIR_Op1*)op2;
  5881     if (fxch1->in_opr()->as_jint() == fxch2->in_opr()->as_jint()) {
  5882       // equal FPU stack operations can be optimized
  5883       return false;
  5886   } else if (op1->code() == lir_fpop_raw && op2->code() == lir_fpop_raw) {
  5887     // equal FPU stack operations can be optimized
  5888     return false;
  5891   // no optimization possible
  5892   return true;
  5895 void EdgeMoveOptimizer::optimize_moves_at_block_end(BlockBegin* block) {
  5896   TRACE_LINEAR_SCAN(4, tty->print_cr("optimizing moves at end of block B%d", block->block_id()));
  5898   if (block->is_predecessor(block)) {
  5899     // currently we can't handle this correctly.
  5900     return;
  5903   init_instructions();
  5904   int num_preds = block->number_of_preds();
  5905   assert(num_preds > 1, "do not call otherwise");
  5906   assert(!block->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
  5908   // setup a list with the lir-instructions of all predecessors
  5909   int i;
  5910   for (i = 0; i < num_preds; i++) {
  5911     BlockBegin* pred = block->pred_at(i);
  5912     LIR_OpList* pred_instructions = pred->lir()->instructions_list();
  5914     if (pred->number_of_sux() != 1) {
  5915       // this can happen with switch-statements where multiple edges are between
  5916       // the same blocks.
  5917       return;
  5920     assert(pred->number_of_sux() == 1, "can handle only one successor");
  5921     assert(pred->sux_at(0) == block, "invalid control flow");
  5922     assert(pred_instructions->last()->code() == lir_branch, "block with successor must end with branch");
  5923     assert(pred_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
  5924     assert(pred_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
  5926     if (pred_instructions->last()->info() != NULL) {
  5927       // can not optimize instructions when debug info is needed
  5928       return;
  5931     // ignore the unconditional branch at the end of the block
  5932     append_instructions(pred_instructions, pred_instructions->length() - 2);
  5936   // process lir-instructions while all predecessors end with the same instruction
  5937   while (true) {
  5938     LIR_Op* op = instruction_at(0);
  5939     for (i = 1; i < num_preds; i++) {
  5940       if (operations_different(op, instruction_at(i))) {
  5941         // these instructions are different and cannot be optimized ->
  5942         // no further optimization possible
  5943         return;
  5947     TRACE_LINEAR_SCAN(4, tty->print("found instruction that is equal in all %d predecessors: ", num_preds); op->print());
  5949     // insert the instruction at the beginning of the current block
  5950     block->lir()->insert_before(1, op);
  5952     // delete the instruction at the end of all predecessors
  5953     for (i = 0; i < num_preds; i++) {
  5954       remove_cur_instruction(i, true);
  5960 void EdgeMoveOptimizer::optimize_moves_at_block_begin(BlockBegin* block) {
  5961   TRACE_LINEAR_SCAN(4, tty->print_cr("optimization moves at begin of block B%d", block->block_id()));
  5963   init_instructions();
  5964   int num_sux = block->number_of_sux();
  5966   LIR_OpList* cur_instructions = block->lir()->instructions_list();
  5968   assert(num_sux == 2, "method should not be called otherwise");
  5969   assert(cur_instructions->last()->code() == lir_branch, "block with successor must end with branch");
  5970   assert(cur_instructions->last()->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
  5971   assert(cur_instructions->last()->as_OpBranch()->cond() == lir_cond_always, "block must end with unconditional branch");
  5973   if (cur_instructions->last()->info() != NULL) {
  5974     // can no optimize instructions when debug info is needed
  5975     return;
  5978   LIR_Op* branch = cur_instructions->at(cur_instructions->length() - 2);
  5979   if (branch->info() != NULL || (branch->code() != lir_branch && branch->code() != lir_cond_float_branch)) {
  5980     // not a valid case for optimization
  5981     // currently, only blocks that end with two branches (conditional branch followed
  5982     // by unconditional branch) are optimized
  5983     return;
  5986   // now it is guaranteed that the block ends with two branch instructions.
  5987   // the instructions are inserted at the end of the block before these two branches
  5988   int insert_idx = cur_instructions->length() - 2;
  5990   int i;
  5991 #ifdef ASSERT
  5992   for (i = insert_idx - 1; i >= 0; i--) {
  5993     LIR_Op* op = cur_instructions->at(i);
  5994     if ((op->code() == lir_branch || op->code() == lir_cond_float_branch) && ((LIR_OpBranch*)op)->block() != NULL) {
  5995       assert(false, "block with two successors can have only two branch instructions");
  5998 #endif
  6000   // setup a list with the lir-instructions of all successors
  6001   for (i = 0; i < num_sux; i++) {
  6002     BlockBegin* sux = block->sux_at(i);
  6003     LIR_OpList* sux_instructions = sux->lir()->instructions_list();
  6005     assert(sux_instructions->at(0)->code() == lir_label, "block must start with label");
  6007     if (sux->number_of_preds() != 1) {
  6008       // this can happen with switch-statements where multiple edges are between
  6009       // the same blocks.
  6010       return;
  6012     assert(sux->pred_at(0) == block, "invalid control flow");
  6013     assert(!sux->is_set(BlockBegin::exception_entry_flag), "exception handlers not allowed");
  6015     // ignore the label at the beginning of the block
  6016     append_instructions(sux_instructions, 1);
  6019   // process lir-instructions while all successors begin with the same instruction
  6020   while (true) {
  6021     LIR_Op* op = instruction_at(0);
  6022     for (i = 1; i < num_sux; i++) {
  6023       if (operations_different(op, instruction_at(i))) {
  6024         // these instructions are different and cannot be optimized ->
  6025         // no further optimization possible
  6026         return;
  6030 #ifdef MIPS
  6031     // Some platforms, such as mips, s390 and aarch64, the branch instruction may contain register operands.
  6032     // If the move instruction would change the branch instruction's operand after the optimization, we can't apply it.
  6033     if (branch->as_Op2() != NULL) {
  6034       LIR_Op2* branch_op2 = (LIR_Op2*)branch;
  6035       if (op->result_opr()->has_common_register(branch_op2->in_opr1())) return;
  6036       if (op->result_opr()->has_common_register(branch_op2->in_opr2())) return;
  6038 #endif
  6040     TRACE_LINEAR_SCAN(4, tty->print("----- found instruction that is equal in all %d successors: ", num_sux); op->print());
  6042     // insert instruction at end of current block
  6043     block->lir()->insert_before(insert_idx, op);
  6044     insert_idx++;
  6046     // delete the instructions at the beginning of all successors
  6047     for (i = 0; i < num_sux; i++) {
  6048       remove_cur_instruction(i, false);
  6054 // Implementation of ControlFlowOptimizer
  6056 ControlFlowOptimizer::ControlFlowOptimizer() :
  6057   _original_preds(4)
  6061 void ControlFlowOptimizer::optimize(BlockList* code) {
  6062   ControlFlowOptimizer optimizer = ControlFlowOptimizer();
  6064   // push the OSR entry block to the end so that we're not jumping over it.
  6065   BlockBegin* osr_entry = code->at(0)->end()->as_Base()->osr_entry();
  6066   if (osr_entry) {
  6067     int index = osr_entry->linear_scan_number();
  6068     assert(code->at(index) == osr_entry, "wrong index");
  6069     code->remove_at(index);
  6070     code->append(osr_entry);
  6073   optimizer.reorder_short_loops(code);
  6074   optimizer.delete_empty_blocks(code);
  6075   optimizer.delete_unnecessary_jumps(code);
  6076   optimizer.delete_jumps_to_return(code);
  6079 void ControlFlowOptimizer::reorder_short_loop(BlockList* code, BlockBegin* header_block, int header_idx) {
  6080   int i = header_idx + 1;
  6081   int max_end = MIN2(header_idx + ShortLoopSize, code->length());
  6082   while (i < max_end && code->at(i)->loop_depth() >= header_block->loop_depth()) {
  6083     i++;
  6086   if (i == code->length() || code->at(i)->loop_depth() < header_block->loop_depth()) {
  6087     int end_idx = i - 1;
  6088     BlockBegin* end_block = code->at(end_idx);
  6090     if (end_block->number_of_sux() == 1 && end_block->sux_at(0) == header_block) {
  6091       // short loop from header_idx to end_idx found -> reorder blocks such that
  6092       // the header_block is the last block instead of the first block of the loop
  6093       TRACE_LINEAR_SCAN(1, tty->print_cr("Reordering short loop: length %d, header B%d, end B%d",
  6094                                          end_idx - header_idx + 1,
  6095                                          header_block->block_id(), end_block->block_id()));
  6097       for (int j = header_idx; j < end_idx; j++) {
  6098         code->at_put(j, code->at(j + 1));
  6100       code->at_put(end_idx, header_block);
  6102       // correct the flags so that any loop alignment occurs in the right place.
  6103       assert(code->at(end_idx)->is_set(BlockBegin::backward_branch_target_flag), "must be backward branch target");
  6104       code->at(end_idx)->clear(BlockBegin::backward_branch_target_flag);
  6105       code->at(header_idx)->set(BlockBegin::backward_branch_target_flag);
  6110 void ControlFlowOptimizer::reorder_short_loops(BlockList* code) {
  6111   for (int i = code->length() - 1; i >= 0; i--) {
  6112     BlockBegin* block = code->at(i);
  6114     if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {
  6115       reorder_short_loop(code, block, i);
  6119   DEBUG_ONLY(verify(code));
  6122 // only blocks with exactly one successor can be deleted. Such blocks
  6123 // must always end with an unconditional branch to this successor
  6124 bool ControlFlowOptimizer::can_delete_block(BlockBegin* block) {
  6125   if (block->number_of_sux() != 1 || block->number_of_exception_handlers() != 0 || block->is_entry_block()) {
  6126     return false;
  6129   LIR_OpList* instructions = block->lir()->instructions_list();
  6131   assert(instructions->length() >= 2, "block must have label and branch");
  6132   assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
  6133   assert(instructions->last()->as_OpBranch() != NULL, "last instrcution must always be a branch");
  6134   assert(instructions->last()->as_OpBranch()->cond() == lir_cond_always, "branch must be unconditional");
  6135   assert(instructions->last()->as_OpBranch()->block() == block->sux_at(0), "branch target must be the successor");
  6137   // block must have exactly one successor
  6139   if (instructions->length() == 2 && instructions->last()->info() == NULL) {
  6140     return true;
  6142   return false;
  6145 // substitute branch targets in all branch-instructions of this blocks
  6146 void ControlFlowOptimizer::substitute_branch_target(BlockBegin* block, BlockBegin* target_from, BlockBegin* target_to) {
  6147   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()));
  6149   LIR_OpList* instructions = block->lir()->instructions_list();
  6151   assert(instructions->at(0)->code() == lir_label, "first instruction must always be a label");
  6152   for (int i = instructions->length() - 1; i >= 1; i--) {
  6153     LIR_Op* op = instructions->at(i);
  6155     if (op->code() == lir_branch || op->code() == lir_cond_float_branch) {
  6156       assert(op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
  6157       LIR_OpBranch* branch = (LIR_OpBranch*)op;
  6159       if (branch->block() == target_from) {
  6160         branch->change_block(target_to);
  6162       if (branch->ublock() == target_from) {
  6163         branch->change_ublock(target_to);
  6169 void ControlFlowOptimizer::delete_empty_blocks(BlockList* code) {
  6170   int old_pos = 0;
  6171   int new_pos = 0;
  6172   int num_blocks = code->length();
  6174   while (old_pos < num_blocks) {
  6175     BlockBegin* block = code->at(old_pos);
  6177     if (can_delete_block(block)) {
  6178       BlockBegin* new_target = block->sux_at(0);
  6180       // propagate backward branch target flag for correct code alignment
  6181       if (block->is_set(BlockBegin::backward_branch_target_flag)) {
  6182         new_target->set(BlockBegin::backward_branch_target_flag);
  6185       // collect a list with all predecessors that contains each predecessor only once
  6186       // the predecessors of cur are changed during the substitution, so a copy of the
  6187       // predecessor list is necessary
  6188       int j;
  6189       _original_preds.clear();
  6190       for (j = block->number_of_preds() - 1; j >= 0; j--) {
  6191         BlockBegin* pred = block->pred_at(j);
  6192         if (_original_preds.index_of(pred) == -1) {
  6193           _original_preds.append(pred);
  6197       for (j = _original_preds.length() - 1; j >= 0; j--) {
  6198         BlockBegin* pred = _original_preds.at(j);
  6199         substitute_branch_target(pred, block, new_target);
  6200         pred->substitute_sux(block, new_target);
  6202     } else {
  6203       // adjust position of this block in the block list if blocks before
  6204       // have been deleted
  6205       if (new_pos != old_pos) {
  6206         code->at_put(new_pos, code->at(old_pos));
  6208       new_pos++;
  6210     old_pos++;
  6212   code->truncate(new_pos);
  6214   DEBUG_ONLY(verify(code));
  6217 void ControlFlowOptimizer::delete_unnecessary_jumps(BlockList* code) {
  6218   // skip the last block because there a branch is always necessary
  6219   for (int i = code->length() - 2; i >= 0; i--) {
  6220     BlockBegin* block = code->at(i);
  6221     LIR_OpList* instructions = block->lir()->instructions_list();
  6223     LIR_Op* last_op = instructions->last();
  6224     if (last_op->code() == lir_branch) {
  6225       assert(last_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
  6226       LIR_OpBranch* last_branch = (LIR_OpBranch*)last_op;
  6228       assert(last_branch->block() != NULL, "last branch must always have a block as target");
  6229       assert(last_branch->label() == last_branch->block()->label(), "must be equal");
  6231       if (last_branch->info() == NULL) {
  6232         if (last_branch->block() == code->at(i + 1)) {
  6234           TRACE_LINEAR_SCAN(3, tty->print_cr("Deleting unconditional branch at end of block B%d", block->block_id()));
  6236           // delete last branch instruction
  6237           instructions->truncate(instructions->length() - 1);
  6239         } else {
  6240           LIR_Op* prev_op = instructions->at(instructions->length() - 2);
  6241           if (prev_op->code() == lir_branch || prev_op->code() == lir_cond_float_branch) {
  6242             assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
  6243             LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;
  6245             if (prev_branch->stub() == NULL) {
  6247 #ifndef MIPS //MIPS not support lir_cmp. same as openjdk6.
  6248               LIR_Op2* prev_cmp = NULL;
  6250               for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {
  6251                 prev_op = instructions->at(j);
  6252                 if (prev_op->code() == lir_cmp) {
  6253                   assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");
  6254                   prev_cmp = (LIR_Op2*)prev_op;
  6255                   assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");
  6258               assert(prev_cmp != NULL, "should have found comp instruction for branch");
  6259 #endif
  6260               if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {
  6262                 TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));
  6264                 // eliminate a conditional branch to the immediate successor
  6265                 prev_branch->change_block(last_branch->block());
  6266                 prev_branch->negate_cond();
  6267 #ifndef MIPS //MIPS not support lir_cmp. same as openjdk6.
  6268                 prev_cmp->set_condition(prev_branch->cond());
  6269 #endif
  6270                 instructions->truncate(instructions->length() - 1);
  6279   DEBUG_ONLY(verify(code));
  6282 void ControlFlowOptimizer::delete_jumps_to_return(BlockList* code) {
  6283 #ifdef ASSERT
  6284   BitMap return_converted(BlockBegin::number_of_blocks());
  6285   return_converted.clear();
  6286 #endif
  6288   for (int i = code->length() - 1; i >= 0; i--) {
  6289     BlockBegin* block = code->at(i);
  6290     LIR_OpList* cur_instructions = block->lir()->instructions_list();
  6291     LIR_Op*     cur_last_op = cur_instructions->last();
  6293     assert(cur_instructions->at(0)->code() == lir_label, "first instruction must always be a label");
  6294     if (cur_instructions->length() == 2 && cur_last_op->code() == lir_return) {
  6295       // the block contains only a label and a return
  6296       // if a predecessor ends with an unconditional jump to this block, then the jump
  6297       // can be replaced with a return instruction
  6298       //
  6299       // Note: the original block with only a return statement cannot be deleted completely
  6300       //       because the predecessors might have other (conditional) jumps to this block
  6301       //       -> this may lead to unnecesary return instructions in the final code
  6303       assert(cur_last_op->info() == NULL, "return instructions do not have debug information");
  6304       assert(block->number_of_sux() == 0 ||
  6305              (return_converted.at(block->block_id()) && block->number_of_sux() == 1),
  6306              "blocks that end with return must not have successors");
  6308       assert(cur_last_op->as_Op1() != NULL, "return must be LIR_Op1");
  6309       LIR_Opr return_opr = ((LIR_Op1*)cur_last_op)->in_opr();
  6311       for (int j = block->number_of_preds() - 1; j >= 0; j--) {
  6312         BlockBegin* pred = block->pred_at(j);
  6313         LIR_OpList* pred_instructions = pred->lir()->instructions_list();
  6314         LIR_Op*     pred_last_op = pred_instructions->last();
  6316         if (pred_last_op->code() == lir_branch) {
  6317           assert(pred_last_op->as_OpBranch() != NULL, "branch must be LIR_OpBranch");
  6318           LIR_OpBranch* pred_last_branch = (LIR_OpBranch*)pred_last_op;
  6320           if (pred_last_branch->block() == block && pred_last_branch->cond() == lir_cond_always && pred_last_branch->info() == NULL) {
  6321             // replace the jump to a return with a direct return
  6322             // Note: currently the edge between the blocks is not deleted
  6323             pred_instructions->at_put(pred_instructions->length() - 1, new LIR_Op1(lir_return, return_opr));
  6324 #ifdef ASSERT
  6325             return_converted.set_bit(pred->block_id());
  6326 #endif
  6335 #ifdef ASSERT
  6336 void ControlFlowOptimizer::verify(BlockList* code) {
  6337   for (int i = 0; i < code->length(); i++) {
  6338     BlockBegin* block = code->at(i);
  6339     LIR_OpList* instructions = block->lir()->instructions_list();
  6341     int j;
  6342     for (j = 0; j < instructions->length(); j++) {
  6343       LIR_OpBranch* op_branch = instructions->at(j)->as_OpBranch();
  6345       if (op_branch != NULL) {
  6346         assert(op_branch->block() == NULL || code->index_of(op_branch->block()) != -1, "branch target not valid");
  6347         assert(op_branch->ublock() == NULL || code->index_of(op_branch->ublock()) != -1, "branch target not valid");
  6351     for (j = 0; j < block->number_of_sux() - 1; j++) {
  6352       BlockBegin* sux = block->sux_at(j);
  6353       assert(code->index_of(sux) != -1, "successor not valid");
  6356     for (j = 0; j < block->number_of_preds() - 1; j++) {
  6357       BlockBegin* pred = block->pred_at(j);
  6358       assert(code->index_of(pred) != -1, "successor not valid");
  6362 #endif
  6365 #ifndef PRODUCT
  6367 // Implementation of LinearStatistic
  6369 const char* LinearScanStatistic::counter_name(int counter_idx) {
  6370   switch (counter_idx) {
  6371     case counter_method:          return "compiled methods";
  6372     case counter_fpu_method:      return "methods using fpu";
  6373     case counter_loop_method:     return "methods with loops";
  6374     case counter_exception_method:return "methods with xhandler";
  6376     case counter_loop:            return "loops";
  6377     case counter_block:           return "blocks";
  6378     case counter_loop_block:      return "blocks inside loop";
  6379     case counter_exception_block: return "exception handler entries";
  6380     case counter_interval:        return "intervals";
  6381     case counter_fixed_interval:  return "fixed intervals";
  6382     case counter_range:           return "ranges";
  6383     case counter_fixed_range:     return "fixed ranges";
  6384     case counter_use_pos:         return "use positions";
  6385     case counter_fixed_use_pos:   return "fixed use positions";
  6386     case counter_spill_slots:     return "spill slots";
  6388     // counter for classes of lir instructions
  6389     case counter_instruction:     return "total instructions";
  6390     case counter_label:           return "labels";
  6391     case counter_entry:           return "method entries";
  6392     case counter_return:          return "method returns";
  6393     case counter_call:            return "method calls";
  6394     case counter_move:            return "moves";
  6395     case counter_cmp:             return "compare";
  6396     case counter_cond_branch:     return "conditional branches";
  6397     case counter_uncond_branch:   return "unconditional branches";
  6398     case counter_stub_branch:     return "branches to stub";
  6399     case counter_alu:             return "artithmetic + logic";
  6400     case counter_alloc:           return "allocations";
  6401     case counter_sync:            return "synchronisation";
  6402     case counter_throw:           return "throw";
  6403     case counter_unwind:          return "unwind";
  6404     case counter_typecheck:       return "type+null-checks";
  6405     case counter_fpu_stack:       return "fpu-stack";
  6406     case counter_misc_inst:       return "other instructions";
  6407     case counter_other_inst:      return "misc. instructions";
  6409     // counter for different types of moves
  6410     case counter_move_total:      return "total moves";
  6411     case counter_move_reg_reg:    return "register->register";
  6412     case counter_move_reg_stack:  return "register->stack";
  6413     case counter_move_stack_reg:  return "stack->register";
  6414     case counter_move_stack_stack:return "stack->stack";
  6415     case counter_move_reg_mem:    return "register->memory";
  6416     case counter_move_mem_reg:    return "memory->register";
  6417     case counter_move_const_any:  return "constant->any";
  6419     case blank_line_1:            return "";
  6420     case blank_line_2:            return "";
  6422     default: ShouldNotReachHere(); return "";
  6426 LinearScanStatistic::Counter LinearScanStatistic::base_counter(int counter_idx) {
  6427   if (counter_idx == counter_fpu_method || counter_idx == counter_loop_method || counter_idx == counter_exception_method) {
  6428     return counter_method;
  6429   } else if (counter_idx == counter_loop_block || counter_idx == counter_exception_block) {
  6430     return counter_block;
  6431   } else if (counter_idx >= counter_instruction && counter_idx <= counter_other_inst) {
  6432     return counter_instruction;
  6433   } else if (counter_idx >= counter_move_total && counter_idx <= counter_move_const_any) {
  6434     return counter_move_total;
  6436   return invalid_counter;
  6439 LinearScanStatistic::LinearScanStatistic() {
  6440   for (int i = 0; i < number_of_counters; i++) {
  6441     _counters_sum[i] = 0;
  6442     _counters_max[i] = -1;
  6447 // add the method-local numbers to the total sum
  6448 void LinearScanStatistic::sum_up(LinearScanStatistic &method_statistic) {
  6449   for (int i = 0; i < number_of_counters; i++) {
  6450     _counters_sum[i] += method_statistic._counters_sum[i];
  6451     _counters_max[i] = MAX2(_counters_max[i], method_statistic._counters_sum[i]);
  6455 void LinearScanStatistic::print(const char* title) {
  6456   if (CountLinearScan || TraceLinearScanLevel > 0) {
  6457     tty->cr();
  6458     tty->print_cr("***** LinearScan statistic - %s *****", title);
  6460     for (int i = 0; i < number_of_counters; i++) {
  6461       if (_counters_sum[i] > 0 || _counters_max[i] >= 0) {
  6462         tty->print("%25s: %8d", counter_name(i), _counters_sum[i]);
  6464         if (base_counter(i) != invalid_counter) {
  6465           tty->print("  (%5.1f%%) ", _counters_sum[i] * 100.0 / _counters_sum[base_counter(i)]);
  6466         } else {
  6467           tty->print("           ");
  6470         if (_counters_max[i] >= 0) {
  6471           tty->print("%8d", _counters_max[i]);
  6474       tty->cr();
  6479 void LinearScanStatistic::collect(LinearScan* allocator) {
  6480   inc_counter(counter_method);
  6481   if (allocator->has_fpu_registers()) {
  6482     inc_counter(counter_fpu_method);
  6484   if (allocator->num_loops() > 0) {
  6485     inc_counter(counter_loop_method);
  6487   inc_counter(counter_loop, allocator->num_loops());
  6488   inc_counter(counter_spill_slots, allocator->max_spills());
  6490   int i;
  6491   for (i = 0; i < allocator->interval_count(); i++) {
  6492     Interval* cur = allocator->interval_at(i);
  6494     if (cur != NULL) {
  6495       inc_counter(counter_interval);
  6496       inc_counter(counter_use_pos, cur->num_use_positions());
  6497       if (LinearScan::is_precolored_interval(cur)) {
  6498         inc_counter(counter_fixed_interval);
  6499         inc_counter(counter_fixed_use_pos, cur->num_use_positions());
  6502       Range* range = cur->first();
  6503       while (range != Range::end()) {
  6504         inc_counter(counter_range);
  6505         if (LinearScan::is_precolored_interval(cur)) {
  6506           inc_counter(counter_fixed_range);
  6508         range = range->next();
  6513   bool has_xhandlers = false;
  6514   // Note: only count blocks that are in code-emit order
  6515   for (i = 0; i < allocator->ir()->code()->length(); i++) {
  6516     BlockBegin* cur = allocator->ir()->code()->at(i);
  6518     inc_counter(counter_block);
  6519     if (cur->loop_depth() > 0) {
  6520       inc_counter(counter_loop_block);
  6522     if (cur->is_set(BlockBegin::exception_entry_flag)) {
  6523       inc_counter(counter_exception_block);
  6524       has_xhandlers = true;
  6527     LIR_OpList* instructions = cur->lir()->instructions_list();
  6528     for (int j = 0; j < instructions->length(); j++) {
  6529       LIR_Op* op = instructions->at(j);
  6531       inc_counter(counter_instruction);
  6533       switch (op->code()) {
  6534         case lir_label:           inc_counter(counter_label); break;
  6535         case lir_std_entry:
  6536         case lir_osr_entry:       inc_counter(counter_entry); break;
  6537         case lir_return:          inc_counter(counter_return); break;
  6539         case lir_rtcall:
  6540         case lir_static_call:
  6541         case lir_optvirtual_call:
  6542         case lir_virtual_call:    inc_counter(counter_call); break;
  6544         case lir_move: {
  6545           inc_counter(counter_move);
  6546           inc_counter(counter_move_total);
  6548           LIR_Opr in = op->as_Op1()->in_opr();
  6549           LIR_Opr res = op->as_Op1()->result_opr();
  6550           if (in->is_register()) {
  6551             if (res->is_register()) {
  6552               inc_counter(counter_move_reg_reg);
  6553             } else if (res->is_stack()) {
  6554               inc_counter(counter_move_reg_stack);
  6555             } else if (res->is_address()) {
  6556               inc_counter(counter_move_reg_mem);
  6557             } else {
  6558               ShouldNotReachHere();
  6560           } else if (in->is_stack()) {
  6561             if (res->is_register()) {
  6562               inc_counter(counter_move_stack_reg);
  6563             } else {
  6564               inc_counter(counter_move_stack_stack);
  6566           } else if (in->is_address()) {
  6567             assert(res->is_register(), "must be");
  6568             inc_counter(counter_move_mem_reg);
  6569           } else if (in->is_constant()) {
  6570             inc_counter(counter_move_const_any);
  6571           } else {
  6572             ShouldNotReachHere();
  6574           break;
  6577 #ifndef MIPS
  6578         case lir_cmp:             inc_counter(counter_cmp); break;
  6580 #endif
  6581         case lir_branch:
  6582         case lir_cond_float_branch: {
  6583           LIR_OpBranch* branch = op->as_OpBranch();
  6584           if (branch->block() == NULL) {
  6585             inc_counter(counter_stub_branch);
  6586           } else if (branch->cond() == lir_cond_always) {
  6587             inc_counter(counter_uncond_branch);
  6588           } else {
  6589             inc_counter(counter_cond_branch);
  6591           break;
  6594         case lir_neg:
  6595         case lir_add:
  6596         case lir_sub:
  6597         case lir_mul:
  6598         case lir_mul_strictfp:
  6599         case lir_div:
  6600         case lir_div_strictfp:
  6601         case lir_rem:
  6602         case lir_sqrt:
  6603         case lir_sin:
  6604         case lir_cos:
  6605         case lir_abs:
  6606         case lir_log10:
  6607         case lir_log:
  6608         case lir_pow:
  6609         case lir_exp:
  6610         case lir_logic_and:
  6611         case lir_logic_or:
  6612         case lir_logic_xor:
  6613         case lir_shl:
  6614         case lir_shr:
  6615         case lir_ushr:            inc_counter(counter_alu); break;
  6617         case lir_alloc_object:
  6618         case lir_alloc_array:     inc_counter(counter_alloc); break;
  6620         case lir_monaddr:
  6621         case lir_lock:
  6622         case lir_unlock:          inc_counter(counter_sync); break;
  6624         case lir_throw:           inc_counter(counter_throw); break;
  6626         case lir_unwind:          inc_counter(counter_unwind); break;
  6628         case lir_null_check:
  6629         case lir_leal:
  6630         case lir_instanceof:
  6631         case lir_checkcast:
  6632         case lir_store_check:     inc_counter(counter_typecheck); break;
  6634         case lir_fpop_raw:
  6635         case lir_fxch:
  6636         case lir_fld:             inc_counter(counter_fpu_stack); break;
  6638         case lir_nop:
  6639         case lir_push:
  6640         case lir_pop:
  6641         case lir_convert:
  6642         case lir_roundfp:
  6643 #ifdef MIPS
  6644         case lir_cmove_mips:
  6645 #endif
  6646         case lir_cmove:           inc_counter(counter_misc_inst); break;
  6648         default:                  inc_counter(counter_other_inst); break;
  6653   if (has_xhandlers) {
  6654     inc_counter(counter_exception_method);
  6658 void LinearScanStatistic::compute(LinearScan* allocator, LinearScanStatistic &global_statistic) {
  6659   if (CountLinearScan || TraceLinearScanLevel > 0) {
  6661     LinearScanStatistic local_statistic = LinearScanStatistic();
  6663     local_statistic.collect(allocator);
  6664     global_statistic.sum_up(local_statistic);
  6666     if (TraceLinearScanLevel > 2) {
  6667       local_statistic.print("current local statistic");
  6673 // Implementation of LinearTimers
  6675 LinearScanTimers::LinearScanTimers() {
  6676   for (int i = 0; i < number_of_timers; i++) {
  6677     timer(i)->reset();
  6681 const char* LinearScanTimers::timer_name(int idx) {
  6682   switch (idx) {
  6683     case timer_do_nothing:               return "Nothing (Time Check)";
  6684     case timer_number_instructions:      return "Number Instructions";
  6685     case timer_compute_local_live_sets:  return "Local Live Sets";
  6686     case timer_compute_global_live_sets: return "Global Live Sets";
  6687     case timer_build_intervals:          return "Build Intervals";
  6688     case timer_sort_intervals_before:    return "Sort Intervals Before";
  6689     case timer_allocate_registers:       return "Allocate Registers";
  6690     case timer_resolve_data_flow:        return "Resolve Data Flow";
  6691     case timer_sort_intervals_after:     return "Sort Intervals After";
  6692     case timer_eliminate_spill_moves:    return "Spill optimization";
  6693     case timer_assign_reg_num:           return "Assign Reg Num";
  6694     case timer_allocate_fpu_stack:       return "Allocate FPU Stack";
  6695     case timer_optimize_lir:             return "Optimize LIR";
  6696     default: ShouldNotReachHere();       return "";
  6700 void LinearScanTimers::begin_method() {
  6701   if (TimeEachLinearScan) {
  6702     // reset all timers to measure only current method
  6703     for (int i = 0; i < number_of_timers; i++) {
  6704       timer(i)->reset();
  6709 void LinearScanTimers::end_method(LinearScan* allocator) {
  6710   if (TimeEachLinearScan) {
  6712     double c = timer(timer_do_nothing)->seconds();
  6713     double total = 0;
  6714     for (int i = 1; i < number_of_timers; i++) {
  6715       total += timer(i)->seconds() - c;
  6718     if (total >= 0.0005) {
  6719       // print all information in one line for automatic processing
  6720       tty->print("@"); allocator->compilation()->method()->print_name();
  6722       tty->print("@ %d ", allocator->compilation()->method()->code_size());
  6723       tty->print("@ %d ", allocator->block_at(allocator->block_count() - 1)->last_lir_instruction_id() / 2);
  6724       tty->print("@ %d ", allocator->block_count());
  6725       tty->print("@ %d ", allocator->num_virtual_regs());
  6726       tty->print("@ %d ", allocator->interval_count());
  6727       tty->print("@ %d ", allocator->_num_calls);
  6728       tty->print("@ %d ", allocator->num_loops());
  6730       tty->print("@ %6.6f ", total);
  6731       for (int i = 1; i < number_of_timers; i++) {
  6732         tty->print("@ %4.1f ", ((timer(i)->seconds() - c) / total) * 100);
  6734       tty->cr();
  6739 void LinearScanTimers::print(double total_time) {
  6740   if (TimeLinearScan) {
  6741     // correction value: sum of dummy-timer that only measures the time that
  6742     // is necesary to start and stop itself
  6743     double c = timer(timer_do_nothing)->seconds();
  6745     for (int i = 0; i < number_of_timers; i++) {
  6746       double t = timer(i)->seconds();
  6747       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);
  6752 #endif // #ifndef PRODUCT

mercurial