1 /*
   2  * Copyright (c) 1999, 2024, 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 // The functionality of this class is to insert a new block between
 312 // the 'from' and 'to' block of a critical edge.
 313 // It first collects the block pairs, and then processes them.
 314 //
 315 // Some instructions may introduce more than one edge between two blocks.
 316 // By checking if the current 'to' block sets critical_edge_split_flag
 317 // (all new blocks set this flag) we can avoid repeated processing.
 318 // This is why BlockPair contains the index rather than the original 'to' block.
 319 class CriticalEdgeFinder: public BlockClosure {
 320   BlockPairList blocks;
 321 
 322  public:
 323   CriticalEdgeFinder(IR* ir) {
 324     ir->iterate_preorder(this);
 325   }
 326 
 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, i));
 335         }
 336       }
 337     }
 338   }
 339 
 340   void split_edges() {
 341     for (int i = 0; i < blocks.length(); i++) {
 342       BlockPair* pair = blocks.at(i);
 343       BlockBegin* from = pair->from();
 344       int index = pair->index();
 345       BlockBegin* to = from->end()->sux_at(index);
 346       if (to->is_set(BlockBegin::critical_edge_split_flag)) {
 347         // inserted
 348         continue;
 349       }
 350       BlockBegin* split = from->insert_block_between(to);
 351 #ifndef PRODUCT
 352       if ((PrintIR || PrintIR1) && Verbose) {
 353         tty->print_cr("Split critical edge B%d -> B%d (new block B%d)",
 354                       from->block_id(), to->block_id(), split->block_id());
 355       }
 356 #endif
 357     }
 358   }
 359 };
 360 
 361 void IR::split_critical_edges() {
 362   CriticalEdgeFinder cef(this);
 363   cef.split_edges();
 364 }
 365 
 366 
 367 class UseCountComputer: public ValueVisitor, BlockClosure {
 368  private:
 369   void visit(Value* n) {
 370     // Local instructions and Phis for expression stack values at the
 371     // start of basic blocks are not added to the instruction list
 372     if (!(*n)->is_linked() && (*n)->can_be_linked()) {
 373       assert(false, "a node was not appended to the graph");
 374       Compilation::current()->bailout("a node was not appended to the graph");
 375     }
 376     // use n's input if not visited before
 377     if (!(*n)->is_pinned() && !(*n)->has_uses()) {
 378       // note: a) if the instruction is pinned, it will be handled by compute_use_count
 379       //       b) if the instruction has uses, it was touched before
 380       //       => in both cases we don't need to update n's values
 381       uses_do(n);
 382     }
 383     // use n
 384     (*n)->_use_count++;
 385   }
 386 
 387   Values* worklist;
 388   int depth;
 389   enum {
 390     max_recurse_depth = 20
 391   };
 392 
 393   void uses_do(Value* n) {
 394     depth++;
 395     if (depth > max_recurse_depth) {
 396       // don't allow the traversal to recurse too deeply
 397       worklist->push(*n);
 398     } else {
 399       (*n)->input_values_do(this);
 400       // special handling for some instructions
 401       if ((*n)->as_BlockEnd() != nullptr) {
 402         // note on BlockEnd:
 403         //   must 'use' the stack only if the method doesn't
 404         //   terminate, however, in those cases stack is empty
 405         (*n)->state_values_do(this);
 406       }
 407     }
 408     depth--;
 409   }
 410 
 411   void block_do(BlockBegin* b) {
 412     depth = 0;
 413     // process all pinned nodes as the roots of expression trees
 414     for (Instruction* n = b; n != nullptr; n = n->next()) {
 415       if (n->is_pinned()) uses_do(&n);
 416     }
 417     assert(depth == 0, "should have counted back down");
 418 
 419     // now process any unpinned nodes which recursed too deeply
 420     while (worklist->length() > 0) {
 421       Value t = worklist->pop();
 422       if (!t->is_pinned()) {
 423         // compute the use count
 424         uses_do(&t);
 425 
 426         // pin the instruction so that LIRGenerator doesn't recurse
 427         // too deeply during it's evaluation.
 428         t->pin();
 429       }
 430     }
 431     assert(depth == 0, "should have counted back down");
 432   }
 433 
 434   UseCountComputer() {
 435     worklist = new Values();
 436     depth = 0;
 437   }
 438 
 439  public:
 440   static void compute(BlockList* blocks) {
 441     UseCountComputer ucc;
 442     blocks->iterate_backward(&ucc);
 443   }
 444 };
 445 
 446 
 447 // helper macro for short definition of trace-output inside code
 448 #ifdef ASSERT
 449   #define TRACE_LINEAR_SCAN(level, code)       \
 450     if (TraceLinearScanLevel >= level) {       \
 451       code;                                    \
 452     }
 453 #else
 454   #define TRACE_LINEAR_SCAN(level, code)
 455 #endif
 456 
 457 class ComputeLinearScanOrder : public StackObj {
 458  private:
 459   int        _max_block_id;        // the highest block_id of a block
 460   int        _num_blocks;          // total number of blocks (smaller than _max_block_id)
 461   int        _num_loops;           // total number of loops
 462   bool       _iterative_dominators;// method requires iterative computation of dominatiors
 463 
 464   BlockList* _linear_scan_order;   // the resulting list of blocks in correct order
 465 
 466   ResourceBitMap _visited_blocks;   // used for recursive processing of blocks
 467   ResourceBitMap _active_blocks;    // used for recursive processing of blocks
 468   ResourceBitMap _dominator_blocks; // temporary BitMap used for computation of dominator
 469   intArray       _forward_branches; // number of incoming forward branches for each block
 470   BlockList      _loop_end_blocks;  // list of all loop end blocks collected during count_edges
 471   BitMap2D       _loop_map;         // two-dimensional bit set: a bit is set if a block is contained in a loop
 472   BlockList      _work_list;        // temporary list (used in mark_loops and compute_order)
 473   BlockList      _loop_headers;
 474 
 475   Compilation* _compilation;
 476 
 477   // accessors for _visited_blocks and _active_blocks
 478   void init_visited()                     { _active_blocks.clear(); _visited_blocks.clear(); }
 479   bool is_visited(BlockBegin* b) const    { return _visited_blocks.at(b->block_id()); }
 480   bool is_active(BlockBegin* b) const     { return _active_blocks.at(b->block_id()); }
 481   void set_visited(BlockBegin* b)         { assert(!is_visited(b), "already set"); _visited_blocks.set_bit(b->block_id()); }
 482   void set_active(BlockBegin* b)          { assert(!is_active(b), "already set");  _active_blocks.set_bit(b->block_id()); }
 483   void clear_active(BlockBegin* b)        { assert(is_active(b), "not already");   _active_blocks.clear_bit(b->block_id()); }
 484 
 485   // accessors for _forward_branches
 486   void inc_forward_branches(BlockBegin* b) { _forward_branches.at_put(b->block_id(), _forward_branches.at(b->block_id()) + 1); }
 487   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()); }
 488 
 489   // accessors for _loop_map
 490   bool is_block_in_loop   (int loop_idx, BlockBegin* b) const { return _loop_map.at(loop_idx, b->block_id()); }
 491   void set_block_in_loop  (int loop_idx, BlockBegin* b)       { _loop_map.set_bit(loop_idx, b->block_id()); }
 492   void clear_block_in_loop(int loop_idx, int block_id)        { _loop_map.clear_bit(loop_idx, block_id); }
 493 
 494   // count edges between blocks
 495   void count_edges(BlockBegin* cur, BlockBegin* parent);
 496 
 497   // loop detection
 498   void mark_loops();
 499   void clear_non_natural_loops(BlockBegin* start_block);
 500   void assign_loop_depth(BlockBegin* start_block);
 501 
 502   // computation of final block order
 503   BlockBegin* common_dominator(BlockBegin* a, BlockBegin* b);
 504   void compute_dominator(BlockBegin* cur, BlockBegin* parent);
 505   void compute_dominator_impl(BlockBegin* cur, BlockBegin* parent);
 506   int  compute_weight(BlockBegin* cur);
 507   bool ready_for_processing(BlockBegin* cur);
 508   void sort_into_work_list(BlockBegin* b);
 509   void append_block(BlockBegin* cur);
 510   void compute_order(BlockBegin* start_block);
 511 
 512   // fixup of dominators for non-natural loops
 513   bool compute_dominators_iter();
 514   void compute_dominators();
 515 
 516   // debug functions
 517   DEBUG_ONLY(void print_blocks();)
 518   DEBUG_ONLY(void verify();)
 519 
 520   Compilation* compilation() const { return _compilation; }
 521  public:
 522   ComputeLinearScanOrder(Compilation* c, BlockBegin* start_block);
 523 
 524   // accessors for final result
 525   BlockList* linear_scan_order() const    { return _linear_scan_order; }
 526   int        num_loops() const            { return _num_loops; }
 527 };
 528 
 529 
 530 ComputeLinearScanOrder::ComputeLinearScanOrder(Compilation* c, BlockBegin* start_block) :
 531   _max_block_id(BlockBegin::number_of_blocks()),
 532   _num_blocks(0),
 533   _num_loops(0),
 534   _iterative_dominators(false),
 535   _linear_scan_order(nullptr), // initialized later with correct size
 536   _visited_blocks(_max_block_id),
 537   _active_blocks(_max_block_id),
 538   _dominator_blocks(_max_block_id),
 539   _forward_branches(_max_block_id, _max_block_id, 0),
 540   _loop_end_blocks(8),
 541   _loop_map(0),             // initialized later with correct size
 542   _work_list(8),
 543   _compilation(c)
 544 {
 545   TRACE_LINEAR_SCAN(2, tty->print_cr("***** computing linear-scan block order"));
 546 
 547   count_edges(start_block, nullptr);
 548 
 549   if (compilation()->is_profiling()) {
 550     ciMethod *method = compilation()->method();
 551     if (!method->is_accessor()) {
 552       ciMethodData* md = method->method_data_or_null();
 553       assert(md != nullptr, "Sanity");
 554       md->set_compilation_stats(_num_loops, _num_blocks);
 555     }
 556   }
 557 
 558   if (_num_loops > 0) {
 559     mark_loops();
 560     clear_non_natural_loops(start_block);
 561     assign_loop_depth(start_block);
 562   }
 563 
 564   compute_order(start_block);
 565   compute_dominators();
 566 
 567   DEBUG_ONLY(print_blocks());
 568   DEBUG_ONLY(verify());
 569 }
 570 
 571 
 572 // Traverse the CFG:
 573 // * count total number of blocks
 574 // * count all incoming edges and backward incoming edges
 575 // * number loop header blocks
 576 // * create a list with all loop end blocks
 577 void ComputeLinearScanOrder::count_edges(BlockBegin* cur, BlockBegin* parent) {
 578   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));
 579   assert(cur->dominator() == nullptr, "dominator already initialized");
 580 
 581   if (is_active(cur)) {
 582     TRACE_LINEAR_SCAN(3, tty->print_cr("backward branch"));
 583     assert(is_visited(cur), "block must be visisted when block is active");
 584     assert(parent != nullptr, "must have parent");
 585 
 586     cur->set(BlockBegin::backward_branch_target_flag);
 587 
 588     // When a loop header is also the start of an exception handler, then the backward branch is
 589     // an exception edge. Because such edges are usually critical edges which cannot be split, the
 590     // loop must be excluded here from processing.
 591     if (cur->is_set(BlockBegin::exception_entry_flag)) {
 592       // Make sure that dominators are correct in this weird situation
 593       _iterative_dominators = true;
 594       return;
 595     }
 596 
 597     cur->set(BlockBegin::linear_scan_loop_header_flag);
 598     parent->set(BlockBegin::linear_scan_loop_end_flag);
 599 
 600     assert(parent->number_of_sux() == 1 && parent->sux_at(0) == cur,
 601            "loop end blocks must have one successor (critical edges are split)");
 602 
 603     _loop_end_blocks.append(parent);
 604     return;
 605   }
 606 
 607   // increment number of incoming forward branches
 608   inc_forward_branches(cur);
 609 
 610   if (is_visited(cur)) {
 611     TRACE_LINEAR_SCAN(3, tty->print_cr("block already visited"));
 612     return;
 613   }
 614 
 615   _num_blocks++;
 616   set_visited(cur);
 617   set_active(cur);
 618 
 619   // recursive call for all successors
 620   int i;
 621   for (i = cur->number_of_sux() - 1; i >= 0; i--) {
 622     count_edges(cur->sux_at(i), cur);
 623   }
 624   for (i = cur->number_of_exception_handlers() - 1; i >= 0; i--) {
 625     count_edges(cur->exception_handler_at(i), cur);
 626   }
 627 
 628   clear_active(cur);
 629 
 630   // Each loop has a unique number.
 631   // When multiple loops are nested, assign_loop_depth assumes that the
 632   // innermost loop has the lowest number. This is guaranteed by setting
 633   // the loop number after the recursive calls for the successors above
 634   // have returned.
 635   if (cur->is_set(BlockBegin::linear_scan_loop_header_flag)) {
 636     assert(cur->loop_index() == -1, "cannot set loop-index twice");
 637     TRACE_LINEAR_SCAN(3, tty->print_cr("Block B%d is loop header of loop %d", cur->block_id(), _num_loops));
 638 
 639     cur->set_loop_index(_num_loops);
 640     _loop_headers.append(cur);
 641     _num_loops++;
 642   }
 643 
 644   TRACE_LINEAR_SCAN(3, tty->print_cr("Finished count_edges for block B%d", cur->block_id()));
 645 }
 646 
 647 
 648 void ComputeLinearScanOrder::mark_loops() {
 649   TRACE_LINEAR_SCAN(3, tty->print_cr("----- marking loops"));
 650 
 651   _loop_map = BitMap2D(_num_loops, _max_block_id);
 652 
 653   for (int i = _loop_end_blocks.length() - 1; i >= 0; i--) {
 654     BlockBegin* loop_end   = _loop_end_blocks.at(i);
 655     BlockBegin* loop_start = loop_end->sux_at(0);
 656     int         loop_idx   = loop_start->loop_index();
 657 
 658     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));
 659     assert(loop_end->is_set(BlockBegin::linear_scan_loop_end_flag), "loop end flag must be set");
 660     assert(loop_end->number_of_sux() == 1, "incorrect number of successors");
 661     assert(loop_start->is_set(BlockBegin::linear_scan_loop_header_flag), "loop header flag must be set");
 662     assert(loop_idx >= 0 && loop_idx < _num_loops, "loop index not set");
 663     assert(_work_list.is_empty(), "work list must be empty before processing");
 664 
 665     // add the end-block of the loop to the working list
 666     _work_list.push(loop_end);
 667     set_block_in_loop(loop_idx, loop_end);
 668     do {
 669       BlockBegin* cur = _work_list.pop();
 670 
 671       TRACE_LINEAR_SCAN(3, tty->print_cr("    processing B%d", cur->block_id()));
 672       assert(is_block_in_loop(loop_idx, cur), "bit in loop map must be set when block is in work list");
 673 
 674       // recursive processing of all predecessors ends when start block of loop is reached
 675       if (cur != loop_start && !cur->is_set(BlockBegin::osr_entry_flag)) {
 676         for (int j = cur->number_of_preds() - 1; j >= 0; j--) {
 677           BlockBegin* pred = cur->pred_at(j);
 678 
 679           if (!is_block_in_loop(loop_idx, pred) /*&& !pred->is_set(BlockBeginosr_entry_flag)*/) {
 680             // this predecessor has not been processed yet, so add it to work list
 681             TRACE_LINEAR_SCAN(3, tty->print_cr("    pushing B%d", pred->block_id()));
 682             _work_list.push(pred);
 683             set_block_in_loop(loop_idx, pred);
 684           }
 685         }
 686       }
 687     } while (!_work_list.is_empty());
 688   }
 689 }
 690 
 691 
 692 // check for non-natural loops (loops where the loop header does not dominate
 693 // all other loop blocks = loops with multiple entries).
 694 // such loops are ignored
 695 void ComputeLinearScanOrder::clear_non_natural_loops(BlockBegin* start_block) {
 696   for (int i = _num_loops - 1; i >= 0; i--) {
 697     if (is_block_in_loop(i, start_block)) {
 698       // loop i contains the entry block of the method
 699       // -> this is not a natural loop, so ignore it
 700       TRACE_LINEAR_SCAN(2, tty->print_cr("Loop %d is non-natural, so it is ignored", i));
 701 
 702       BlockBegin *loop_header = _loop_headers.at(i);
 703       assert(loop_header->is_set(BlockBegin::linear_scan_loop_header_flag), "Must be loop header");
 704 
 705       for (int j = 0; j < loop_header->number_of_preds(); j++) {
 706         BlockBegin *pred = loop_header->pred_at(j);
 707         pred->clear(BlockBegin::linear_scan_loop_end_flag);
 708       }
 709 
 710       loop_header->clear(BlockBegin::linear_scan_loop_header_flag);
 711 
 712       for (int block_id = _max_block_id - 1; block_id >= 0; block_id--) {
 713         clear_block_in_loop(i, block_id);
 714       }
 715       _iterative_dominators = true;
 716     }
 717   }
 718 }
 719 
 720 void ComputeLinearScanOrder::assign_loop_depth(BlockBegin* start_block) {
 721   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing loop-depth and weight"));
 722   init_visited();
 723 
 724   assert(_work_list.is_empty(), "work list must be empty before processing");
 725   _work_list.append(start_block);
 726 
 727   do {
 728     BlockBegin* cur = _work_list.pop();
 729 
 730     if (!is_visited(cur)) {
 731       set_visited(cur);
 732       TRACE_LINEAR_SCAN(4, tty->print_cr("Computing loop depth for block B%d", cur->block_id()));
 733 
 734       // compute loop-depth and loop-index for the block
 735       assert(cur->loop_depth() == 0, "cannot set loop-depth twice");
 736       int i;
 737       int loop_depth = 0;
 738       int min_loop_idx = -1;
 739       for (i = _num_loops - 1; i >= 0; i--) {
 740         if (is_block_in_loop(i, cur)) {
 741           loop_depth++;
 742           min_loop_idx = i;
 743         }
 744       }
 745       cur->set_loop_depth(loop_depth);
 746       cur->set_loop_index(min_loop_idx);
 747 
 748       // append all unvisited successors to work list
 749       for (i = cur->number_of_sux() - 1; i >= 0; i--) {
 750         _work_list.append(cur->sux_at(i));
 751       }
 752       for (i = cur->number_of_exception_handlers() - 1; i >= 0; i--) {
 753         _work_list.append(cur->exception_handler_at(i));
 754       }
 755     }
 756   } while (!_work_list.is_empty());
 757 }
 758 
 759 
 760 BlockBegin* ComputeLinearScanOrder::common_dominator(BlockBegin* a, BlockBegin* b) {
 761   assert(a != nullptr && b != nullptr, "must have input blocks");
 762 
 763   _dominator_blocks.clear();
 764   while (a != nullptr) {
 765     _dominator_blocks.set_bit(a->block_id());
 766     assert(a->dominator() != nullptr || a == _linear_scan_order->at(0), "dominator must be initialized");
 767     a = a->dominator();
 768   }
 769   while (b != nullptr && !_dominator_blocks.at(b->block_id())) {
 770     assert(b->dominator() != nullptr || b == _linear_scan_order->at(0), "dominator must be initialized");
 771     b = b->dominator();
 772   }
 773 
 774   assert(b != nullptr, "could not find dominator");
 775   return b;
 776 }
 777 
 778 void ComputeLinearScanOrder::compute_dominator(BlockBegin* cur, BlockBegin* parent) {
 779   init_visited();
 780   compute_dominator_impl(cur, parent);
 781 }
 782 
 783 void ComputeLinearScanOrder::compute_dominator_impl(BlockBegin* cur, BlockBegin* parent) {
 784   // Mark as visited to avoid recursive calls with same parent
 785   set_visited(cur);
 786 
 787   if (cur->dominator() == nullptr) {
 788     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: initializing dominator of B%d to B%d", cur->block_id(), parent->block_id()));
 789     cur->set_dominator(parent);
 790 
 791   } else if (!(cur->is_set(BlockBegin::linear_scan_loop_header_flag) && parent->is_set(BlockBegin::linear_scan_loop_end_flag))) {
 792     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()));
 793     // Does not hold for exception blocks
 794     assert(cur->number_of_preds() > 1 || cur->is_set(BlockBegin::exception_entry_flag), "");
 795     cur->set_dominator(common_dominator(cur->dominator(), parent));
 796   }
 797 
 798   // Additional edge to xhandler of all our successors
 799   // range check elimination needs that the state at the end of a
 800   // block be valid in every block it dominates so cur must dominate
 801   // the exception handlers of its successors.
 802   int num_cur_xhandler = cur->number_of_exception_handlers();
 803   for (int j = 0; j < num_cur_xhandler; j++) {
 804     BlockBegin* xhandler = cur->exception_handler_at(j);
 805     if (!is_visited(xhandler)) {
 806       compute_dominator_impl(xhandler, parent);
 807     }
 808   }
 809 }
 810 
 811 
 812 int ComputeLinearScanOrder::compute_weight(BlockBegin* cur) {
 813   BlockBegin* single_sux = nullptr;
 814   if (cur->number_of_sux() == 1) {
 815     single_sux = cur->sux_at(0);
 816   }
 817 
 818   // limit loop-depth to 15 bit (only for security reason, it will never be so big)
 819   int weight = (cur->loop_depth() & 0x7FFF) << 16;
 820 
 821   // general macro for short definition of weight flags
 822   // the first instance of INC_WEIGHT_IF has the highest priority
 823   int cur_bit = 15;
 824   #define INC_WEIGHT_IF(condition) if ((condition)) { weight |= (1 << cur_bit); } cur_bit--;
 825 
 826   // this is necessary for the (very rare) case that two successive blocks have
 827   // the same loop depth, but a different loop index (can happen for endless loops
 828   // with exception handlers)
 829   INC_WEIGHT_IF(!cur->is_set(BlockBegin::linear_scan_loop_header_flag));
 830 
 831   // loop end blocks (blocks that end with a backward branch) are added
 832   // after all other blocks of the loop.
 833   INC_WEIGHT_IF(!cur->is_set(BlockBegin::linear_scan_loop_end_flag));
 834 
 835   // critical edge split blocks are preferred because than they have a bigger
 836   // proability to be completely empty
 837   INC_WEIGHT_IF(cur->is_set(BlockBegin::critical_edge_split_flag));
 838 
 839   // exceptions should not be thrown in normal control flow, so these blocks
 840   // are added as late as possible
 841   INC_WEIGHT_IF(cur->end()->as_Throw() == nullptr  && (single_sux == nullptr || single_sux->end()->as_Throw()  == nullptr));
 842   INC_WEIGHT_IF(cur->end()->as_Return() == nullptr && (single_sux == nullptr || single_sux->end()->as_Return() == nullptr));
 843 
 844   // exceptions handlers are added as late as possible
 845   INC_WEIGHT_IF(!cur->is_set(BlockBegin::exception_entry_flag));
 846 
 847   // guarantee that weight is > 0
 848   weight |= 1;
 849 
 850   #undef INC_WEIGHT_IF
 851   assert(cur_bit >= 0, "too many flags");
 852   assert(weight > 0, "weight cannot become negative");
 853 
 854   return weight;
 855 }
 856 
 857 bool ComputeLinearScanOrder::ready_for_processing(BlockBegin* cur) {
 858   // Discount the edge just traveled.
 859   // When the number drops to zero, all forward branches were processed
 860   if (dec_forward_branches(cur) != 0) {
 861     return false;
 862   }
 863 
 864   assert(_linear_scan_order->find(cur) == -1, "block already processed (block can be ready only once)");
 865   assert(_work_list.find(cur) == -1, "block already in work-list (block can be ready only once)");
 866   return true;
 867 }
 868 
 869 void ComputeLinearScanOrder::sort_into_work_list(BlockBegin* cur) {
 870   assert(_work_list.find(cur) == -1, "block already in work list");
 871 
 872   int cur_weight = compute_weight(cur);
 873 
 874   // the linear_scan_number is used to cache the weight of a block
 875   cur->set_linear_scan_number(cur_weight);
 876 
 877 #ifndef PRODUCT
 878   if (StressLinearScan) {
 879     _work_list.insert_before(0, cur);
 880     return;
 881   }
 882 #endif
 883 
 884   _work_list.append(nullptr); // provide space for new element
 885 
 886   int insert_idx = _work_list.length() - 1;
 887   while (insert_idx > 0 && _work_list.at(insert_idx - 1)->linear_scan_number() > cur_weight) {
 888     _work_list.at_put(insert_idx, _work_list.at(insert_idx - 1));
 889     insert_idx--;
 890   }
 891   _work_list.at_put(insert_idx, cur);
 892 
 893   TRACE_LINEAR_SCAN(3, tty->print_cr("Sorted B%d into worklist. new worklist:", cur->block_id()));
 894   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()));
 895 
 896 #ifdef ASSERT
 897   for (int i = 0; i < _work_list.length(); i++) {
 898     assert(_work_list.at(i)->linear_scan_number() > 0, "weight not set");
 899     assert(i == 0 || _work_list.at(i - 1)->linear_scan_number() <= _work_list.at(i)->linear_scan_number(), "incorrect order in worklist");
 900   }
 901 #endif
 902 }
 903 
 904 void ComputeLinearScanOrder::append_block(BlockBegin* cur) {
 905   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()));
 906   assert(_linear_scan_order->find(cur) == -1, "cannot add the same block twice");
 907 
 908   // currently, the linear scan order and code emit order are equal.
 909   // therefore the linear_scan_number and the weight of a block must also
 910   // be equal.
 911   cur->set_linear_scan_number(_linear_scan_order->length());
 912   _linear_scan_order->append(cur);
 913 }
 914 
 915 void ComputeLinearScanOrder::compute_order(BlockBegin* start_block) {
 916   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing final block order"));
 917 
 918   // the start block is always the first block in the linear scan order
 919   _linear_scan_order = new BlockList(_num_blocks);
 920   append_block(start_block);
 921 
 922   assert(start_block->end()->as_Base() != nullptr, "start block must end with Base-instruction");
 923   BlockBegin* std_entry = ((Base*)start_block->end())->std_entry();
 924   BlockBegin* osr_entry = ((Base*)start_block->end())->osr_entry();
 925 
 926   BlockBegin* sux_of_osr_entry = nullptr;
 927   if (osr_entry != nullptr) {
 928     // special handling for osr entry:
 929     // ignore the edge between the osr entry and its successor for processing
 930     // the osr entry block is added manually below
 931     assert(osr_entry->number_of_sux() == 1, "osr entry must have exactly one successor");
 932     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");
 933 
 934     sux_of_osr_entry = osr_entry->sux_at(0);
 935     dec_forward_branches(sux_of_osr_entry);
 936 
 937     compute_dominator(osr_entry, start_block);
 938     _iterative_dominators = true;
 939   }
 940   compute_dominator(std_entry, start_block);
 941 
 942   // start processing with standard entry block
 943   assert(_work_list.is_empty(), "list must be empty before processing");
 944 
 945   if (ready_for_processing(std_entry)) {
 946     sort_into_work_list(std_entry);
 947   } else {
 948     assert(false, "the std_entry must be ready for processing (otherwise, the method has no start block)");
 949   }
 950 
 951   do {
 952     BlockBegin* cur = _work_list.pop();
 953 
 954     if (cur == sux_of_osr_entry) {
 955       // the osr entry block is ignored in normal processing, it is never added to the
 956       // work list. Instead, it is added as late as possible manually here.
 957       append_block(osr_entry);
 958       compute_dominator(cur, osr_entry);
 959     }
 960     append_block(cur);
 961 
 962     int i;
 963     int num_sux = cur->number_of_sux();
 964     // changed loop order to get "intuitive" order of if- and else-blocks
 965     for (i = 0; i < num_sux; i++) {
 966       BlockBegin* sux = cur->sux_at(i);
 967       compute_dominator(sux, cur);
 968       if (ready_for_processing(sux)) {
 969         sort_into_work_list(sux);
 970       }
 971     }
 972     num_sux = cur->number_of_exception_handlers();
 973     for (i = 0; i < num_sux; i++) {
 974       BlockBegin* sux = cur->exception_handler_at(i);
 975       if (ready_for_processing(sux)) {
 976         sort_into_work_list(sux);
 977       }
 978     }
 979   } while (_work_list.length() > 0);
 980 }
 981 
 982 
 983 bool ComputeLinearScanOrder::compute_dominators_iter() {
 984   bool changed = false;
 985   int num_blocks = _linear_scan_order->length();
 986 
 987   assert(_linear_scan_order->at(0)->dominator() == nullptr, "must not have dominator");
 988   assert(_linear_scan_order->at(0)->number_of_preds() == 0, "must not have predecessors");
 989   for (int i = 1; i < num_blocks; i++) {
 990     BlockBegin* block = _linear_scan_order->at(i);
 991 
 992     BlockBegin* dominator = block->pred_at(0);
 993     int num_preds = block->number_of_preds();
 994 
 995     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: Processing B%d", block->block_id()));
 996 
 997     for (int j = 0; j < num_preds; j++) {
 998 
 999       BlockBegin *pred = block->pred_at(j);
1000       TRACE_LINEAR_SCAN(4, tty->print_cr("   DOM: Subrocessing B%d", pred->block_id()));
1001 
1002       if (block->is_set(BlockBegin::exception_entry_flag)) {
1003         dominator = common_dominator(dominator, pred);
1004         int num_pred_preds = pred->number_of_preds();
1005         for (int k = 0; k < num_pred_preds; k++) {
1006           dominator = common_dominator(dominator, pred->pred_at(k));
1007         }
1008       } else {
1009         dominator = common_dominator(dominator, pred);
1010       }
1011     }
1012 
1013     if (dominator != block->dominator()) {
1014       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()));
1015 
1016       block->set_dominator(dominator);
1017       changed = true;
1018     }
1019   }
1020   return changed;
1021 }
1022 
1023 void ComputeLinearScanOrder::compute_dominators() {
1024   TRACE_LINEAR_SCAN(3, tty->print_cr("----- computing dominators (iterative computation reqired: %d)", _iterative_dominators));
1025 
1026   // iterative computation of dominators is only required for methods with non-natural loops
1027   // and OSR-methods. For all other methods, the dominators computed when generating the
1028   // linear scan block order are correct.
1029   if (_iterative_dominators) {
1030     do {
1031       TRACE_LINEAR_SCAN(1, tty->print_cr("DOM: next iteration of fix-point calculation"));
1032     } while (compute_dominators_iter());
1033   }
1034 
1035   // check that dominators are correct
1036   assert(!compute_dominators_iter(), "fix point not reached");
1037 
1038   // Add Blocks to dominates-Array
1039   int num_blocks = _linear_scan_order->length();
1040   for (int i = 0; i < num_blocks; i++) {
1041     BlockBegin* block = _linear_scan_order->at(i);
1042 
1043     BlockBegin *dom = block->dominator();
1044     if (dom) {
1045       assert(dom->dominator_depth() != -1, "Dominator must have been visited before");
1046       dom->dominates()->append(block);
1047       block->set_dominator_depth(dom->dominator_depth() + 1);
1048     } else {
1049       block->set_dominator_depth(0);
1050     }
1051   }
1052 }
1053 
1054 
1055 #ifdef ASSERT
1056 void ComputeLinearScanOrder::print_blocks() {
1057   if (TraceLinearScanLevel >= 2) {
1058     tty->print_cr("----- loop information:");
1059     for (int block_idx = 0; block_idx < _linear_scan_order->length(); block_idx++) {
1060       BlockBegin* cur = _linear_scan_order->at(block_idx);
1061 
1062       tty->print("%4d: B%2d: ", cur->linear_scan_number(), cur->block_id());
1063       for (int loop_idx = 0; loop_idx < _num_loops; loop_idx++) {
1064         tty->print ("%d ", is_block_in_loop(loop_idx, cur));
1065       }
1066       tty->print_cr(" -> loop_index: %2d, loop_depth: %2d", cur->loop_index(), cur->loop_depth());
1067     }
1068   }
1069 
1070   if (TraceLinearScanLevel >= 1) {
1071     tty->print_cr("----- linear-scan block order:");
1072     for (int block_idx = 0; block_idx < _linear_scan_order->length(); block_idx++) {
1073       BlockBegin* cur = _linear_scan_order->at(block_idx);
1074       tty->print("%4d: B%2d    loop: %2d  depth: %2d", cur->linear_scan_number(), cur->block_id(), cur->loop_index(), cur->loop_depth());
1075 
1076       tty->print(cur->is_set(BlockBegin::exception_entry_flag)         ? " ex" : "   ");
1077       tty->print(cur->is_set(BlockBegin::critical_edge_split_flag)     ? " ce" : "   ");
1078       tty->print(cur->is_set(BlockBegin::linear_scan_loop_header_flag) ? " lh" : "   ");
1079       tty->print(cur->is_set(BlockBegin::linear_scan_loop_end_flag)    ? " le" : "   ");
1080 
1081       if (cur->dominator() != nullptr) {
1082         tty->print("    dom: B%d ", cur->dominator()->block_id());
1083       } else {
1084         tty->print("    dom: null ");
1085       }
1086 
1087       if (cur->number_of_preds() > 0) {
1088         tty->print("    preds: ");
1089         for (int j = 0; j < cur->number_of_preds(); j++) {
1090           BlockBegin* pred = cur->pred_at(j);
1091           tty->print("B%d ", pred->block_id());
1092         }
1093       }
1094       if (cur->number_of_sux() > 0) {
1095         tty->print("    sux: ");
1096         for (int j = 0; j < cur->number_of_sux(); j++) {
1097           BlockBegin* sux = cur->sux_at(j);
1098           tty->print("B%d ", sux->block_id());
1099         }
1100       }
1101       if (cur->number_of_exception_handlers() > 0) {
1102         tty->print("    ex: ");
1103         for (int j = 0; j < cur->number_of_exception_handlers(); j++) {
1104           BlockBegin* ex = cur->exception_handler_at(j);
1105           tty->print("B%d ", ex->block_id());
1106         }
1107       }
1108       tty->cr();
1109     }
1110   }
1111 }
1112 
1113 void ComputeLinearScanOrder::verify() {
1114   assert(_linear_scan_order->length() == _num_blocks, "wrong number of blocks in list");
1115 
1116   if (StressLinearScan) {
1117     // blocks are scrambled when StressLinearScan is used
1118     return;
1119   }
1120 
1121   // check that all successors of a block have a higher linear-scan-number
1122   // and that all predecessors of a block have a lower linear-scan-number
1123   // (only backward branches of loops are ignored)
1124   int i;
1125   for (i = 0; i < _linear_scan_order->length(); i++) {
1126     BlockBegin* cur = _linear_scan_order->at(i);
1127 
1128     assert(cur->linear_scan_number() == i, "incorrect linear_scan_number");
1129     assert(cur->linear_scan_number() >= 0 && cur->linear_scan_number() == _linear_scan_order->find(cur), "incorrect linear_scan_number");
1130 
1131     int j;
1132     for (j = cur->number_of_sux() - 1; j >= 0; j--) {
1133       BlockBegin* sux = cur->sux_at(j);
1134 
1135       assert(sux->linear_scan_number() >= 0 && sux->linear_scan_number() == _linear_scan_order->find(sux), "incorrect linear_scan_number");
1136       if (!sux->is_set(BlockBegin::backward_branch_target_flag)) {
1137         assert(cur->linear_scan_number() < sux->linear_scan_number(), "invalid order");
1138       }
1139       if (cur->loop_depth() == sux->loop_depth()) {
1140         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");
1141       }
1142     }
1143 
1144     for (j = cur->number_of_preds() - 1; j >= 0; j--) {
1145       BlockBegin* pred = cur->pred_at(j);
1146 
1147       assert(pred->linear_scan_number() >= 0 && pred->linear_scan_number() == _linear_scan_order->find(pred), "incorrect linear_scan_number");
1148       if (!cur->is_set(BlockBegin::backward_branch_target_flag)) {
1149         assert(cur->linear_scan_number() > pred->linear_scan_number(), "invalid order");
1150       }
1151       if (cur->loop_depth() == pred->loop_depth()) {
1152         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");
1153       }
1154 
1155       assert(cur->dominator()->linear_scan_number() <= cur->pred_at(j)->linear_scan_number(), "dominator must be before predecessors");
1156     }
1157 
1158     // check dominator
1159     if (i == 0) {
1160       assert(cur->dominator() == nullptr, "first block has no dominator");
1161     } else {
1162       assert(cur->dominator() != nullptr, "all but first block must have dominator");
1163     }
1164     // Assertion does not hold for exception handlers
1165     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");
1166   }
1167 
1168   // check that all loops are continuous
1169   for (int loop_idx = 0; loop_idx < _num_loops; loop_idx++) {
1170     int block_idx = 0;
1171     assert(!is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx)), "the first block must not be present in any loop");
1172 
1173     // skip blocks before the loop
1174     while (block_idx < _num_blocks && !is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx))) {
1175       block_idx++;
1176     }
1177     // skip blocks of loop
1178     while (block_idx < _num_blocks && is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx))) {
1179       block_idx++;
1180     }
1181     // after the first non-loop block, there must not be another loop-block
1182     while (block_idx < _num_blocks) {
1183       assert(!is_block_in_loop(loop_idx, _linear_scan_order->at(block_idx)), "loop not continuous in linear-scan order");
1184       block_idx++;
1185     }
1186   }
1187 }
1188 #endif // ASSERT
1189 
1190 
1191 void IR::compute_code() {
1192   assert(is_valid(), "IR must be valid");
1193 
1194   ComputeLinearScanOrder compute_order(compilation(), start());
1195   _num_loops = compute_order.num_loops();
1196   _code = compute_order.linear_scan_order();
1197 }
1198 
1199 
1200 void IR::compute_use_counts() {
1201   // make sure all values coming out of this block get evaluated.
1202   int num_blocks = _code->length();
1203   for (int i = 0; i < num_blocks; i++) {
1204     _code->at(i)->end()->state()->pin_stack_for_linear_scan();
1205   }
1206 
1207   // compute use counts
1208   UseCountComputer::compute(_code);
1209 }
1210 
1211 
1212 void IR::iterate_preorder(BlockClosure* closure) {
1213   assert(is_valid(), "IR must be valid");
1214   start()->iterate_preorder(closure);
1215 }
1216 
1217 
1218 void IR::iterate_postorder(BlockClosure* closure) {
1219   assert(is_valid(), "IR must be valid");
1220   start()->iterate_postorder(closure);
1221 }
1222 
1223 void IR::iterate_linear_scan_order(BlockClosure* closure) {
1224   linear_scan_order()->iterate_forward(closure);
1225 }
1226 
1227 
1228 #ifndef PRODUCT
1229 class BlockPrinter: public BlockClosure {
1230  private:
1231   InstructionPrinter* _ip;
1232   bool                _cfg_only;
1233   bool                _live_only;
1234 
1235  public:
1236   BlockPrinter(InstructionPrinter* ip, bool cfg_only, bool live_only = false) {
1237     _ip       = ip;
1238     _cfg_only = cfg_only;
1239     _live_only = live_only;
1240   }
1241 
1242   virtual void block_do(BlockBegin* block) {
1243     if (_cfg_only) {
1244       _ip->print_instr(block); tty->cr();
1245     } else {
1246       block->print_block(*_ip, _live_only);
1247     }
1248   }
1249 };
1250 
1251 
1252 void IR::print(BlockBegin* start, bool cfg_only, bool live_only) {
1253   ttyLocker ttyl;
1254   InstructionPrinter ip(!cfg_only);
1255   BlockPrinter bp(&ip, cfg_only, live_only);
1256   start->iterate_preorder(&bp);
1257   tty->cr();
1258 }
1259 
1260 void IR::print(bool cfg_only, bool live_only) {
1261   if (is_valid()) {
1262     print(start(), cfg_only, live_only);
1263   } else {
1264     tty->print_cr("invalid IR");
1265   }
1266 }
1267 #endif // PRODUCT
1268 
1269 #ifdef ASSERT
1270 class EndNotNullValidator : public BlockClosure {
1271  public:
1272   virtual void block_do(BlockBegin* block) {
1273     assert(block->end() != nullptr, "Expect block end to exist.");
1274   }
1275 };
1276 
1277 class XentryFlagValidator : public BlockClosure {
1278  public:
1279   virtual void block_do(BlockBegin* block) {
1280     for (int i = 0; i < block->end()->number_of_sux(); i++) {
1281       assert(!block->end()->sux_at(i)->is_set(BlockBegin::exception_entry_flag), "must not be xhandler");
1282     }
1283     for (int i = 0; i < block->number_of_exception_handlers(); i++) {
1284       assert(block->exception_handler_at(i)->is_set(BlockBegin::exception_entry_flag), "must be xhandler");
1285     }
1286   }
1287 };
1288 
1289 typedef GrowableArray<BlockList*> BlockListList;
1290 
1291 // Validation goals:
1292 // - code() length == blocks length
1293 // - code() contents == blocks content
1294 // - Each block's computed predecessors match sux lists (length)
1295 // - Each block's computed predecessors match sux lists (set content)
1296 class PredecessorAndCodeValidator : public BlockClosure {
1297  private:
1298   BlockListList* _predecessors; // Each index i will hold predecessors of block with id i
1299   BlockList*     _blocks;
1300 
1301   static int cmp(BlockBegin** a, BlockBegin** b) {
1302     return (*a)->block_id() - (*b)->block_id();
1303   }
1304 
1305  public:
1306   PredecessorAndCodeValidator(IR* hir) {
1307     ResourceMark rm;
1308     _predecessors = new BlockListList(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), nullptr);
1309     _blocks = new BlockList(BlockBegin::number_of_blocks());
1310 
1311     hir->start()->iterate_preorder(this);
1312     if (hir->code() != nullptr) {
1313       assert(hir->code()->length() == _blocks->length(), "must match");
1314       for (int i = 0; i < _blocks->length(); i++) {
1315         assert(hir->code()->contains(_blocks->at(i)), "should be in both lists");
1316       }
1317     }
1318 
1319     for (int i = 0; i < _blocks->length(); i++) {
1320       BlockBegin* block = _blocks->at(i);
1321       verify_block_preds_against_collected_preds(block);
1322     }
1323   }
1324 
1325   virtual void block_do(BlockBegin* block) {
1326     _blocks->append(block);
1327     collect_predecessors(block);
1328   }
1329 
1330  private:
1331   void collect_predecessors(BlockBegin* block) {
1332     for (int i = 0; i < block->end()->number_of_sux(); i++) {
1333       collect_predecessor(block, block->end()->sux_at(i));
1334     }
1335     for (int i = 0; i < block->number_of_exception_handlers(); i++) {
1336       collect_predecessor(block, block->exception_handler_at(i));
1337     }
1338   }
1339 
1340   void collect_predecessor(BlockBegin* const pred, const BlockBegin* sux) {
1341     BlockList* preds = _predecessors->at_grow(sux->block_id(), nullptr);
1342     if (preds == nullptr) {
1343       preds = new BlockList();
1344       _predecessors->at_put(sux->block_id(), preds);
1345     }
1346     preds->append(pred);
1347   }
1348 
1349   void verify_block_preds_against_collected_preds(const BlockBegin* block) const {
1350     BlockList* preds = _predecessors->at(block->block_id());
1351     if (preds == nullptr) {
1352       assert(block->number_of_preds() == 0, "should be the same");
1353       return;
1354     }
1355     assert(preds->length() == block->number_of_preds(), "should be the same");
1356 
1357     // clone the pred list so we can mutate it
1358     BlockList* pred_copy = new BlockList();
1359     for (int j = 0; j < block->number_of_preds(); j++) {
1360       pred_copy->append(block->pred_at(j));
1361     }
1362     // sort them in the same order
1363     preds->sort(cmp);
1364     pred_copy->sort(cmp);
1365     for (int j = 0; j < block->number_of_preds(); j++) {
1366       assert(preds->at(j) == pred_copy->at(j), "must match");
1367     }
1368   }
1369 };
1370 
1371 class VerifyBlockBeginField : public BlockClosure {
1372 public:
1373   virtual void block_do(BlockBegin* block) {
1374     for (Instruction* cur = block; cur != nullptr; cur = cur->next()) {
1375       assert(cur->block() == block, "Block begin is not correct");
1376     }
1377   }
1378 };
1379 
1380 class ValidateEdgeMutuality : public BlockClosure {
1381  public:
1382   virtual void block_do(BlockBegin* block) {
1383     for (int i = 0; i < block->end()->number_of_sux(); i++) {
1384       assert(block->end()->sux_at(i)->is_predecessor(block), "Block's successor should have it as predecessor");
1385     }
1386 
1387     for (int i = 0; i < block->number_of_exception_handlers(); i++) {
1388       assert(block->exception_handler_at(i)->is_predecessor(block), "Block's exception handler should have it as predecessor");
1389     }
1390 
1391     for (int i = 0; i < block->number_of_preds(); i++) {
1392       assert(block->pred_at(i) != nullptr, "Predecessor must exist");
1393       assert(block->pred_at(i)->end() != nullptr, "Predecessor end must exist");
1394       bool is_sux      = block->pred_at(i)->end()->is_sux(block);
1395       bool is_xhandler = block->pred_at(i)->is_exception_handler(block);
1396       assert(is_sux || is_xhandler, "Block's predecessor should have it as successor or xhandler");
1397     }
1398   }
1399 };
1400 
1401 void IR::expand_with_neighborhood(BlockList& blocks) {
1402   int original_size = blocks.length();
1403   for (int h = 0; h < original_size; h++) {
1404     BlockBegin* block = blocks.at(h);
1405 
1406     for (int i = 0; i < block->end()->number_of_sux(); i++) {
1407       if (!blocks.contains(block->end()->sux_at(i))) {
1408         blocks.append(block->end()->sux_at(i));
1409       }
1410     }
1411 
1412     for (int i = 0; i < block->number_of_preds(); i++) {
1413       if (!blocks.contains(block->pred_at(i))) {
1414         blocks.append(block->pred_at(i));
1415       }
1416     }
1417 
1418     for (int i = 0; i < block->number_of_exception_handlers(); i++) {
1419       if (!blocks.contains(block->exception_handler_at(i))) {
1420         blocks.append(block->exception_handler_at(i));
1421       }
1422     }
1423   }
1424 }
1425 
1426 void IR::verify_local(BlockList& blocks) {
1427   EndNotNullValidator ennv;
1428   blocks.iterate_forward(&ennv);
1429 
1430   ValidateEdgeMutuality vem;
1431   blocks.iterate_forward(&vem);
1432 
1433   VerifyBlockBeginField verifier;
1434   blocks.iterate_forward(&verifier);
1435 }
1436 
1437 void IR::verify() {
1438   XentryFlagValidator xe;
1439   iterate_postorder(&xe);
1440 
1441   PredecessorAndCodeValidator pv(this);
1442 
1443   EndNotNullValidator ennv;
1444   iterate_postorder(&ennv);
1445 
1446   ValidateEdgeMutuality vem;
1447   iterate_postorder(&vem);
1448 
1449   VerifyBlockBeginField verifier;
1450   iterate_postorder(&verifier);
1451 }
1452 #endif // ASSERT
1453 
1454 void SubstitutionResolver::visit(Value* v) {
1455   Value v0 = *v;
1456   if (v0) {
1457     Value vs = v0->subst();
1458     if (vs != v0) {
1459       *v = v0->subst();
1460     }
1461   }
1462 }
1463 
1464 #ifdef ASSERT
1465 class SubstitutionChecker: public ValueVisitor {
1466   void visit(Value* v) {
1467     Value v0 = *v;
1468     if (v0) {
1469       Value vs = v0->subst();
1470       assert(vs == v0, "missed substitution");
1471     }
1472   }
1473 };
1474 #endif
1475 
1476 
1477 void SubstitutionResolver::block_do(BlockBegin* block) {
1478   Instruction* last = nullptr;
1479   for (Instruction* n = block; n != nullptr;) {
1480     n->values_do(this);
1481     // need to remove this instruction from the instruction stream
1482     if (n->subst() != n) {
1483       guarantee(last != nullptr, "must have last");
1484       last->set_next(n->next());
1485     } else {
1486       last = n;
1487     }
1488     n = last->next();
1489   }
1490 
1491 #ifdef ASSERT
1492   SubstitutionChecker check_substitute;
1493   if (block->state()) block->state()->values_do(&check_substitute);
1494   block->block_values_do(&check_substitute);
1495   if (block->end() && block->end()->state()) block->end()->state()->values_do(&check_substitute);
1496 #endif
1497 }