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