1 /*
   2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "c1/c1_Compilation.hpp"
  27 #include "c1/c1_FrameMap.hpp"
  28 #include "c1/c1_GraphBuilder.hpp"
  29 #include "c1/c1_IR.hpp"
  30 #include "c1/c1_InstructionPrinter.hpp"
  31 #include "c1/c1_Optimizer.hpp"
  32 #include "utilities/bitMap.inline.hpp"
  33 
  34 
  35 // Implementation of XHandlers
  36 //
  37 // Note: This code could eventually go away if we are
  38 //       just using the ciExceptionHandlerStream.
  39 
  40 XHandlers::XHandlers(ciMethod* method) : _list(method->exception_table_length()) {
  41   ciExceptionHandlerStream s(method);
  42   while (!s.is_done()) {
  43     _list.append(new XHandler(s.handler()));
  44     s.next();
  45   }
  46   assert(s.count() == method->exception_table_length(), "exception table lengths inconsistent");
  47 }
  48 
  49 // deep copy of all XHandler contained in list
  50 XHandlers::XHandlers(XHandlers* other) :
  51   _list(other->length())
  52 {
  53   for (int i = 0; i < other->length(); i++) {
  54     _list.append(new XHandler(other->handler_at(i)));
  55   }
  56 }
  57 
  58 // Returns whether a particular exception type can be caught.  Also
  59 // returns true if klass is unloaded or any exception handler
  60 // classes are unloaded.  type_is_exact indicates whether the throw
  61 // is known to be exactly that class or it might throw a subtype.
  62 bool XHandlers::could_catch(ciInstanceKlass* klass, bool type_is_exact) const {
  63   // the type is unknown so be conservative
  64   if (!klass->is_loaded()) {
  65     return true;
  66   }
  67 
  68   for (int i = 0; i < length(); i++) {
  69     XHandler* handler = handler_at(i);
  70     if (handler->is_catch_all()) {
  71       // catch of ANY
  72       return true;
  73     }
  74     ciInstanceKlass* handler_klass = handler->catch_klass();
  75     // if it's unknown it might be catchable
  76     if (!handler_klass->is_loaded()) {
  77       return true;
  78     }
  79     // if the throw type is definitely a subtype of the catch type
  80     // then it can be caught.
  81     if (klass->is_subtype_of(handler_klass)) {
  82       return true;
  83     }
  84     if (!type_is_exact) {
  85       // If the type isn't exactly known then it can also be caught by
  86       // catch statements where the inexact type is a subtype of the
  87       // catch type.
  88       // given: foo extends bar extends Exception
  89       // throw bar can be caught by catch foo, catch bar, and catch
  90       // Exception, however it can't be caught by any handlers without
  91       // bar in its type hierarchy.
  92       if (handler_klass->is_subtype_of(klass)) {
  93         return true;
  94       }
  95     }
  96   }
  97 
  98   return false;
  99 }
 100 
 101 
 102 bool XHandlers::equals(XHandlers* others) const {
 103   if (others == NULL) return false;
 104   if (length() != others->length()) return false;
 105 
 106   for (int i = 0; i < length(); i++) {
 107     if (!handler_at(i)->equals(others->handler_at(i))) return false;
 108   }
 109   return true;
 110 }
 111 
 112 bool XHandler::equals(XHandler* other) const {
 113   assert(entry_pco() != -1 && other->entry_pco() != -1, "must have entry_pco");
 114 
 115   if (entry_pco() != other->entry_pco()) return false;
 116   if (scope_count() != other->scope_count()) return false;
 117   if (_desc != other->_desc) return false;
 118 
 119   assert(entry_block() == other->entry_block(), "entry_block must be equal when entry_pco is equal");
 120   return true;
 121 }
 122 
 123 
 124 // Implementation of IRScope
 125 BlockBegin* IRScope::build_graph(Compilation* compilation, int osr_bci) {
 126   GraphBuilder gm(compilation, this);
 127   NOT_PRODUCT(if (PrintValueNumbering && Verbose) gm.print_stats());
 128   if (compilation->bailed_out()) return NULL;
 129   return gm.start();
 130 }
 131 
 132 
 133 IRScope::IRScope(Compilation* compilation, IRScope* caller, int caller_bci, ciMethod* method, int osr_bci, bool create_graph)
 134 : _callees(2)
 135 , _compilation(compilation)
 136 , _requires_phi_function(method->max_locals())
 137 {
 138   _caller             = caller;
 139   _level              = caller == NULL ?  0 : caller->level() + 1;
 140   _method             = method;
 141   _xhandlers          = new XHandlers(method);
 142   _number_of_locks    = 0;
 143   _monitor_pairing_ok = method->has_balanced_monitors();
 144   _wrote_final        = false;
 145   _start              = NULL;
 146 
 147   if (osr_bci == -1) {
 148     _requires_phi_function.clear();
 149   } else {
 150         // selective creation of phi functions is not possibel in osr-methods
 151     _requires_phi_function.set_range(0, method->max_locals());
 152   }
 153 
 154   assert(method->holder()->is_loaded() , "method holder must be loaded");
 155 
 156   // build graph if monitor pairing is ok
 157   if (create_graph && monitor_pairing_ok()) _start = build_graph(compilation, osr_bci);
 158 }
 159 
 160 
 161 int IRScope::max_stack() const {
 162   int my_max = method()->max_stack();
 163   int callee_max = 0;
 164   for (int i = 0; i < number_of_callees(); i++) {
 165     callee_max = MAX2(callee_max, callee_no(i)->max_stack());
 166   }
 167   return my_max + callee_max;
 168 }
 169 
 170 
 171 bool IRScopeDebugInfo::should_reexecute() {
 172   ciMethod* cur_method = scope()->method();
 173   int       cur_bci    = bci();
 174   if (cur_method != NULL && cur_bci != SynchronizationEntryBCI) {
 175     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 176     return Interpreter::bytecode_should_reexecute(code);
 177   } else
 178     return false;
 179 }
 180 
 181 
 182 // Implementation of CodeEmitInfo
 183 
 184 // Stack must be NON-null
 185 CodeEmitInfo::CodeEmitInfo(ValueStack* stack, XHandlers* exception_handlers, bool deoptimize_on_exception)
 186   : _scope(stack->scope())
 187   , _scope_debug_info(NULL)
 188   , _oop_map(NULL)
 189   , _stack(stack)
 190   , _exception_handlers(exception_handlers)
 191   , _is_method_handle_invoke(false)
 192   , _deoptimize_on_exception(deoptimize_on_exception) {
 193   assert(_stack != NULL, "must be non null");
 194 }
 195 
 196 
 197 CodeEmitInfo::CodeEmitInfo(CodeEmitInfo* info, ValueStack* stack)
 198   : _scope(info->_scope)
 199   , _exception_handlers(NULL)
 200   , _scope_debug_info(NULL)
 201   , _oop_map(NULL)
 202   , _stack(stack == NULL ? info->_stack : stack)
 203   , _is_method_handle_invoke(info->_is_method_handle_invoke)
 204   , _deoptimize_on_exception(info->_deoptimize_on_exception) {
 205 
 206   // deep copy of exception handlers
 207   if (info->_exception_handlers != NULL) {
 208     _exception_handlers = new XHandlers(info->_exception_handlers);
 209   }
 210 }
 211 
 212 
 213 void CodeEmitInfo::record_debug_info(DebugInformationRecorder* recorder, int pc_offset) {
 214   // record the safepoint before recording the debug info for enclosing scopes
 215   recorder->add_safepoint(pc_offset, _oop_map->deep_copy());
 216   _scope_debug_info->record_debug_info(recorder, pc_offset, true/*topmost*/, _is_method_handle_invoke);
 217   recorder->end_safepoint(pc_offset);
 218 }
 219 
 220 
 221 void CodeEmitInfo::record_non_safepoint_debug_info(DebugInformationRecorder* recorder, int pc_offset) {
 222   if (recorder->recording_non_safepoints()) {
 223     recorder->add_non_safepoint(pc_offset);
 224     record_scope_non_safepoint_debug_info(recorder, pc_offset, scope(), stack());
 225     recorder->end_non_safepoint(pc_offset);
 226   }
 227 }
 228 
 229 
 230 void CodeEmitInfo::record_scope_non_safepoint_debug_info(DebugInformationRecorder* recorder, int pc_offset, IRScope *scope, ValueStack *state) {
 231   if (scope->caller() != NULL) {
 232     record_scope_non_safepoint_debug_info(recorder, pc_offset, scope->caller(), state->caller_state());
 233   }
 234   recorder->describe_scope(pc_offset, scope->method(), state->bci(), false);
 235 }
 236 
 237 
 238 void CodeEmitInfo::add_register_oop(LIR_Opr opr) {
 239   assert(_oop_map != NULL, "oop map must already exist");
 240   assert(opr->is_single_cpu(), "should not call otherwise");
 241 
 242   VMReg name = frame_map()->regname(opr);
 243   _oop_map->set_oop(name);
 244 }
 245 
 246 // Mirror the stack size calculation in the deopt code
 247 // How much stack space would we need at this point in the program in
 248 // case of deoptimization?
 249 int CodeEmitInfo::interpreter_frame_size() const {
 250   ValueStack* state = _stack;
 251   int size = 0;
 252   int callee_parameters = 0;
 253   int callee_locals = 0;
 254   int extra_args = state->scope()->method()->max_stack() - state->stack_size();
 255 
 256   while (state != NULL) {
 257     int locks = state->locks_size();
 258     int temps = state->stack_size();
 259     bool is_top_frame = (state == _stack);
 260     ciMethod* method = state->scope()->method();
 261 
 262     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
 263                                                                  temps + callee_parameters,
 264                                                                  extra_args,
 265                                                                  locks,
 266                                                                  callee_parameters,
 267                                                                  callee_locals,
 268                                                                  is_top_frame);
 269     size += frame_size;
 270 
 271     callee_parameters = method->size_of_parameters();
 272     callee_locals = method->max_locals();
 273     extra_args = 0;
 274     state = state->caller_state();
 275   }
 276   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
 277 }
 278 
 279 // Implementation of IR
 280 
 281 IR::IR(Compilation* compilation, ciMethod* method, int osr_bci) :
 282     _locals_size(in_WordSize(-1))
 283   , _num_loops(0) {
 284   // setup IR fields
 285   _compilation = compilation;
 286   _top_scope   = new IRScope(compilation, NULL, -1, method, osr_bci, true);
 287   _code        = NULL;
 288 }
 289 
 290 
 291 void IR::optimize_blocks() {
 292   Optimizer opt(this);
 293   if (!compilation()->profile_branches()) {
 294     if (DoCEE) {
 295       opt.eliminate_conditional_expressions();
 296 #ifndef PRODUCT
 297       if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after CEE"); print(true); }
 298       if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after CEE"); print(false); }
 299 #endif
 300     }
 301     if (EliminateBlocks) {
 302       opt.eliminate_blocks();
 303 #ifndef PRODUCT
 304       if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after block elimination"); print(true); }
 305       if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after block elimination"); print(false); }
 306 #endif
 307     }
 308   }
 309 }
 310 
 311 void IR::eliminate_null_checks() {
 312   Optimizer opt(this);
 313   if (EliminateNullChecks) {
 314     opt.eliminate_null_checks();
 315 #ifndef PRODUCT
 316     if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after null check elimination"); print(true); }
 317     if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after null check elimination"); print(false); }
 318 #endif
 319   }
 320 }
 321 
 322 
 323 static int sort_pairs(BlockPair** a, BlockPair** b) {
 324   if ((*a)->from() == (*b)->from()) {
 325     return (*a)->to()->block_id() - (*b)->to()->block_id();
 326   } else {
 327     return (*a)->from()->block_id() - (*b)->from()->block_id();
 328   }
 329 }
 330 
 331 
 332 class CriticalEdgeFinder: public BlockClosure {
 333   BlockPairList blocks;
 334   IR*       _ir;
 335 
 336  public:
 337   CriticalEdgeFinder(IR* ir): _ir(ir) {}
 338   void block_do(BlockBegin* bb) {
 339     BlockEnd* be = bb->end();
 340     int nos = be->number_of_sux();
 341     if (nos >= 2) {
 342       for (int i = 0; i < nos; i++) {
 343         BlockBegin* sux = be->sux_at(i);
 344         if (sux->number_of_preds() >= 2) {
 345           blocks.append(new BlockPair(bb, sux));
 346         }
 347       }
 348     }
 349   }
 350 
 351   void split_edges() {
 352     BlockPair* last_pair = NULL;
 353     blocks.sort(sort_pairs);
 354     for (int i = 0; i < blocks.length(); i++) {
 355       BlockPair* pair = blocks.at(i);
 356       if (last_pair != NULL && pair->is_same(last_pair)) continue;
 357       BlockBegin* from = pair->from();
 358       BlockBegin* to = pair->to();
 359       BlockBegin* split = from->insert_block_between(to);
 360 #ifndef PRODUCT
 361       if ((PrintIR || PrintIR1) && Verbose) {
 362         tty->print_cr("Split critical edge B%d -> B%d (new block B%d)",
 363                       from->block_id(), to->block_id(), split->block_id());
 364       }
 365 #endif
 366       last_pair = pair;
 367     }
 368   }
 369 };
 370 
 371 void IR::split_critical_edges() {
 372   CriticalEdgeFinder cef(this);
 373 
 374   iterate_preorder(&cef);
 375   cef.split_edges();
 376 }
 377 
 378 
 379 class UseCountComputer: public ValueVisitor, BlockClosure {
 380  private:
 381   void visit(Value* n) {
 382     // Local instructions and Phis for expression stack values at the
 383     // start of basic blocks are not added to the instruction list
 384     if (!(*n)->is_linked() && (*n)->can_be_linked()) {
 385       assert(false, "a node was not appended to the graph");
 386       Compilation::current()->bailout("a node was not appended to the graph");
 387     }
 388     // use n's input if not visited before
 389     if (!(*n)->is_pinned() && !(*n)->has_uses()) {
 390       // note: a) if the instruction is pinned, it will be handled by compute_use_count
 391       //       b) if the instruction has uses, it was touched before
 392       //       => in both cases we don't need to update n's values
 393       uses_do(n);
 394     }
 395     // use n
 396     (*n)->_use_count++;
 397   }
 398 
 399   Values* worklist;
 400   int depth;
 401   enum {
 402     max_recurse_depth = 20
 403   };
 404 
 405   void uses_do(Value* n) {
 406     depth++;
 407     if (depth > max_recurse_depth) {
 408       // don't allow the traversal to recurse too deeply
 409       worklist->push(*n);
 410     } else {
 411       (*n)->input_values_do(this);
 412       // special handling for some instructions
 413       if ((*n)->as_BlockEnd() != NULL) {
 414         // note on BlockEnd:
 415         //   must 'use' the stack only if the method doesn't
 416         //   terminate, however, in those cases stack is empty
 417         (*n)->state_values_do(this);
 418       }
 419     }
 420     depth--;
 421   }
 422 
 423   void block_do(BlockBegin* b) {
 424     depth = 0;
 425     // process all pinned nodes as the roots of expression trees
 426     for (Instruction* n = b; n != NULL; n = n->next()) {
 427       if (n->is_pinned()) uses_do(&n);
 428     }
 429     assert(depth == 0, "should have counted back down");
 430 
 431     // now process any unpinned nodes which recursed too deeply
 432     while (worklist->length() > 0) {
 433       Value t = worklist->pop();
 434       if (!t->is_pinned()) {
 435         // compute the use count
 436         uses_do(&t);
 437 
 438         // pin the instruction so that LIRGenerator doesn't recurse
 439         // too deeply during it's evaluation.
 440         t->pin();
 441       }
 442     }
 443     assert(depth == 0, "should have counted back down");
 444   }
 445 
 446   UseCountComputer() {
 447     worklist = new Values();
 448     depth = 0;
 449   }
 450 
 451  public:
 452   static void compute(BlockList* blocks) {
 453     UseCountComputer ucc;
 454     blocks->iterate_backward(&ucc);
 455   }
 456 };
 457 
 458 
 459 // helper macro for short definition of trace-output inside code
 460 #ifndef PRODUCT
 461   #define TRACE_LINEAR_SCAN(level, code)       \
 462     if (TraceLinearScanLevel >= level) {       \
 463       code;                                    \
 464     }
 465 #else
 466   #define TRACE_LINEAR_SCAN(level, code)
 467 #endif
 468 
 469 class ComputeLinearScanOrder : public StackObj {
 470  private:
 471   int        _max_block_id;        // the highest block_id of a block
 472   int        _num_blocks;          // total number of blocks (smaller than _max_block_id)
 473   int        _num_loops;           // total number of loops
 474   bool       _iterative_dominators;// method requires iterative computation of dominatiors
 475 
 476   BlockList* _linear_scan_order;   // the resulting list of blocks in correct order
 477 
 478   BitMap     _visited_blocks;      // used for recursive processing of blocks
 479   BitMap     _active_blocks;       // used for recursive processing of blocks
 480   BitMap     _dominator_blocks;    // temproary BitMap used for computation of dominator
 481   intArray   _forward_branches;    // number of incoming forward branches for each block
 482   BlockList  _loop_end_blocks;     // list of all loop end blocks collected during count_edges
 483   BitMap2D   _loop_map;            // two-dimensional bit set: a bit is set if a block is contained in a loop
 484   BlockList  _work_list;           // temporary list (used in mark_loops and compute_order)
 485   BlockList  _loop_headers;
 486 
 487   Compilation* _compilation;
 488 
 489   // accessors for _visited_blocks and _active_blocks
 490   void init_visited()                     { _active_blocks.clear(); _visited_blocks.clear(); }
 491   bool is_visited(BlockBegin* b) const    { return _visited_blocks.at(b->block_id()); }
 492   bool is_active(BlockBegin* b) const     { return _active_blocks.at(b->block_id()); }
 493   void set_visited(BlockBegin* b)         { assert(!is_visited(b), "already set"); _visited_blocks.set_bit(b->block_id()); }
 494   void set_active(BlockBegin* b)          { assert(!is_active(b), "already set");  _active_blocks.set_bit(b->block_id()); }
 495   void clear_active(BlockBegin* b)        { assert(is_active(b), "not already");   _active_blocks.clear_bit(b->block_id()); }
 496 
 497   // accessors for _forward_branches
 498   void inc_forward_branches(BlockBegin* b) { _forward_branches.at_put(b->block_id(), _forward_branches.at(b->block_id()) + 1); }
 499   int  dec_forward_branches(BlockBegin* b) { _forward_branches.at_put(b->block_id(), _forward_branches.at(b->block_id()) - 1); return _forward_branches.at(b->block_id()); }
 500 
 501   // accessors for _loop_map
 502   bool is_block_in_loop   (int loop_idx, BlockBegin* b) const { return _loop_map.at(loop_idx, b->block_id()); }
 503   void set_block_in_loop  (int loop_idx, BlockBegin* b)       { _loop_map.set_bit(loop_idx, b->block_id()); }
 504   void clear_block_in_loop(int loop_idx, int block_id)        { _loop_map.clear_bit(loop_idx, block_id); }
 505 
 506   // count edges between blocks
 507   void count_edges(BlockBegin* cur, BlockBegin* parent);
 508 
 509   // loop detection
 510   void mark_loops();
 511   void clear_non_natural_loops(BlockBegin* start_block);
 512   void assign_loop_depth(BlockBegin* start_block);
 513 
 514   // computation of final block order
 515   BlockBegin* common_dominator(BlockBegin* a, BlockBegin* b);
 516   void compute_dominator(BlockBegin* cur, BlockBegin* parent);
 517   int  compute_weight(BlockBegin* cur);
 518   bool ready_for_processing(BlockBegin* cur);
 519   void sort_into_work_list(BlockBegin* b);
 520   void append_block(BlockBegin* cur);
 521   void compute_order(BlockBegin* start_block);
 522 
 523   // fixup of dominators for non-natural loops
 524   bool compute_dominators_iter();
 525   void compute_dominators();
 526 
 527   // debug functions
 528   NOT_PRODUCT(void print_blocks();)
 529   DEBUG_ONLY(void verify();)
 530 
 531   Compilation* compilation() const { return _compilation; }
 532  public:
 533   ComputeLinearScanOrder(Compilation* c, BlockBegin* start_block);
 534 
 535   // accessors for final result
 536   BlockList* linear_scan_order() const    { return _linear_scan_order; }
 537   int        num_loops() const            { return _num_loops; }
 538 };
 539 
 540 
 541 ComputeLinearScanOrder::ComputeLinearScanOrder(Compilation* c, BlockBegin* start_block) :
 542   _max_block_id(BlockBegin::number_of_blocks()),
 543   _num_blocks(0),
 544   _num_loops(0),
 545   _iterative_dominators(false),
 546   _visited_blocks(_max_block_id),
 547   _active_blocks(_max_block_id),
 548   _dominator_blocks(_max_block_id),
 549   _forward_branches(_max_block_id, 0),
 550   _loop_end_blocks(8),
 551   _work_list(8),
 552   _linear_scan_order(NULL), // initialized later with correct size
 553   _loop_map(0, 0),          // initialized later with correct size
 554   _compilation(c)
 555 {
 556   TRACE_LINEAR_SCAN(2, tty->print_cr("***** computing linear-scan block order"));
 557 
 558   init_visited();
 559   count_edges(start_block, NULL);
 560 
 561   if (compilation()->is_profiling()) {
 562     ciMethod *method = compilation()->method();
 563     if (!method->is_accessor()) {
 564       ciMethodData* md = method->method_data_or_null();
 565       assert(md != NULL, "Sanity");
 566       md->set_compilation_stats(_num_loops, _num_blocks);
 567     }
 568   }
 569 
 570   if (_num_loops > 0) {
 571     mark_loops();
 572     clear_non_natural_loops(start_block);
 573     assign_loop_depth(start_block);
 574   }
 575 
 576   compute_order(start_block);
 577   compute_dominators();
 578 
 579   NOT_PRODUCT(print_blocks());
 580   DEBUG_ONLY(verify());
 581 }
 582 
 583 
 584 // Traverse the CFG:
 585 // * count total number of blocks
 586 // * count all incoming edges and backward incoming edges
 587 // * number loop header blocks
 588 // * create a list with all loop end blocks
 589 void ComputeLinearScanOrder::count_edges(BlockBegin* cur, BlockBegin* parent) {
 590   TRACE_LINEAR_SCAN(3, tty->print_cr("Enter count_edges for block B%d coming from B%d", cur->block_id(), parent != NULL ? parent->block_id() : -1));
 591   assert(cur->dominator() == NULL, "dominator already initialized");
 592 
 593   if (is_active(cur)) {
 594     TRACE_LINEAR_SCAN(3, tty->print_cr("backward branch"));
 595     assert(is_visited(cur), "block must be visisted when block is active");
 596     assert(parent != NULL, "must have parent");
 597 
 598     cur->set(BlockBegin::linear_scan_loop_header_flag);
 599     cur->set(BlockBegin::backward_branch_target_flag);
 600 
 601     parent->set(BlockBegin::linear_scan_loop_end_flag);
 602 
 603     // When a loop header is also the start of an exception handler, then the backward branch is
 604     // an exception edge. Because such edges are usually critical edges which cannot be split, the
 605     // loop must be excluded here from processing.
 606     if (cur->is_set(BlockBegin::exception_entry_flag)) {
 607       // Make sure that dominators are correct in this weird situation
 608       _iterative_dominators = true;
 609       return;
 610     }
 611     assert(parent->number_of_sux() == 1 && parent->sux_at(0) == cur,
 612            "loop end blocks must have one successor (critical edges are split)");
 613 
 614     _loop_end_blocks.append(parent);
 615     return;
 616   }
 617 
 618   // increment number of incoming forward branches
 619   inc_forward_branches(cur);
 620 
 621   if (is_visited(cur)) {
 622     TRACE_LINEAR_SCAN(3, tty->print_cr("block already visited"));
 623     return;
 624   }
 625 
 626   _num_blocks++;
 627   set_visited(cur);
 628   set_active(cur);
 629 
 630   // recursive call for all successors
 631   int i;
 632   for (i = cur->number_of_sux() - 1; i >= 0; i--) {
 633     count_edges(cur->sux_at(i), cur);
 634   }
 635   for (i = cur->number_of_exception_handlers() - 1; i >= 0; i--) {
 636     count_edges(cur->exception_handler_at(i), cur);
 637   }
 638 
 639   clear_active(cur);
 640 
 641   // Each loop has a unique number.
 642   // When multiple loops are nested, assign_loop_depth assumes that the
 643   // innermost loop has the lowest number. This is guaranteed by setting
 644   // the loop number after the recursive calls for the successors above
 645   // have returned.
 646   if (cur->is_set(BlockBegin::linear_scan_loop_header_flag)) {
 647     assert(cur->loop_index() == -1, "cannot set loop-index twice");
 648     TRACE_LINEAR_SCAN(3, tty->print_cr("Block B%d is loop header of loop %d", cur->block_id(), _num_loops));
 649 
 650     cur->set_loop_index(_num_loops);
 651     _loop_headers.append(cur);
 652     _num_loops++;
 653   }
 654 
 655   TRACE_LINEAR_SCAN(3, tty->print_cr("Finished count_edges for block B%d", cur->block_id()));
 656 }
 657 
 658 
 659 void ComputeLinearScanOrder::mark_loops() {
 660   TRACE_LINEAR_SCAN(3, tty->print_cr("----- marking loops"));
 661 
 662   _loop_map = BitMap2D(_num_loops, _max_block_id);
 663   _loop_map.clear();
 664 
 665   for (int i = _loop_end_blocks.length() - 1; i >= 0; i--) {
 666     BlockBegin* loop_end   = _loop_end_blocks.at(i);
 667     BlockBegin* loop_start = loop_end->sux_at(0);
 668     int         loop_idx   = loop_start->loop_index();
 669 
 670     TRACE_LINEAR_SCAN(3, tty->print_cr("Processing loop from B%d to B%d (loop %d):", loop_start->block_id(), loop_end->block_id(), loop_idx));
 671     assert(loop_end->is_set(BlockBegin::linear_scan_loop_end_flag), "loop end flag must be set");
 672     assert(loop_end->number_of_sux() == 1, "incorrect number of successors");
 673     assert(loop_start->is_set(BlockBegin::linear_scan_loop_header_flag), "loop header flag must be set");
 674     assert(loop_idx >= 0 && loop_idx < _num_loops, "loop index not set");
 675     assert(_work_list.is_empty(), "work list must be empty before processing");
 676 
 677     // add the end-block of the loop to the working list
 678     _work_list.push(loop_end);
 679     set_block_in_loop(loop_idx, loop_end);
 680     do {
 681       BlockBegin* cur = _work_list.pop();
 682 
 683       TRACE_LINEAR_SCAN(3, tty->print_cr("    processing B%d", cur->block_id()));
 684       assert(is_block_in_loop(loop_idx, cur), "bit in loop map must be set when block is in work list");
 685 
 686       // recursive processing of all predecessors ends when start block of loop is reached
 687       if (cur != loop_start && !cur->is_set(BlockBegin::osr_entry_flag)) {
 688         for (int j = cur->number_of_preds() - 1; j >= 0; j--) {
 689           BlockBegin* pred = cur->pred_at(j);
 690 
 691           if (!is_block_in_loop(loop_idx, pred) /*&& !pred->is_set(BlockBeginosr_entry_flag)*/) {
 692             // this predecessor has not been processed yet, so add it to work list
 693             TRACE_LINEAR_SCAN(3, tty->print_cr("    pushing B%d", pred->block_id()));
 694             _work_list.push(pred);
 695             set_block_in_loop(loop_idx, pred);
 696           }
 697         }
 698       }
 699     } while (!_work_list.is_empty());
 700   }
 701 }
 702 
 703 
 704 // check for non-natural loops (loops where the loop header does not dominate
 705 // all other loop blocks = loops with mulitple entries).
 706 // such loops are ignored
 707 void ComputeLinearScanOrder::clear_non_natural_loops(BlockBegin* start_block) {
 708   for (int i = _num_loops - 1; i >= 0; i--) {
 709     if (is_block_in_loop(i, start_block)) {
 710       // loop i contains the entry block of the method
 711       // -> this is not a natural loop, so ignore it
 712       TRACE_LINEAR_SCAN(2, tty->print_cr("Loop %d is non-natural, so it is ignored", i));
 713 
 714       BlockBegin *loop_header = _loop_headers.at(i);
 715       assert(loop_header->is_set(BlockBegin::linear_scan_loop_header_flag), "Must be loop header");
 716 
 717       for (int j = 0; j < loop_header->number_of_preds(); j++) {
 718         BlockBegin *pred = loop_header->pred_at(j);
 719         pred->clear(BlockBegin::linear_scan_loop_end_flag);
 720       }
 721 
 722       loop_header->clear(BlockBegin::linear_scan_loop_header_flag);
 723 
 724       for (int block_id = _max_block_id - 1; block_id >= 0; block_id--) {
 725         clear_block_in_loop(i, block_id);
 726       }
 727       _iterative_dominators = true;
 728     }
 729   }
 730 }
 731 
 732 void ComputeLinearScanOrder::assign_loop_depth(BlockBegin* start_block) {
 733   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing loop-depth and weight"));
 734   init_visited();
 735 
 736   assert(_work_list.is_empty(), "work list must be empty before processing");
 737   _work_list.append(start_block);
 738 
 739   do {
 740     BlockBegin* cur = _work_list.pop();
 741 
 742     if (!is_visited(cur)) {
 743       set_visited(cur);
 744       TRACE_LINEAR_SCAN(4, tty->print_cr("Computing loop depth for block B%d", cur->block_id()));
 745 
 746       // compute loop-depth and loop-index for the block
 747       assert(cur->loop_depth() == 0, "cannot set loop-depth twice");
 748       int i;
 749       int loop_depth = 0;
 750       int min_loop_idx = -1;
 751       for (i = _num_loops - 1; i >= 0; i--) {
 752         if (is_block_in_loop(i, cur)) {
 753           loop_depth++;
 754           min_loop_idx = i;
 755         }
 756       }
 757       cur->set_loop_depth(loop_depth);
 758       cur->set_loop_index(min_loop_idx);
 759 
 760       // append all unvisited successors to work list
 761       for (i = cur->number_of_sux() - 1; i >= 0; i--) {
 762         _work_list.append(cur->sux_at(i));
 763       }
 764       for (i = cur->number_of_exception_handlers() - 1; i >= 0; i--) {
 765         _work_list.append(cur->exception_handler_at(i));
 766       }
 767     }
 768   } while (!_work_list.is_empty());
 769 }
 770 
 771 
 772 BlockBegin* ComputeLinearScanOrder::common_dominator(BlockBegin* a, BlockBegin* b) {
 773   assert(a != NULL && b != NULL, "must have input blocks");
 774 
 775   _dominator_blocks.clear();
 776   while (a != NULL) {
 777     _dominator_blocks.set_bit(a->block_id());
 778     assert(a->dominator() != NULL || a == _linear_scan_order->at(0), "dominator must be initialized");
 779     a = a->dominator();
 780   }
 781   while (b != NULL && !_dominator_blocks.at(b->block_id())) {
 782     assert(b->dominator() != NULL || b == _linear_scan_order->at(0), "dominator must be initialized");
 783     b = b->dominator();
 784   }
 785 
 786   assert(b != NULL, "could not find dominator");
 787   return b;
 788 }
 789 
 790 void ComputeLinearScanOrder::compute_dominator(BlockBegin* cur, BlockBegin* parent) {
 791   if (cur->dominator() == NULL) {
 792     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: initializing dominator of B%d to B%d", cur->block_id(), parent->block_id()));
 793     cur->set_dominator(parent);
 794 
 795   } else if (!(cur->is_set(BlockBegin::linear_scan_loop_header_flag) && parent->is_set(BlockBegin::linear_scan_loop_end_flag))) {
 796     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: computing dominator of B%d: common dominator of B%d and B%d is B%d", cur->block_id(), parent->block_id(), cur->dominator()->block_id(), common_dominator(cur->dominator(), parent)->block_id()));
 797     // Does not hold for exception blocks
 798     assert(cur->number_of_preds() > 1 || cur->is_set(BlockBegin::exception_entry_flag), "");
 799     cur->set_dominator(common_dominator(cur->dominator(), parent));
 800   }
 801 
 802   // Additional edge to xhandler of all our successors
 803   // range check elimination needs that the state at the end of a
 804   // block be valid in every block it dominates so cur must dominate
 805   // the exception handlers of its successors.
 806   int num_cur_xhandler = cur->number_of_exception_handlers();
 807   for (int j = 0; j < num_cur_xhandler; j++) {
 808     BlockBegin* xhandler = cur->exception_handler_at(j);
 809     compute_dominator(xhandler, parent);
 810   }
 811 }
 812 
 813 
 814 int ComputeLinearScanOrder::compute_weight(BlockBegin* cur) {
 815   BlockBegin* single_sux = NULL;
 816   if (cur->number_of_sux() == 1) {
 817     single_sux = cur->sux_at(0);
 818   }
 819 
 820   // limit loop-depth to 15 bit (only for security reason, it will never be so big)
 821   int weight = (cur->loop_depth() & 0x7FFF) << 16;
 822 
 823   // general macro for short definition of weight flags
 824   // the first instance of INC_WEIGHT_IF has the highest priority
 825   int cur_bit = 15;
 826   #define INC_WEIGHT_IF(condition) if ((condition)) { weight |= (1 << cur_bit); } cur_bit--;
 827 
 828   // this is necessery for the (very rare) case that two successing blocks have
 829   // the same loop depth, but a different loop index (can happen for endless loops
 830   // with exception handlers)
 831   INC_WEIGHT_IF(!cur->is_set(BlockBegin::linear_scan_loop_header_flag));
 832 
 833   // loop end blocks (blocks that end with a backward branch) are added
 834   // after all other blocks of the loop.
 835   INC_WEIGHT_IF(!cur->is_set(BlockBegin::linear_scan_loop_end_flag));
 836 
 837   // critical edge split blocks are prefered because than they have a bigger
 838   // proability to be completely empty
 839   INC_WEIGHT_IF(cur->is_set(BlockBegin::critical_edge_split_flag));
 840 
 841   // exceptions should not be thrown in normal control flow, so these blocks
 842   // are added as late as possible
 843   INC_WEIGHT_IF(cur->end()->as_Throw() == NULL  && (single_sux == NULL || single_sux->end()->as_Throw()  == NULL));
 844   INC_WEIGHT_IF(cur->end()->as_Return() == NULL && (single_sux == NULL || single_sux->end()->as_Return() == NULL));
 845 
 846   // exceptions handlers are added as late as possible
 847   INC_WEIGHT_IF(!cur->is_set(BlockBegin::exception_entry_flag));
 848 
 849   // guarantee that weight is > 0
 850   weight |= 1;
 851 
 852   #undef INC_WEIGHT_IF
 853   assert(cur_bit >= 0, "too many flags");
 854   assert(weight > 0, "weight cannot become negative");
 855 
 856   return weight;
 857 }
 858 
 859 bool ComputeLinearScanOrder::ready_for_processing(BlockBegin* cur) {
 860   // Discount the edge just traveled.
 861   // When the number drops to zero, all forward branches were processed
 862   if (dec_forward_branches(cur) != 0) {
 863     return false;
 864   }
 865 
 866   assert(_linear_scan_order->index_of(cur) == -1, "block already processed (block can be ready only once)");
 867   assert(_work_list.index_of(cur) == -1, "block already in work-list (block can be ready only once)");
 868   return true;
 869 }
 870 
 871 void ComputeLinearScanOrder::sort_into_work_list(BlockBegin* cur) {
 872   assert(_work_list.index_of(cur) == -1, "block already in work list");
 873 
 874   int cur_weight = compute_weight(cur);
 875 
 876   // the linear_scan_number is used to cache the weight of a block
 877   cur->set_linear_scan_number(cur_weight);
 878 
 879 #ifndef PRODUCT
 880   if (StressLinearScan) {
 881     _work_list.insert_before(0, cur);
 882     return;
 883   }
 884 #endif
 885 
 886   _work_list.append(NULL); // provide space for new element
 887 
 888   int insert_idx = _work_list.length() - 1;
 889   while (insert_idx > 0 && _work_list.at(insert_idx - 1)->linear_scan_number() > cur_weight) {
 890     _work_list.at_put(insert_idx, _work_list.at(insert_idx - 1));
 891     insert_idx--;
 892   }
 893   _work_list.at_put(insert_idx, cur);
 894 
 895   TRACE_LINEAR_SCAN(3, tty->print_cr("Sorted B%d into worklist. new worklist:", cur->block_id()));
 896   TRACE_LINEAR_SCAN(3, for (int i = 0; i < _work_list.length(); i++) tty->print_cr("%8d B%2d  weight:%6x", i, _work_list.at(i)->block_id(), _work_list.at(i)->linear_scan_number()));
 897 
 898 #ifdef ASSERT
 899   for (int i = 0; i < _work_list.length(); i++) {
 900     assert(_work_list.at(i)->linear_scan_number() > 0, "weight not set");
 901     assert(i == 0 || _work_list.at(i - 1)->linear_scan_number() <= _work_list.at(i)->linear_scan_number(), "incorrect order in worklist");
 902   }
 903 #endif
 904 }
 905 
 906 void ComputeLinearScanOrder::append_block(BlockBegin* cur) {
 907   TRACE_LINEAR_SCAN(3, tty->print_cr("appending block B%d (weight 0x%6x) to linear-scan order", cur->block_id(), cur->linear_scan_number()));
 908   assert(_linear_scan_order->index_of(cur) == -1, "cannot add the same block twice");
 909 
 910   // currently, the linear scan order and code emit order are equal.
 911   // therefore the linear_scan_number and the weight of a block must also
 912   // be equal.
 913   cur->set_linear_scan_number(_linear_scan_order->length());
 914   _linear_scan_order->append(cur);
 915 }
 916 
 917 void ComputeLinearScanOrder::compute_order(BlockBegin* start_block) {
 918   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing final block order"));
 919 
 920   // the start block is always the first block in the linear scan order
 921   _linear_scan_order = new BlockList(_num_blocks);
 922   append_block(start_block);
 923 
 924   assert(start_block->end()->as_Base() != NULL, "start block must end with Base-instruction");
 925   BlockBegin* std_entry = ((Base*)start_block->end())->std_entry();
 926   BlockBegin* osr_entry = ((Base*)start_block->end())->osr_entry();
 927 
 928   BlockBegin* sux_of_osr_entry = NULL;
 929   if (osr_entry != NULL) {
 930     // special handling for osr entry:
 931     // ignore the edge between the osr entry and its successor for processing
 932     // the osr entry block is added manually below
 933     assert(osr_entry->number_of_sux() == 1, "osr entry must have exactly one successor");
 934     assert(osr_entry->sux_at(0)->number_of_preds() >= 2, "sucessor of osr entry must have two predecessors (otherwise it is not present in normal control flow");
 935 
 936     sux_of_osr_entry = osr_entry->sux_at(0);
 937     dec_forward_branches(sux_of_osr_entry);
 938 
 939     compute_dominator(osr_entry, start_block);
 940     _iterative_dominators = true;
 941   }
 942   compute_dominator(std_entry, start_block);
 943 
 944   // start processing with standard entry block
 945   assert(_work_list.is_empty(), "list must be empty before processing");
 946 
 947   if (ready_for_processing(std_entry)) {
 948     sort_into_work_list(std_entry);
 949   } else {
 950     assert(false, "the std_entry must be ready for processing (otherwise, the method has no start block)");
 951   }
 952 
 953   do {
 954     BlockBegin* cur = _work_list.pop();
 955 
 956     if (cur == sux_of_osr_entry) {
 957       // the osr entry block is ignored in normal processing, it is never added to the
 958       // work list. Instead, it is added as late as possible manually here.
 959       append_block(osr_entry);
 960       compute_dominator(cur, osr_entry);
 961     }
 962     append_block(cur);
 963 
 964     int i;
 965     int num_sux = cur->number_of_sux();
 966     // changed loop order to get "intuitive" order of if- and else-blocks
 967     for (i = 0; i < num_sux; i++) {
 968       BlockBegin* sux = cur->sux_at(i);
 969       compute_dominator(sux, cur);
 970       if (ready_for_processing(sux)) {
 971         sort_into_work_list(sux);
 972       }
 973     }
 974     num_sux = cur->number_of_exception_handlers();
 975     for (i = 0; i < num_sux; i++) {
 976       BlockBegin* sux = cur->exception_handler_at(i);
 977       if (ready_for_processing(sux)) {
 978         sort_into_work_list(sux);
 979       }
 980     }
 981   } while (_work_list.length() > 0);
 982 }
 983 
 984 
 985 bool ComputeLinearScanOrder::compute_dominators_iter() {
 986   bool changed = false;
 987   int num_blocks = _linear_scan_order->length();
 988 
 989   assert(_linear_scan_order->at(0)->dominator() == NULL, "must not have dominator");
 990   assert(_linear_scan_order->at(0)->number_of_preds() == 0, "must not have predecessors");
 991   for (int i = 1; i < num_blocks; i++) {
 992     BlockBegin* block = _linear_scan_order->at(i);
 993 
 994     BlockBegin* dominator = block->pred_at(0);
 995     int num_preds = block->number_of_preds();
 996 
 997     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: Processing B%d", block->block_id()));
 998 
 999     for (int j = 0; j < num_preds; j++) {
1000 
1001       BlockBegin *pred = block->pred_at(j);
1002       TRACE_LINEAR_SCAN(4, tty->print_cr("   DOM: Subrocessing B%d", pred->block_id()));
1003 
1004       if (block->is_set(BlockBegin::exception_entry_flag)) {
1005         dominator = common_dominator(dominator, pred);
1006         int num_pred_preds = pred->number_of_preds();
1007         for (int k = 0; k < num_pred_preds; k++) {
1008           dominator = common_dominator(dominator, pred->pred_at(k));
1009         }
1010       } else {
1011         dominator = common_dominator(dominator, pred);
1012       }
1013     }
1014 
1015     if (dominator != block->dominator()) {
1016       TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: updating dominator of B%d from B%d to B%d", block->block_id(), block->dominator()->block_id(), dominator->block_id()));
1017 
1018       block->set_dominator(dominator);
1019       changed = true;
1020     }
1021   }
1022   return changed;
1023 }
1024 
1025 void ComputeLinearScanOrder::compute_dominators() {
1026   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing dominators (iterative computation reqired: %d)", _iterative_dominators));
1027 
1028   // iterative computation of dominators is only required for methods with non-natural loops
1029   // and OSR-methods. For all other methods, the dominators computed when generating the
1030   // linear scan block order are correct.
1031   if (_iterative_dominators) {
1032     do {
1033       TRACE_LINEAR_SCAN(1, tty->print_cr("DOM: next iteration of fix-point calculation"));
1034     } while (compute_dominators_iter());
1035   }
1036 
1037   // check that dominators are correct
1038   assert(!compute_dominators_iter(), "fix point not reached");
1039 
1040   // Add Blocks to dominates-Array
1041   int num_blocks = _linear_scan_order->length();
1042   for (int i = 0; i < num_blocks; i++) {
1043     BlockBegin* block = _linear_scan_order->at(i);
1044 
1045     BlockBegin *dom = block->dominator();
1046     if (dom) {
1047       assert(dom->dominator_depth() != -1, "Dominator must have been visited before");
1048       dom->dominates()->append(block);
1049       block->set_dominator_depth(dom->dominator_depth() + 1);
1050     } else {
1051       block->set_dominator_depth(0);
1052     }
1053   }
1054 }
1055 
1056 
1057 #ifndef PRODUCT
1058 void ComputeLinearScanOrder::print_blocks() {
1059   if (TraceLinearScanLevel >= 2) {
1060     tty->print_cr("----- loop information:");
1061     for (int block_idx = 0; block_idx < _linear_scan_order->length(); block_idx++) {
1062       BlockBegin* cur = _linear_scan_order->at(block_idx);
1063 
1064       tty->print("%4d: B%2d: ", cur->linear_scan_number(), cur->block_id());
1065       for (int loop_idx = 0; loop_idx < _num_loops; loop_idx++) {
1066         tty->print ("%d ", is_block_in_loop(loop_idx, cur));
1067       }
1068       tty->print_cr(" -> loop_index: %2d, loop_depth: %2d", cur->loop_index(), cur->loop_depth());
1069     }
1070   }
1071 
1072   if (TraceLinearScanLevel >= 1) {
1073     tty->print_cr("----- linear-scan block order:");
1074     for (int block_idx = 0; block_idx < _linear_scan_order->length(); block_idx++) {
1075       BlockBegin* cur = _linear_scan_order->at(block_idx);
1076       tty->print("%4d: B%2d    loop: %2d  depth: %2d", cur->linear_scan_number(), cur->block_id(), cur->loop_index(), cur->loop_depth());
1077 
1078       tty->print(cur->is_set(BlockBegin::exception_entry_flag)         ? " ex" : "   ");
1079       tty->print(cur->is_set(BlockBegin::critical_edge_split_flag)     ? " ce" : "   ");
1080       tty->print(cur->is_set(BlockBegin::linear_scan_loop_header_flag) ? " lh" : "   ");
1081       tty->print(cur->is_set(BlockBegin::linear_scan_loop_end_flag)    ? " le" : "   ");
1082 
1083       if (cur->dominator() != NULL) {
1084         tty->print("    dom: B%d ", cur->dominator()->block_id());
1085       } else {
1086         tty->print("    dom: NULL ");
1087       }
1088 
1089       if (cur->number_of_preds() > 0) {
1090         tty->print("    preds: ");
1091         for (int j = 0; j < cur->number_of_preds(); j++) {
1092           BlockBegin* pred = cur->pred_at(j);
1093           tty->print("B%d ", pred->block_id());
1094         }
1095       }
1096       if (cur->number_of_sux() > 0) {
1097         tty->print("    sux: ");
1098         for (int j = 0; j < cur->number_of_sux(); j++) {
1099           BlockBegin* sux = cur->sux_at(j);
1100           tty->print("B%d ", sux->block_id());
1101         }
1102       }
1103       if (cur->number_of_exception_handlers() > 0) {
1104         tty->print("    ex: ");
1105         for (int j = 0; j < cur->number_of_exception_handlers(); j++) {
1106           BlockBegin* ex = cur->exception_handler_at(j);
1107           tty->print("B%d ", ex->block_id());
1108         }
1109       }
1110       tty->cr();
1111     }
1112   }
1113 }
1114 #endif
1115 
1116 #ifdef ASSERT
1117 void ComputeLinearScanOrder::verify() {
1118   assert(_linear_scan_order->length() == _num_blocks, "wrong number of blocks in list");
1119 
1120   if (StressLinearScan) {
1121     // blocks are scrambled when StressLinearScan is used
1122     return;
1123   }
1124 
1125   // check that all successors of a block have a higher linear-scan-number
1126   // and that all predecessors of a block have a lower linear-scan-number
1127   // (only backward branches of loops are ignored)
1128   int i;
1129   for (i = 0; i < _linear_scan_order->length(); i++) {
1130     BlockBegin* cur = _linear_scan_order->at(i);
1131 
1132     assert(cur->linear_scan_number() == i, "incorrect linear_scan_number");
1133     assert(cur->linear_scan_number() >= 0 && cur->linear_scan_number() == _linear_scan_order->index_of(cur), "incorrect linear_scan_number");
1134 
1135     int j;
1136     for (j = cur->number_of_sux() - 1; j >= 0; j--) {
1137       BlockBegin* sux = cur->sux_at(j);
1138 
1139       assert(sux->linear_scan_number() >= 0 && sux->linear_scan_number() == _linear_scan_order->index_of(sux), "incorrect linear_scan_number");
1140       if (!sux->is_set(BlockBegin::backward_branch_target_flag)) {
1141         assert(cur->linear_scan_number() < sux->linear_scan_number(), "invalid order");
1142       }
1143       if (cur->loop_depth() == sux->loop_depth()) {
1144         assert(cur->loop_index() == sux->loop_index() || sux->is_set(BlockBegin::linear_scan_loop_header_flag), "successing blocks with same loop depth must have same loop index");
1145       }
1146     }
1147 
1148     for (j = cur->number_of_preds() - 1; j >= 0; j--) {
1149       BlockBegin* pred = cur->pred_at(j);
1150 
1151       assert(pred->linear_scan_number() >= 0 && pred->linear_scan_number() == _linear_scan_order->index_of(pred), "incorrect linear_scan_number");
1152       if (!cur->is_set(BlockBegin::backward_branch_target_flag)) {
1153         assert(cur->linear_scan_number() > pred->linear_scan_number(), "invalid order");
1154       }
1155       if (cur->loop_depth() == pred->loop_depth()) {
1156         assert(cur->loop_index() == pred->loop_index() || cur->is_set(BlockBegin::linear_scan_loop_header_flag), "successing blocks with same loop depth must have same loop index");
1157       }
1158 
1159       assert(cur->dominator()->linear_scan_number() <= cur->pred_at(j)->linear_scan_number(), "dominator must be before predecessors");
1160     }
1161 
1162     // check dominator
1163     if (i == 0) {
1164       assert(cur->dominator() == NULL, "first block has no dominator");
1165     } else {
1166       assert(cur->dominator() != NULL, "all but first block must have dominator");
1167     }
1168     // Assertion does not hold for exception handlers
1169     assert(cur->number_of_preds() != 1 || cur->dominator() == cur->pred_at(0) || cur->is_set(BlockBegin::exception_entry_flag), "Single predecessor must also be dominator");
1170   }
1171 
1172   // check that all loops are continuous
1173   for (int loop_idx = 0; loop_idx < _num_loops; loop_idx++) {
1174     int block_idx = 0;
1175     assert(!is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx)), "the first block must not be present in any loop");
1176 
1177     // skip blocks before the loop
1178     while (block_idx < _num_blocks && !is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx))) {
1179       block_idx++;
1180     }
1181     // skip blocks of loop
1182     while (block_idx < _num_blocks && is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx))) {
1183       block_idx++;
1184     }
1185     // after the first non-loop block, there must not be another loop-block
1186     while (block_idx < _num_blocks) {
1187       assert(!is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx)), "loop not continuous in linear-scan order");
1188       block_idx++;
1189     }
1190   }
1191 }
1192 #endif
1193 
1194 
1195 void IR::compute_code() {
1196   assert(is_valid(), "IR must be valid");
1197 
1198   ComputeLinearScanOrder compute_order(compilation(), start());
1199   _num_loops = compute_order.num_loops();
1200   _code = compute_order.linear_scan_order();
1201 }
1202 
1203 
1204 void IR::compute_use_counts() {
1205   // make sure all values coming out of this block get evaluated.
1206   int num_blocks = _code->length();
1207   for (int i = 0; i < num_blocks; i++) {
1208     _code->at(i)->end()->state()->pin_stack_for_linear_scan();
1209   }
1210 
1211   // compute use counts
1212   UseCountComputer::compute(_code);
1213 }
1214 
1215 
1216 void IR::iterate_preorder(BlockClosure* closure) {
1217   assert(is_valid(), "IR must be valid");
1218   start()->iterate_preorder(closure);
1219 }
1220 
1221 
1222 void IR::iterate_postorder(BlockClosure* closure) {
1223   assert(is_valid(), "IR must be valid");
1224   start()->iterate_postorder(closure);
1225 }
1226 
1227 void IR::iterate_linear_scan_order(BlockClosure* closure) {
1228   linear_scan_order()->iterate_forward(closure);
1229 }
1230 
1231 
1232 #ifndef PRODUCT
1233 class BlockPrinter: public BlockClosure {
1234  private:
1235   InstructionPrinter* _ip;
1236   bool                _cfg_only;
1237   bool                _live_only;
1238 
1239  public:
1240   BlockPrinter(InstructionPrinter* ip, bool cfg_only, bool live_only = false) {
1241     _ip       = ip;
1242     _cfg_only = cfg_only;
1243     _live_only = live_only;
1244   }
1245 
1246   virtual void block_do(BlockBegin* block) {
1247     if (_cfg_only) {
1248       _ip->print_instr(block); tty->cr();
1249     } else {
1250       block->print_block(*_ip, _live_only);
1251     }
1252   }
1253 };
1254 
1255 
1256 void IR::print(BlockBegin* start, bool cfg_only, bool live_only) {
1257   ttyLocker ttyl;
1258   InstructionPrinter ip(!cfg_only);
1259   BlockPrinter bp(&ip, cfg_only, live_only);
1260   start->iterate_preorder(&bp);
1261   tty->cr();
1262 }
1263 
1264 void IR::print(bool cfg_only, bool live_only) {
1265   if (is_valid()) {
1266     print(start(), cfg_only, live_only);
1267   } else {
1268     tty->print_cr("invalid IR");
1269   }
1270 }
1271 
1272 
1273 define_array(BlockListArray, BlockList*)
1274 define_stack(BlockListList, BlockListArray)
1275 
1276 class PredecessorValidator : public BlockClosure {
1277  private:
1278   BlockListList* _predecessors;
1279   BlockList*     _blocks;
1280 
1281   static int cmp(BlockBegin** a, BlockBegin** b) {
1282     return (*a)->block_id() - (*b)->block_id();
1283   }
1284 
1285  public:
1286   PredecessorValidator(IR* hir) {
1287     ResourceMark rm;
1288     _predecessors = new BlockListList(BlockBegin::number_of_blocks(), NULL);
1289     _blocks = new BlockList();
1290 
1291     int i;
1292     hir->start()->iterate_preorder(this);
1293     if (hir->code() != NULL) {
1294       assert(hir->code()->length() == _blocks->length(), "must match");
1295       for (i = 0; i < _blocks->length(); i++) {
1296         assert(hir->code()->contains(_blocks->at(i)), "should be in both lists");
1297       }
1298     }
1299 
1300     for (i = 0; i < _blocks->length(); i++) {
1301       BlockBegin* block = _blocks->at(i);
1302       BlockList* preds = _predecessors->at(block->block_id());
1303       if (preds == NULL) {
1304         assert(block->number_of_preds() == 0, "should be the same");
1305         continue;
1306       }
1307 
1308       // clone the pred list so we can mutate it
1309       BlockList* pred_copy = new BlockList();
1310       int j;
1311       for (j = 0; j < block->number_of_preds(); j++) {
1312         pred_copy->append(block->pred_at(j));
1313       }
1314       // sort them in the same order
1315       preds->sort(cmp);
1316       pred_copy->sort(cmp);
1317       int length = MIN2(preds->length(), block->number_of_preds());
1318       for (j = 0; j < block->number_of_preds(); j++) {
1319         assert(preds->at(j) == pred_copy->at(j), "must match");
1320       }
1321 
1322       assert(preds->length() == block->number_of_preds(), "should be the same");
1323     }
1324   }
1325 
1326   virtual void block_do(BlockBegin* block) {
1327     _blocks->append(block);
1328     BlockEnd* be = block->end();
1329     int n = be->number_of_sux();
1330     int i;
1331     for (i = 0; i < n; i++) {
1332       BlockBegin* sux = be->sux_at(i);
1333       assert(!sux->is_set(BlockBegin::exception_entry_flag), "must not be xhandler");
1334 
1335       BlockList* preds = _predecessors->at_grow(sux->block_id(), NULL);
1336       if (preds == NULL) {
1337         preds = new BlockList();
1338         _predecessors->at_put(sux->block_id(), preds);
1339       }
1340       preds->append(block);
1341     }
1342 
1343     n = block->number_of_exception_handlers();
1344     for (i = 0; i < n; i++) {
1345       BlockBegin* sux = block->exception_handler_at(i);
1346       assert(sux->is_set(BlockBegin::exception_entry_flag), "must be xhandler");
1347 
1348       BlockList* preds = _predecessors->at_grow(sux->block_id(), NULL);
1349       if (preds == NULL) {
1350         preds = new BlockList();
1351         _predecessors->at_put(sux->block_id(), preds);
1352       }
1353       preds->append(block);
1354     }
1355   }
1356 };
1357 
1358 class VerifyBlockBeginField : public BlockClosure {
1359 
1360 public:
1361 
1362   virtual void block_do(BlockBegin *block) {
1363     for ( Instruction *cur = block; cur != NULL; cur = cur->next()) {
1364       assert(cur->block() == block, "Block begin is not correct");
1365     }
1366   }
1367 };
1368 
1369 void IR::verify() {
1370 #ifdef ASSERT
1371   PredecessorValidator pv(this);
1372   VerifyBlockBeginField verifier;
1373   this->iterate_postorder(&verifier);
1374 #endif
1375 }
1376 
1377 #endif // PRODUCT
1378 
1379 void SubstitutionResolver::visit(Value* v) {
1380   Value v0 = *v;
1381   if (v0) {
1382     Value vs = v0->subst();
1383     if (vs != v0) {
1384       *v = v0->subst();
1385     }
1386   }
1387 }
1388 
1389 #ifdef ASSERT
1390 class SubstitutionChecker: public ValueVisitor {
1391   void visit(Value* v) {
1392     Value v0 = *v;
1393     if (v0) {
1394       Value vs = v0->subst();
1395       assert(vs == v0, "missed substitution");
1396     }
1397   }
1398 };
1399 #endif
1400 
1401 
1402 void SubstitutionResolver::block_do(BlockBegin* block) {
1403   Instruction* last = NULL;
1404   for (Instruction* n = block; n != NULL;) {
1405     n->values_do(this);
1406     // need to remove this instruction from the instruction stream
1407     if (n->subst() != n) {
1408       assert(last != NULL, "must have last");
1409       last->set_next(n->next());
1410     } else {
1411       last = n;
1412     }
1413     n = last->next();
1414   }
1415 
1416 #ifdef ASSERT
1417   SubstitutionChecker check_substitute;
1418   if (block->state()) block->state()->values_do(&check_substitute);
1419   block->block_values_do(&check_substitute);
1420   if (block->end() && block->end()->state()) block->end()->state()->values_do(&check_substitute);
1421 #endif
1422 }