1 /*
   2  * Copyright (c) 1997, 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 "asm/macroAssembler.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "ci/ciReplay.hpp"
  29 #include "classfile/javaClasses.hpp"
  30 #include "code/exceptionHandlerTable.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "compiler/compilationFailureInfo.hpp"
  33 #include "compiler/compilationMemoryStatistic.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/compileLog.hpp"
  36 #include "compiler/compiler_globals.hpp"
  37 #include "compiler/disassembler.hpp"
  38 #include "compiler/oopMap.hpp"
  39 #include "gc/shared/barrierSet.hpp"
  40 #include "gc/shared/c2/barrierSetC2.hpp"
  41 #include "jfr/jfrEvents.hpp"
  42 #include "jvm_io.h"
  43 #include "memory/allocation.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "opto/addnode.hpp"
  46 #include "opto/block.hpp"
  47 #include "opto/c2compiler.hpp"
  48 #include "opto/callGenerator.hpp"
  49 #include "opto/callnode.hpp"
  50 #include "opto/castnode.hpp"
  51 #include "opto/cfgnode.hpp"
  52 #include "opto/chaitin.hpp"
  53 #include "opto/compile.hpp"
  54 #include "opto/connode.hpp"
  55 #include "opto/convertnode.hpp"
  56 #include "opto/divnode.hpp"
  57 #include "opto/escape.hpp"
  58 #include "opto/idealGraphPrinter.hpp"
  59 #include "opto/loopnode.hpp"
  60 #include "opto/machnode.hpp"
  61 #include "opto/macro.hpp"
  62 #include "opto/matcher.hpp"
  63 #include "opto/mathexactnode.hpp"
  64 #include "opto/memnode.hpp"
  65 #include "opto/mulnode.hpp"
  66 #include "opto/narrowptrnode.hpp"
  67 #include "opto/node.hpp"
  68 #include "opto/opcodes.hpp"
  69 #include "opto/output.hpp"
  70 #include "opto/parse.hpp"
  71 #include "opto/phaseX.hpp"
  72 #include "opto/rootnode.hpp"
  73 #include "opto/runtime.hpp"
  74 #include "opto/stringopts.hpp"
  75 #include "opto/type.hpp"
  76 #include "opto/vector.hpp"
  77 #include "opto/vectornode.hpp"
  78 #include "runtime/globals_extension.hpp"
  79 #include "runtime/sharedRuntime.hpp"
  80 #include "runtime/signature.hpp"
  81 #include "runtime/stubRoutines.hpp"
  82 #include "runtime/timer.hpp"
  83 #include "utilities/align.hpp"
  84 #include "utilities/copy.hpp"
  85 #include "utilities/macros.hpp"
  86 #include "utilities/resourceHash.hpp"
  87 
  88 // -------------------- Compile::mach_constant_base_node -----------------------
  89 // Constant table base node singleton.
  90 MachConstantBaseNode* Compile::mach_constant_base_node() {
  91   if (_mach_constant_base_node == nullptr) {
  92     _mach_constant_base_node = new MachConstantBaseNode();
  93     _mach_constant_base_node->add_req(C->root());
  94   }
  95   return _mach_constant_base_node;
  96 }
  97 
  98 
  99 /// Support for intrinsics.
 100 
 101 // Return the index at which m must be inserted (or already exists).
 102 // The sort order is by the address of the ciMethod, with is_virtual as minor key.
 103 class IntrinsicDescPair {
 104  private:
 105   ciMethod* _m;
 106   bool _is_virtual;
 107  public:
 108   IntrinsicDescPair(ciMethod* m, bool is_virtual) : _m(m), _is_virtual(is_virtual) {}
 109   static int compare(IntrinsicDescPair* const& key, CallGenerator* const& elt) {
 110     ciMethod* m= elt->method();
 111     ciMethod* key_m = key->_m;
 112     if (key_m < m)      return -1;
 113     else if (key_m > m) return 1;
 114     else {
 115       bool is_virtual = elt->is_virtual();
 116       bool key_virtual = key->_is_virtual;
 117       if (key_virtual < is_virtual)      return -1;
 118       else if (key_virtual > is_virtual) return 1;
 119       else                               return 0;
 120     }
 121   }
 122 };
 123 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual, bool& found) {
 124 #ifdef ASSERT
 125   for (int i = 1; i < _intrinsics.length(); i++) {
 126     CallGenerator* cg1 = _intrinsics.at(i-1);
 127     CallGenerator* cg2 = _intrinsics.at(i);
 128     assert(cg1->method() != cg2->method()
 129            ? cg1->method()     < cg2->method()
 130            : cg1->is_virtual() < cg2->is_virtual(),
 131            "compiler intrinsics list must stay sorted");
 132   }
 133 #endif
 134   IntrinsicDescPair pair(m, is_virtual);
 135   return _intrinsics.find_sorted<IntrinsicDescPair*, IntrinsicDescPair::compare>(&pair, found);
 136 }
 137 
 138 void Compile::register_intrinsic(CallGenerator* cg) {
 139   bool found = false;
 140   int index = intrinsic_insertion_index(cg->method(), cg->is_virtual(), found);
 141   assert(!found, "registering twice");
 142   _intrinsics.insert_before(index, cg);
 143   assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
 144 }
 145 
 146 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
 147   assert(m->is_loaded(), "don't try this on unloaded methods");
 148   if (_intrinsics.length() > 0) {
 149     bool found = false;
 150     int index = intrinsic_insertion_index(m, is_virtual, found);
 151      if (found) {
 152       return _intrinsics.at(index);
 153     }
 154   }
 155   // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
 156   if (m->intrinsic_id() != vmIntrinsics::_none &&
 157       m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
 158     CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
 159     if (cg != nullptr) {
 160       // Save it for next time:
 161       register_intrinsic(cg);
 162       return cg;
 163     } else {
 164       gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
 165     }
 166   }
 167   return nullptr;
 168 }
 169 
 170 // Compile::make_vm_intrinsic is defined in library_call.cpp.
 171 
 172 #ifndef PRODUCT
 173 // statistics gathering...
 174 
 175 juint  Compile::_intrinsic_hist_count[vmIntrinsics::number_of_intrinsics()] = {0};
 176 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::number_of_intrinsics()] = {0};
 177 
 178 inline int as_int(vmIntrinsics::ID id) {
 179   return vmIntrinsics::as_int(id);
 180 }
 181 
 182 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
 183   assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
 184   int oflags = _intrinsic_hist_flags[as_int(id)];
 185   assert(flags != 0, "what happened?");
 186   if (is_virtual) {
 187     flags |= _intrinsic_virtual;
 188   }
 189   bool changed = (flags != oflags);
 190   if ((flags & _intrinsic_worked) != 0) {
 191     juint count = (_intrinsic_hist_count[as_int(id)] += 1);
 192     if (count == 1) {
 193       changed = true;           // first time
 194     }
 195     // increment the overall count also:
 196     _intrinsic_hist_count[as_int(vmIntrinsics::_none)] += 1;
 197   }
 198   if (changed) {
 199     if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
 200       // Something changed about the intrinsic's virtuality.
 201       if ((flags & _intrinsic_virtual) != 0) {
 202         // This is the first use of this intrinsic as a virtual call.
 203         if (oflags != 0) {
 204           // We already saw it as a non-virtual, so note both cases.
 205           flags |= _intrinsic_both;
 206         }
 207       } else if ((oflags & _intrinsic_both) == 0) {
 208         // This is the first use of this intrinsic as a non-virtual
 209         flags |= _intrinsic_both;
 210       }
 211     }
 212     _intrinsic_hist_flags[as_int(id)] = (jubyte) (oflags | flags);
 213   }
 214   // update the overall flags also:
 215   _intrinsic_hist_flags[as_int(vmIntrinsics::_none)] |= (jubyte) flags;
 216   return changed;
 217 }
 218 
 219 static char* format_flags(int flags, char* buf) {
 220   buf[0] = 0;
 221   if ((flags & Compile::_intrinsic_worked) != 0)    strcat(buf, ",worked");
 222   if ((flags & Compile::_intrinsic_failed) != 0)    strcat(buf, ",failed");
 223   if ((flags & Compile::_intrinsic_disabled) != 0)  strcat(buf, ",disabled");
 224   if ((flags & Compile::_intrinsic_virtual) != 0)   strcat(buf, ",virtual");
 225   if ((flags & Compile::_intrinsic_both) != 0)      strcat(buf, ",nonvirtual");
 226   if (buf[0] == 0)  strcat(buf, ",");
 227   assert(buf[0] == ',', "must be");
 228   return &buf[1];
 229 }
 230 
 231 void Compile::print_intrinsic_statistics() {
 232   char flagsbuf[100];
 233   ttyLocker ttyl;
 234   if (xtty != nullptr)  xtty->head("statistics type='intrinsic'");
 235   tty->print_cr("Compiler intrinsic usage:");
 236   juint total = _intrinsic_hist_count[as_int(vmIntrinsics::_none)];
 237   if (total == 0)  total = 1;  // avoid div0 in case of no successes
 238   #define PRINT_STAT_LINE(name, c, f) \
 239     tty->print_cr("  %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
 240   for (auto id : EnumRange<vmIntrinsicID>{}) {
 241     int   flags = _intrinsic_hist_flags[as_int(id)];
 242     juint count = _intrinsic_hist_count[as_int(id)];
 243     if ((flags | count) != 0) {
 244       PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
 245     }
 246   }
 247   PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[as_int(vmIntrinsics::_none)], flagsbuf));
 248   if (xtty != nullptr)  xtty->tail("statistics");
 249 }
 250 
 251 void Compile::print_statistics() {
 252   { ttyLocker ttyl;
 253     if (xtty != nullptr)  xtty->head("statistics type='opto'");
 254     Parse::print_statistics();
 255     PhaseStringOpts::print_statistics();
 256     PhaseCCP::print_statistics();
 257     PhaseRegAlloc::print_statistics();
 258     PhaseOutput::print_statistics();
 259     PhasePeephole::print_statistics();
 260     PhaseIdealLoop::print_statistics();
 261     ConnectionGraph::print_statistics();
 262     PhaseMacroExpand::print_statistics();
 263     if (xtty != nullptr)  xtty->tail("statistics");
 264   }
 265   if (_intrinsic_hist_flags[as_int(vmIntrinsics::_none)] != 0) {
 266     // put this under its own <statistics> element.
 267     print_intrinsic_statistics();
 268   }
 269 }
 270 #endif //PRODUCT
 271 
 272 void Compile::gvn_replace_by(Node* n, Node* nn) {
 273   for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
 274     Node* use = n->last_out(i);
 275     bool is_in_table = initial_gvn()->hash_delete(use);
 276     uint uses_found = 0;
 277     for (uint j = 0; j < use->len(); j++) {
 278       if (use->in(j) == n) {
 279         if (j < use->req())
 280           use->set_req(j, nn);
 281         else
 282           use->set_prec(j, nn);
 283         uses_found++;
 284       }
 285     }
 286     if (is_in_table) {
 287       // reinsert into table
 288       initial_gvn()->hash_find_insert(use);
 289     }
 290     record_for_igvn(use);
 291     PhaseIterGVN::add_users_of_use_to_worklist(nn, use, *_igvn_worklist);
 292     i -= uses_found;    // we deleted 1 or more copies of this edge
 293   }
 294 }
 295 
 296 
 297 // Identify all nodes that are reachable from below, useful.
 298 // Use breadth-first pass that records state in a Unique_Node_List,
 299 // recursive traversal is slower.
 300 void Compile::identify_useful_nodes(Unique_Node_List &useful) {
 301   int estimated_worklist_size = live_nodes();
 302   useful.map( estimated_worklist_size, nullptr );  // preallocate space
 303 
 304   // Initialize worklist
 305   if (root() != nullptr)  { useful.push(root()); }
 306   // If 'top' is cached, declare it useful to preserve cached node
 307   if (cached_top_node())  { useful.push(cached_top_node()); }
 308 
 309   // Push all useful nodes onto the list, breadthfirst
 310   for( uint next = 0; next < useful.size(); ++next ) {
 311     assert( next < unique(), "Unique useful nodes < total nodes");
 312     Node *n  = useful.at(next);
 313     uint max = n->len();
 314     for( uint i = 0; i < max; ++i ) {
 315       Node *m = n->in(i);
 316       if (not_a_node(m))  continue;
 317       useful.push(m);
 318     }
 319   }
 320 }
 321 
 322 // Update dead_node_list with any missing dead nodes using useful
 323 // list. Consider all non-useful nodes to be useless i.e., dead nodes.
 324 void Compile::update_dead_node_list(Unique_Node_List &useful) {
 325   uint max_idx = unique();
 326   VectorSet& useful_node_set = useful.member_set();
 327 
 328   for (uint node_idx = 0; node_idx < max_idx; node_idx++) {
 329     // If node with index node_idx is not in useful set,
 330     // mark it as dead in dead node list.
 331     if (!useful_node_set.test(node_idx)) {
 332       record_dead_node(node_idx);
 333     }
 334   }
 335 }
 336 
 337 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
 338   int shift = 0;
 339   for (int i = 0; i < inlines->length(); i++) {
 340     CallGenerator* cg = inlines->at(i);
 341     if (useful.member(cg->call_node())) {
 342       if (shift > 0) {
 343         inlines->at_put(i - shift, cg);
 344       }
 345     } else {
 346       shift++; // skip over the dead element
 347     }
 348   }
 349   if (shift > 0) {
 350     inlines->trunc_to(inlines->length() - shift); // remove last elements from compacted array
 351   }
 352 }
 353 
 354 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Node* dead) {
 355   assert(dead != nullptr && dead->is_Call(), "sanity");
 356   int found = 0;
 357   for (int i = 0; i < inlines->length(); i++) {
 358     if (inlines->at(i)->call_node() == dead) {
 359       inlines->remove_at(i);
 360       found++;
 361       NOT_DEBUG( break; ) // elements are unique, so exit early
 362     }
 363   }
 364   assert(found <= 1, "not unique");
 365 }
 366 
 367 template<typename N, ENABLE_IF_SDEFN(std::is_base_of<Node, N>::value)>
 368 void Compile::remove_useless_nodes(GrowableArray<N*>& node_list, Unique_Node_List& useful) {
 369   for (int i = node_list.length() - 1; i >= 0; i--) {
 370     N* node = node_list.at(i);
 371     if (!useful.member(node)) {
 372       node_list.delete_at(i); // replaces i-th with last element which is known to be useful (already processed)
 373     }
 374   }
 375 }
 376 
 377 void Compile::remove_useless_node(Node* dead) {
 378   remove_modified_node(dead);
 379 
 380   // Constant node that has no out-edges and has only one in-edge from
 381   // root is usually dead. However, sometimes reshaping walk makes
 382   // it reachable by adding use edges. So, we will NOT count Con nodes
 383   // as dead to be conservative about the dead node count at any
 384   // given time.
 385   if (!dead->is_Con()) {
 386     record_dead_node(dead->_idx);
 387   }
 388   if (dead->is_macro()) {
 389     remove_macro_node(dead);
 390   }
 391   if (dead->is_expensive()) {
 392     remove_expensive_node(dead);
 393   }
 394   if (dead->Opcode() == Op_Opaque4) {
 395     remove_template_assertion_predicate_opaq(dead);
 396   }
 397   if (dead->is_ParsePredicate()) {
 398     remove_parse_predicate(dead->as_ParsePredicate());
 399   }
 400   if (dead->for_post_loop_opts_igvn()) {
 401     remove_from_post_loop_opts_igvn(dead);
 402   }
 403   if (dead->is_Call()) {
 404     remove_useless_late_inlines(                &_late_inlines, dead);
 405     remove_useless_late_inlines(         &_string_late_inlines, dead);
 406     remove_useless_late_inlines(         &_boxing_late_inlines, dead);
 407     remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
 408 
 409     if (dead->is_CallStaticJava()) {
 410       remove_unstable_if_trap(dead->as_CallStaticJava(), false);
 411     }
 412   }
 413   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 414   bs->unregister_potential_barrier_node(dead);
 415 }
 416 
 417 // Disconnect all useless nodes by disconnecting those at the boundary.
 418 void Compile::disconnect_useless_nodes(Unique_Node_List& useful, Unique_Node_List& worklist) {
 419   uint next = 0;
 420   while (next < useful.size()) {
 421     Node *n = useful.at(next++);
 422     if (n->is_SafePoint()) {
 423       // We're done with a parsing phase. Replaced nodes are not valid
 424       // beyond that point.
 425       n->as_SafePoint()->delete_replaced_nodes();
 426     }
 427     // Use raw traversal of out edges since this code removes out edges
 428     int max = n->outcnt();
 429     for (int j = 0; j < max; ++j) {
 430       Node* child = n->raw_out(j);
 431       if (!useful.member(child)) {
 432         assert(!child->is_top() || child != top(),
 433                "If top is cached in Compile object it is in useful list");
 434         // Only need to remove this out-edge to the useless node
 435         n->raw_del_out(j);
 436         --j;
 437         --max;
 438       }
 439     }
 440     if (n->outcnt() == 1 && n->has_special_unique_user()) {
 441       assert(useful.member(n->unique_out()), "do not push a useless node");
 442       worklist.push(n->unique_out());
 443     }
 444   }
 445 
 446   remove_useless_nodes(_macro_nodes,        useful); // remove useless macro nodes
 447   remove_useless_nodes(_parse_predicates,   useful); // remove useless Parse Predicate nodes
 448   remove_useless_nodes(_template_assertion_predicate_opaqs, useful); // remove useless Assertion Predicate opaque nodes
 449   remove_useless_nodes(_expensive_nodes,    useful); // remove useless expensive nodes
 450   remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass
 451   remove_useless_unstable_if_traps(useful);          // remove useless unstable_if traps
 452   remove_useless_coarsened_locks(useful);            // remove useless coarsened locks nodes
 453 #ifdef ASSERT
 454   if (_modified_nodes != nullptr) {
 455     _modified_nodes->remove_useless_nodes(useful.member_set());
 456   }
 457 #endif
 458 
 459   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 460   bs->eliminate_useless_gc_barriers(useful, this);
 461   // clean up the late inline lists
 462   remove_useless_late_inlines(                &_late_inlines, useful);
 463   remove_useless_late_inlines(         &_string_late_inlines, useful);
 464   remove_useless_late_inlines(         &_boxing_late_inlines, useful);
 465   remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
 466   debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
 467 }
 468 
 469 // ============================================================================
 470 //------------------------------CompileWrapper---------------------------------
 471 class CompileWrapper : public StackObj {
 472   Compile *const _compile;
 473  public:
 474   CompileWrapper(Compile* compile);
 475 
 476   ~CompileWrapper();
 477 };
 478 
 479 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
 480   // the Compile* pointer is stored in the current ciEnv:
 481   ciEnv* env = compile->env();
 482   assert(env == ciEnv::current(), "must already be a ciEnv active");
 483   assert(env->compiler_data() == nullptr, "compile already active?");
 484   env->set_compiler_data(compile);
 485   assert(compile == Compile::current(), "sanity");
 486 
 487   compile->set_type_dict(nullptr);
 488   compile->set_clone_map(new Dict(cmpkey, hashkey, _compile->comp_arena()));
 489   compile->clone_map().set_clone_idx(0);
 490   compile->set_type_last_size(0);
 491   compile->set_last_tf(nullptr, nullptr);
 492   compile->set_indexSet_arena(nullptr);
 493   compile->set_indexSet_free_block_list(nullptr);
 494   compile->init_type_arena();
 495   Type::Initialize(compile);
 496   _compile->begin_method();
 497   _compile->clone_map().set_debug(_compile->has_method() && _compile->directive()->CloneMapDebugOption);
 498 }
 499 CompileWrapper::~CompileWrapper() {
 500   // simulate crash during compilation
 501   assert(CICrashAt < 0 || _compile->compile_id() != CICrashAt, "just as planned");
 502 
 503   _compile->end_method();
 504   _compile->env()->set_compiler_data(nullptr);
 505 }
 506 
 507 
 508 //----------------------------print_compile_messages---------------------------
 509 void Compile::print_compile_messages() {
 510 #ifndef PRODUCT
 511   // Check if recompiling
 512   if (!subsume_loads() && PrintOpto) {
 513     // Recompiling without allowing machine instructions to subsume loads
 514     tty->print_cr("*********************************************************");
 515     tty->print_cr("** Bailout: Recompile without subsuming loads          **");
 516     tty->print_cr("*********************************************************");
 517   }
 518   if ((do_escape_analysis() != DoEscapeAnalysis) && PrintOpto) {
 519     // Recompiling without escape analysis
 520     tty->print_cr("*********************************************************");
 521     tty->print_cr("** Bailout: Recompile without escape analysis          **");
 522     tty->print_cr("*********************************************************");
 523   }
 524   if (do_iterative_escape_analysis() != DoEscapeAnalysis && PrintOpto) {
 525     // Recompiling without iterative escape analysis
 526     tty->print_cr("*********************************************************");
 527     tty->print_cr("** Bailout: Recompile without iterative escape analysis**");
 528     tty->print_cr("*********************************************************");
 529   }
 530   if (do_reduce_allocation_merges() != ReduceAllocationMerges && PrintOpto) {
 531     // Recompiling without reducing allocation merges
 532     tty->print_cr("*********************************************************");
 533     tty->print_cr("** Bailout: Recompile without reduce allocation merges **");
 534     tty->print_cr("*********************************************************");
 535   }
 536   if ((eliminate_boxing() != EliminateAutoBox) && PrintOpto) {
 537     // Recompiling without boxing elimination
 538     tty->print_cr("*********************************************************");
 539     tty->print_cr("** Bailout: Recompile without boxing elimination       **");
 540     tty->print_cr("*********************************************************");
 541   }
 542   if ((do_locks_coarsening() != EliminateLocks) && PrintOpto) {
 543     // Recompiling without locks coarsening
 544     tty->print_cr("*********************************************************");
 545     tty->print_cr("** Bailout: Recompile without locks coarsening         **");
 546     tty->print_cr("*********************************************************");
 547   }
 548   if (env()->break_at_compile()) {
 549     // Open the debugger when compiling this method.
 550     tty->print("### Breaking when compiling: ");
 551     method()->print_short_name();
 552     tty->cr();
 553     BREAKPOINT;
 554   }
 555 
 556   if( PrintOpto ) {
 557     if (is_osr_compilation()) {
 558       tty->print("[OSR]%3d", _compile_id);
 559     } else {
 560       tty->print("%3d", _compile_id);
 561     }
 562   }
 563 #endif
 564 }
 565 
 566 #ifndef PRODUCT
 567 void Compile::print_ideal_ir(const char* phase_name) {
 568   // keep the following output all in one block
 569   // This output goes directly to the tty, not the compiler log.
 570   // To enable tools to match it up with the compilation activity,
 571   // be sure to tag this tty output with the compile ID.
 572 
 573   // Node dumping can cause a safepoint, which can break the tty lock.
 574   // Buffer all node dumps, so that all safepoints happen before we lock.
 575   ResourceMark rm;
 576   stringStream ss;
 577 
 578   if (_output == nullptr) {
 579     ss.print_cr("AFTER: %s", phase_name);
 580     // Print out all nodes in ascending order of index.
 581     root()->dump_bfs(MaxNodeLimit, nullptr, "+S$", &ss);
 582   } else {
 583     // Dump the node blockwise if we have a scheduling
 584     _output->print_scheduling(&ss);
 585   }
 586 
 587   // Check that the lock is not broken by a safepoint.
 588   NoSafepointVerifier nsv;
 589   ttyLocker ttyl;
 590   if (xtty != nullptr) {
 591     xtty->head("ideal compile_id='%d'%s compile_phase='%s'",
 592                compile_id(),
 593                is_osr_compilation() ? " compile_kind='osr'" : "",
 594                phase_name);
 595   }
 596 
 597   tty->print("%s", ss.as_string());
 598 
 599   if (xtty != nullptr) {
 600     xtty->tail("ideal");
 601   }
 602 }
 603 #endif
 604 
 605 // ============================================================================
 606 //------------------------------Compile standard-------------------------------
 607 
 608 // Compile a method.  entry_bci is -1 for normal compilations and indicates
 609 // the continuation bci for on stack replacement.
 610 
 611 
 612 Compile::Compile( ciEnv* ci_env, ciMethod* target, int osr_bci,
 613                   Options options, DirectiveSet* directive)
 614                 : Phase(Compiler),
 615                   _compile_id(ci_env->compile_id()),
 616                   _options(options),
 617                   _method(target),
 618                   _entry_bci(osr_bci),
 619                   _ilt(nullptr),
 620                   _stub_function(nullptr),
 621                   _stub_name(nullptr),
 622                   _stub_entry_point(nullptr),
 623                   _max_node_limit(MaxNodeLimit),
 624                   _post_loop_opts_phase(false),
 625                   _inlining_progress(false),
 626                   _inlining_incrementally(false),
 627                   _do_cleanup(false),
 628                   _has_reserved_stack_access(target->has_reserved_stack_access()),
 629 #ifndef PRODUCT
 630                   _igv_idx(0),
 631                   _trace_opto_output(directive->TraceOptoOutputOption),
 632 #endif
 633                   _has_method_handle_invokes(false),
 634                   _clinit_barrier_on_entry(false),
 635                   _stress_seed(0),
 636                   _comp_arena(mtCompiler),
 637                   _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 638                   _env(ci_env),
 639                   _directive(directive),
 640                   _log(ci_env->log()),
 641                   _failure_reason(nullptr),
 642                   _first_failure_details(nullptr),
 643                   _intrinsics        (comp_arena(), 0, 0, nullptr),
 644                   _macro_nodes       (comp_arena(), 8, 0, nullptr),
 645                   _parse_predicates  (comp_arena(), 8, 0, nullptr),
 646                   _template_assertion_predicate_opaqs (comp_arena(), 8, 0, nullptr),
 647                   _expensive_nodes   (comp_arena(), 8, 0, nullptr),
 648                   _for_post_loop_igvn(comp_arena(), 8, 0, nullptr),
 649                   _unstable_if_traps (comp_arena(), 8, 0, nullptr),
 650                   _coarsened_locks   (comp_arena(), 8, 0, nullptr),
 651                   _congraph(nullptr),
 652                   NOT_PRODUCT(_igv_printer(nullptr) COMMA)
 653                   _unique(0),
 654                   _dead_node_count(0),
 655                   _dead_node_list(comp_arena()),
 656                   _node_arena_one(mtCompiler, Arena::Tag::tag_node),
 657                   _node_arena_two(mtCompiler, Arena::Tag::tag_node),
 658                   _node_arena(&_node_arena_one),
 659                   _mach_constant_base_node(nullptr),
 660                   _Compile_types(mtCompiler),
 661                   _initial_gvn(nullptr),
 662                   _igvn_worklist(nullptr),
 663                   _types(nullptr),
 664                   _node_hash(nullptr),
 665                   _late_inlines(comp_arena(), 2, 0, nullptr),
 666                   _string_late_inlines(comp_arena(), 2, 0, nullptr),
 667                   _boxing_late_inlines(comp_arena(), 2, 0, nullptr),
 668                   _vector_reboxing_late_inlines(comp_arena(), 2, 0, nullptr),
 669                   _late_inlines_pos(0),
 670                   _number_of_mh_late_inlines(0),
 671                   _oom(false),
 672                   _print_inlining_stream(new (mtCompiler) stringStream()),
 673                   _print_inlining_list(nullptr),
 674                   _print_inlining_idx(0),
 675                   _print_inlining_output(nullptr),
 676                   _replay_inline_data(nullptr),
 677                   _java_calls(0),
 678                   _inner_loops(0),
 679                   _interpreter_frame_size(0),
 680                   _output(nullptr)
 681 #ifndef PRODUCT
 682                   , _in_dump_cnt(0)
 683 #endif
 684 {
 685   C = this;
 686   CompileWrapper cw(this);
 687 
 688   TraceTime t1("Total compilation time", &_t_totalCompilation, CITime, CITimeVerbose);
 689   TraceTime t2(nullptr, &_t_methodCompilation, CITime, false);
 690 
 691 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 692   bool print_opto_assembly = directive->PrintOptoAssemblyOption;
 693   // We can always print a disassembly, either abstract (hex dump) or
 694   // with the help of a suitable hsdis library. Thus, we should not
 695   // couple print_assembly and print_opto_assembly controls.
 696   // But: always print opto and regular assembly on compile command 'print'.
 697   bool print_assembly = directive->PrintAssemblyOption;
 698   set_print_assembly(print_opto_assembly || print_assembly);
 699 #else
 700   set_print_assembly(false); // must initialize.
 701 #endif
 702 
 703 #ifndef PRODUCT
 704   set_parsed_irreducible_loop(false);
 705 #endif
 706 
 707   if (directive->ReplayInlineOption) {
 708     _replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level());
 709   }
 710   set_print_inlining(directive->PrintInliningOption || PrintOptoInlining);
 711   set_print_intrinsics(directive->PrintIntrinsicsOption);
 712   set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it
 713 
 714   if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) {
 715     // Make sure the method being compiled gets its own MDO,
 716     // so we can at least track the decompile_count().
 717     // Need MDO to record RTM code generation state.
 718     method()->ensure_method_data();
 719   }
 720 
 721   Init(/*do_aliasing=*/ true);
 722 
 723   print_compile_messages();
 724 
 725   _ilt = InlineTree::build_inline_tree_root();
 726 
 727   // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
 728   assert(num_alias_types() >= AliasIdxRaw, "");
 729 
 730 #define MINIMUM_NODE_HASH  1023
 731 
 732   // GVN that will be run immediately on new nodes
 733   uint estimated_size = method()->code_size()*4+64;
 734   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
 735   _igvn_worklist = new (comp_arena()) Unique_Node_List(comp_arena());
 736   _types = new (comp_arena()) Type_Array(comp_arena());
 737   _node_hash = new (comp_arena()) NodeHash(comp_arena(), estimated_size);
 738   PhaseGVN gvn;
 739   set_initial_gvn(&gvn);
 740 
 741   print_inlining_init();
 742   { // Scope for timing the parser
 743     TracePhase tp("parse", &timers[_t_parser]);
 744 
 745     // Put top into the hash table ASAP.
 746     initial_gvn()->transform(top());
 747 
 748     // Set up tf(), start(), and find a CallGenerator.
 749     CallGenerator* cg = nullptr;
 750     if (is_osr_compilation()) {
 751       const TypeTuple *domain = StartOSRNode::osr_domain();
 752       const TypeTuple *range = TypeTuple::make_range(method()->signature());
 753       init_tf(TypeFunc::make(domain, range));
 754       StartNode* s = new StartOSRNode(root(), domain);
 755       initial_gvn()->set_type_bottom(s);
 756       init_start(s);
 757       cg = CallGenerator::for_osr(method(), entry_bci());
 758     } else {
 759       // Normal case.
 760       init_tf(TypeFunc::make(method()));
 761       StartNode* s = new StartNode(root(), tf()->domain());
 762       initial_gvn()->set_type_bottom(s);
 763       init_start(s);
 764       if (method()->intrinsic_id() == vmIntrinsics::_Reference_get) {
 765         // With java.lang.ref.reference.get() we must go through the
 766         // intrinsic - even when get() is the root
 767         // method of the compile - so that, if necessary, the value in
 768         // the referent field of the reference object gets recorded by
 769         // the pre-barrier code.
 770         cg = find_intrinsic(method(), false);
 771       }
 772       if (cg == nullptr) {
 773         float past_uses = method()->interpreter_invocation_count();
 774         float expected_uses = past_uses;
 775         cg = CallGenerator::for_inline(method(), expected_uses);
 776       }
 777     }
 778     if (failing())  return;
 779     if (cg == nullptr) {
 780       const char* reason = InlineTree::check_can_parse(method());
 781       assert(reason != nullptr, "expect reason for parse failure");
 782       stringStream ss;
 783       ss.print("cannot parse method: %s", reason);
 784       record_method_not_compilable(ss.as_string());
 785       return;
 786     }
 787 
 788     gvn.set_type(root(), root()->bottom_type());
 789 
 790     JVMState* jvms = build_start_state(start(), tf());
 791     if ((jvms = cg->generate(jvms)) == nullptr) {
 792       assert(failure_reason() != nullptr, "expect reason for parse failure");
 793       stringStream ss;
 794       ss.print("method parse failed: %s", failure_reason());
 795       record_method_not_compilable(ss.as_string());
 796       return;
 797     }
 798     GraphKit kit(jvms);
 799 
 800     if (!kit.stopped()) {
 801       // Accept return values, and transfer control we know not where.
 802       // This is done by a special, unique ReturnNode bound to root.
 803       return_values(kit.jvms());
 804     }
 805 
 806     if (kit.has_exceptions()) {
 807       // Any exceptions that escape from this call must be rethrown
 808       // to whatever caller is dynamically above us on the stack.
 809       // This is done by a special, unique RethrowNode bound to root.
 810       rethrow_exceptions(kit.transfer_exceptions_into_jvms());
 811     }
 812 
 813     assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
 814 
 815     if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
 816       inline_string_calls(true);
 817     }
 818 
 819     if (failing())  return;
 820 
 821     // Remove clutter produced by parsing.
 822     if (!failing()) {
 823       ResourceMark rm;
 824       PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
 825     }
 826   }
 827 
 828   // Note:  Large methods are capped off in do_one_bytecode().
 829   if (failing())  return;
 830 
 831   // After parsing, node notes are no longer automagic.
 832   // They must be propagated by register_new_node_with_optimizer(),
 833   // clone(), or the like.
 834   set_default_node_notes(nullptr);
 835 
 836 #ifndef PRODUCT
 837   if (should_print_igv(1)) {
 838     _igv_printer->print_inlining();
 839   }
 840 #endif
 841 
 842   if (failing())  return;
 843   NOT_PRODUCT( verify_graph_edges(); )
 844 
 845   // If any phase is randomized for stress testing, seed random number
 846   // generation and log the seed for repeatability.
 847   if (StressLCM || StressGCM || StressIGVN || StressCCP ||
 848       StressIncrementalInlining || StressMacroExpansion) {
 849     if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && directive->RepeatCompilationOption)) {
 850       _stress_seed = static_cast<uint>(Ticks::now().nanoseconds());
 851       FLAG_SET_ERGO(StressSeed, _stress_seed);
 852     } else {
 853       _stress_seed = StressSeed;
 854     }
 855     if (_log != nullptr) {
 856       _log->elem("stress_test seed='%u'", _stress_seed);
 857     }
 858   }
 859 
 860   // Now optimize
 861   Optimize();
 862   if (failing())  return;
 863   NOT_PRODUCT( verify_graph_edges(); )
 864 
 865 #ifndef PRODUCT
 866   if (should_print_ideal()) {
 867     print_ideal_ir("print_ideal");
 868   }
 869 #endif
 870 
 871 #ifdef ASSERT
 872   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 873   bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
 874 #endif
 875 
 876   // Dump compilation data to replay it.
 877   if (directive->DumpReplayOption) {
 878     env()->dump_replay_data(_compile_id);
 879   }
 880   if (directive->DumpInlineOption && (ilt() != nullptr)) {
 881     env()->dump_inline_data(_compile_id);
 882   }
 883 
 884   // Now that we know the size of all the monitors we can add a fixed slot
 885   // for the original deopt pc.
 886   int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size);
 887   set_fixed_slots(next_slot);
 888 
 889   // Compute when to use implicit null checks. Used by matching trap based
 890   // nodes and NullCheck optimization.
 891   set_allowed_deopt_reasons();
 892 
 893   // Now generate code
 894   Code_Gen();
 895 }
 896 
 897 //------------------------------Compile----------------------------------------
 898 // Compile a runtime stub
 899 Compile::Compile( ciEnv* ci_env,
 900                   TypeFunc_generator generator,
 901                   address stub_function,
 902                   const char *stub_name,
 903                   int is_fancy_jump,
 904                   bool pass_tls,
 905                   bool return_pc,
 906                   DirectiveSet* directive)
 907   : Phase(Compiler),
 908     _compile_id(0),
 909     _options(Options::for_runtime_stub()),
 910     _method(nullptr),
 911     _entry_bci(InvocationEntryBci),
 912     _stub_function(stub_function),
 913     _stub_name(stub_name),
 914     _stub_entry_point(nullptr),
 915     _max_node_limit(MaxNodeLimit),
 916     _post_loop_opts_phase(false),
 917     _inlining_progress(false),
 918     _inlining_incrementally(false),
 919     _has_reserved_stack_access(false),
 920 #ifndef PRODUCT
 921     _igv_idx(0),
 922     _trace_opto_output(directive->TraceOptoOutputOption),
 923 #endif
 924     _has_method_handle_invokes(false),
 925     _clinit_barrier_on_entry(false),
 926     _stress_seed(0),
 927     _comp_arena(mtCompiler),
 928     _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 929     _env(ci_env),
 930     _directive(directive),
 931     _log(ci_env->log()),
 932     _failure_reason(nullptr),
 933     _first_failure_details(nullptr),
 934     _congraph(nullptr),
 935     NOT_PRODUCT(_igv_printer(nullptr) COMMA)
 936     _unique(0),
 937     _dead_node_count(0),
 938     _dead_node_list(comp_arena()),
 939     _node_arena_one(mtCompiler),
 940     _node_arena_two(mtCompiler),
 941     _node_arena(&_node_arena_one),
 942     _mach_constant_base_node(nullptr),
 943     _Compile_types(mtCompiler),
 944     _initial_gvn(nullptr),
 945     _igvn_worklist(nullptr),
 946     _types(nullptr),
 947     _node_hash(nullptr),
 948     _number_of_mh_late_inlines(0),
 949     _oom(false),
 950     _print_inlining_stream(new (mtCompiler) stringStream()),
 951     _print_inlining_list(nullptr),
 952     _print_inlining_idx(0),
 953     _print_inlining_output(nullptr),
 954     _replay_inline_data(nullptr),
 955     _java_calls(0),
 956     _inner_loops(0),
 957     _interpreter_frame_size(0),
 958     _output(nullptr),
 959 #ifndef PRODUCT
 960     _in_dump_cnt(0),
 961 #endif
 962     _allowed_reasons(0) {
 963   C = this;
 964 
 965   TraceTime t1(nullptr, &_t_totalCompilation, CITime, false);
 966   TraceTime t2(nullptr, &_t_stubCompilation, CITime, false);
 967 
 968 #ifndef PRODUCT
 969   set_print_assembly(PrintFrameConverterAssembly);
 970   set_parsed_irreducible_loop(false);
 971 #else
 972   set_print_assembly(false); // Must initialize.
 973 #endif
 974   set_has_irreducible_loop(false); // no loops
 975 
 976   CompileWrapper cw(this);
 977   Init(/*do_aliasing=*/ false);
 978   init_tf((*generator)());
 979 
 980   _igvn_worklist = new (comp_arena()) Unique_Node_List(comp_arena());
 981   _types = new (comp_arena()) Type_Array(comp_arena());
 982   _node_hash = new (comp_arena()) NodeHash(comp_arena(), 255);
 983   {
 984     PhaseGVN gvn;
 985     set_initial_gvn(&gvn);    // not significant, but GraphKit guys use it pervasively
 986     gvn.transform(top());
 987 
 988     GraphKit kit;
 989     kit.gen_stub(stub_function, stub_name, is_fancy_jump, pass_tls, return_pc);
 990   }
 991 
 992   NOT_PRODUCT( verify_graph_edges(); )
 993 
 994   Code_Gen();
 995 }
 996 
 997 Compile::~Compile() {
 998   delete _print_inlining_stream;
 999   delete _first_failure_details;
1000 };
1001 
1002 //------------------------------Init-------------------------------------------
1003 // Prepare for a single compilation
1004 void Compile::Init(bool aliasing) {
1005   _do_aliasing = aliasing;
1006   _unique  = 0;
1007   _regalloc = nullptr;
1008 
1009   _tf      = nullptr;  // filled in later
1010   _top     = nullptr;  // cached later
1011   _matcher = nullptr;  // filled in later
1012   _cfg     = nullptr;  // filled in later
1013 
1014   IA32_ONLY( set_24_bit_selection_and_mode(true, false); )
1015 
1016   _node_note_array = nullptr;
1017   _default_node_notes = nullptr;
1018   DEBUG_ONLY( _modified_nodes = nullptr; ) // Used in Optimize()
1019 
1020   _immutable_memory = nullptr; // filled in at first inquiry
1021 
1022 #ifdef ASSERT
1023   _phase_optimize_finished = false;
1024   _exception_backedge = false;
1025   _type_verify = nullptr;
1026 #endif
1027 
1028   // Globally visible Nodes
1029   // First set TOP to null to give safe behavior during creation of RootNode
1030   set_cached_top_node(nullptr);
1031   set_root(new RootNode());
1032   // Now that you have a Root to point to, create the real TOP
1033   set_cached_top_node( new ConNode(Type::TOP) );
1034   set_recent_alloc(nullptr, nullptr);
1035 
1036   // Create Debug Information Recorder to record scopes, oopmaps, etc.
1037   env()->set_oop_recorder(new OopRecorder(env()->arena()));
1038   env()->set_debug_info(new DebugInformationRecorder(env()->oop_recorder()));
1039   env()->set_dependencies(new Dependencies(env()));
1040 
1041   _fixed_slots = 0;
1042   set_has_split_ifs(false);
1043   set_has_loops(false); // first approximation
1044   set_has_stringbuilder(false);
1045   set_has_boxed_value(false);
1046   _trap_can_recompile = false;  // no traps emitted yet
1047   _major_progress = true; // start out assuming good things will happen
1048   set_has_unsafe_access(false);
1049   set_max_vector_size(0);
1050   set_clear_upper_avx(false);  //false as default for clear upper bits of ymm registers
1051   Copy::zero_to_bytes(_trap_hist, sizeof(_trap_hist));
1052   set_decompile_count(0);
1053 
1054 #ifndef PRODUCT
1055   Copy::zero_to_bytes(_igv_phase_iter, sizeof(_igv_phase_iter));
1056 #endif
1057 
1058   set_do_freq_based_layout(_directive->BlockLayoutByFrequencyOption);
1059   _loop_opts_cnt = LoopOptsCount;
1060   set_do_inlining(Inline);
1061   set_max_inline_size(MaxInlineSize);
1062   set_freq_inline_size(FreqInlineSize);
1063   set_do_scheduling(OptoScheduling);
1064 
1065   set_do_vector_loop(false);
1066   set_has_monitors(false);
1067 
1068   if (AllowVectorizeOnDemand) {
1069     if (has_method() && _directive->VectorizeOption) {
1070       set_do_vector_loop(true);
1071       NOT_PRODUCT(if (do_vector_loop() && Verbose) {tty->print("Compile::Init: do vectorized loops (SIMD like) for method %s\n",  method()->name()->as_quoted_ascii());})
1072     } else if (has_method() && method()->name() != 0 &&
1073                method()->intrinsic_id() == vmIntrinsics::_forEachRemaining) {
1074       set_do_vector_loop(true);
1075     }
1076   }
1077   set_use_cmove(UseCMoveUnconditionally /* || do_vector_loop()*/); //TODO: consider do_vector_loop() mandate use_cmove unconditionally
1078   NOT_PRODUCT(if (use_cmove() && Verbose && has_method()) {tty->print("Compile::Init: use CMove without profitability tests for method %s\n",  method()->name()->as_quoted_ascii());})
1079 
1080   set_rtm_state(NoRTM); // No RTM lock eliding by default
1081   _max_node_limit = _directive->MaxNodeLimitOption;
1082 
1083 #if INCLUDE_RTM_OPT
1084   if (UseRTMLocking && has_method() && (method()->method_data_or_null() != nullptr)) {
1085     int rtm_state = method()->method_data()->rtm_state();
1086     if (method_has_option(CompileCommand::NoRTMLockEliding) || ((rtm_state & NoRTM) != 0)) {
1087       // Don't generate RTM lock eliding code.
1088       set_rtm_state(NoRTM);
1089     } else if (method_has_option(CompileCommand::UseRTMLockEliding) || ((rtm_state & UseRTM) != 0) || !UseRTMDeopt) {
1090       // Generate RTM lock eliding code without abort ratio calculation code.
1091       set_rtm_state(UseRTM);
1092     } else if (UseRTMDeopt) {
1093       // Generate RTM lock eliding code and include abort ratio calculation
1094       // code if UseRTMDeopt is on.
1095       set_rtm_state(ProfileRTM);
1096     }
1097   }
1098 #endif
1099   if (VM_Version::supports_fast_class_init_checks() && has_method() && !is_osr_compilation() && method()->needs_clinit_barrier()) {
1100     set_clinit_barrier_on_entry(true);
1101   }
1102   if (debug_info()->recording_non_safepoints()) {
1103     set_node_note_array(new(comp_arena()) GrowableArray<Node_Notes*>
1104                         (comp_arena(), 8, 0, nullptr));
1105     set_default_node_notes(Node_Notes::make(this));
1106   }
1107 
1108   const int grow_ats = 16;
1109   _max_alias_types = grow_ats;
1110   _alias_types   = NEW_ARENA_ARRAY(comp_arena(), AliasType*, grow_ats);
1111   AliasType* ats = NEW_ARENA_ARRAY(comp_arena(), AliasType,  grow_ats);
1112   Copy::zero_to_bytes(ats, sizeof(AliasType)*grow_ats);
1113   {
1114     for (int i = 0; i < grow_ats; i++)  _alias_types[i] = &ats[i];
1115   }
1116   // Initialize the first few types.
1117   _alias_types[AliasIdxTop]->Init(AliasIdxTop, nullptr);
1118   _alias_types[AliasIdxBot]->Init(AliasIdxBot, TypePtr::BOTTOM);
1119   _alias_types[AliasIdxRaw]->Init(AliasIdxRaw, TypeRawPtr::BOTTOM);
1120   _num_alias_types = AliasIdxRaw+1;
1121   // Zero out the alias type cache.
1122   Copy::zero_to_bytes(_alias_cache, sizeof(_alias_cache));
1123   // A null adr_type hits in the cache right away.  Preload the right answer.
1124   probe_alias_cache(nullptr)->_index = AliasIdxTop;
1125 }
1126 
1127 //---------------------------init_start----------------------------------------
1128 // Install the StartNode on this compile object.
1129 void Compile::init_start(StartNode* s) {
1130   if (failing())
1131     return; // already failing
1132   assert(s == start(), "");
1133 }
1134 
1135 /**
1136  * Return the 'StartNode'. We must not have a pending failure, since the ideal graph
1137  * can be in an inconsistent state, i.e., we can get segmentation faults when traversing
1138  * the ideal graph.
1139  */
1140 StartNode* Compile::start() const {
1141   assert (!failing(), "Must not have pending failure. Reason is: %s", failure_reason());
1142   for (DUIterator_Fast imax, i = root()->fast_outs(imax); i < imax; i++) {
1143     Node* start = root()->fast_out(i);
1144     if (start->is_Start()) {
1145       return start->as_Start();
1146     }
1147   }
1148   fatal("Did not find Start node!");
1149   return nullptr;
1150 }
1151 
1152 //-------------------------------immutable_memory-------------------------------------
1153 // Access immutable memory
1154 Node* Compile::immutable_memory() {
1155   if (_immutable_memory != nullptr) {
1156     return _immutable_memory;
1157   }
1158   StartNode* s = start();
1159   for (DUIterator_Fast imax, i = s->fast_outs(imax); true; i++) {
1160     Node *p = s->fast_out(i);
1161     if (p != s && p->as_Proj()->_con == TypeFunc::Memory) {
1162       _immutable_memory = p;
1163       return _immutable_memory;
1164     }
1165   }
1166   ShouldNotReachHere();
1167   return nullptr;
1168 }
1169 
1170 //----------------------set_cached_top_node------------------------------------
1171 // Install the cached top node, and make sure Node::is_top works correctly.
1172 void Compile::set_cached_top_node(Node* tn) {
1173   if (tn != nullptr)  verify_top(tn);
1174   Node* old_top = _top;
1175   _top = tn;
1176   // Calling Node::setup_is_top allows the nodes the chance to adjust
1177   // their _out arrays.
1178   if (_top != nullptr)     _top->setup_is_top();
1179   if (old_top != nullptr)  old_top->setup_is_top();
1180   assert(_top == nullptr || top()->is_top(), "");
1181 }
1182 
1183 #ifdef ASSERT
1184 uint Compile::count_live_nodes_by_graph_walk() {
1185   Unique_Node_List useful(comp_arena());
1186   // Get useful node list by walking the graph.
1187   identify_useful_nodes(useful);
1188   return useful.size();
1189 }
1190 
1191 void Compile::print_missing_nodes() {
1192 
1193   // Return if CompileLog is null and PrintIdealNodeCount is false.
1194   if ((_log == nullptr) && (! PrintIdealNodeCount)) {
1195     return;
1196   }
1197 
1198   // This is an expensive function. It is executed only when the user
1199   // specifies VerifyIdealNodeCount option or otherwise knows the
1200   // additional work that needs to be done to identify reachable nodes
1201   // by walking the flow graph and find the missing ones using
1202   // _dead_node_list.
1203 
1204   Unique_Node_List useful(comp_arena());
1205   // Get useful node list by walking the graph.
1206   identify_useful_nodes(useful);
1207 
1208   uint l_nodes = C->live_nodes();
1209   uint l_nodes_by_walk = useful.size();
1210 
1211   if (l_nodes != l_nodes_by_walk) {
1212     if (_log != nullptr) {
1213       _log->begin_head("mismatched_nodes count='%d'", abs((int) (l_nodes - l_nodes_by_walk)));
1214       _log->stamp();
1215       _log->end_head();
1216     }
1217     VectorSet& useful_member_set = useful.member_set();
1218     int last_idx = l_nodes_by_walk;
1219     for (int i = 0; i < last_idx; i++) {
1220       if (useful_member_set.test(i)) {
1221         if (_dead_node_list.test(i)) {
1222           if (_log != nullptr) {
1223             _log->elem("mismatched_node_info node_idx='%d' type='both live and dead'", i);
1224           }
1225           if (PrintIdealNodeCount) {
1226             // Print the log message to tty
1227               tty->print_cr("mismatched_node idx='%d' both live and dead'", i);
1228               useful.at(i)->dump();
1229           }
1230         }
1231       }
1232       else if (! _dead_node_list.test(i)) {
1233         if (_log != nullptr) {
1234           _log->elem("mismatched_node_info node_idx='%d' type='neither live nor dead'", i);
1235         }
1236         if (PrintIdealNodeCount) {
1237           // Print the log message to tty
1238           tty->print_cr("mismatched_node idx='%d' type='neither live nor dead'", i);
1239         }
1240       }
1241     }
1242     if (_log != nullptr) {
1243       _log->tail("mismatched_nodes");
1244     }
1245   }
1246 }
1247 void Compile::record_modified_node(Node* n) {
1248   if (_modified_nodes != nullptr && !_inlining_incrementally && !n->is_Con()) {
1249     _modified_nodes->push(n);
1250   }
1251 }
1252 
1253 void Compile::remove_modified_node(Node* n) {
1254   if (_modified_nodes != nullptr) {
1255     _modified_nodes->remove(n);
1256   }
1257 }
1258 #endif
1259 
1260 #ifndef PRODUCT
1261 void Compile::verify_top(Node* tn) const {
1262   if (tn != nullptr) {
1263     assert(tn->is_Con(), "top node must be a constant");
1264     assert(((ConNode*)tn)->type() == Type::TOP, "top node must have correct type");
1265     assert(tn->in(0) != nullptr, "must have live top node");
1266   }
1267 }
1268 #endif
1269 
1270 
1271 ///-------------------Managing Per-Node Debug & Profile Info-------------------
1272 
1273 void Compile::grow_node_notes(GrowableArray<Node_Notes*>* arr, int grow_by) {
1274   guarantee(arr != nullptr, "");
1275   int num_blocks = arr->length();
1276   if (grow_by < num_blocks)  grow_by = num_blocks;
1277   int num_notes = grow_by * _node_notes_block_size;
1278   Node_Notes* notes = NEW_ARENA_ARRAY(node_arena(), Node_Notes, num_notes);
1279   Copy::zero_to_bytes(notes, num_notes * sizeof(Node_Notes));
1280   while (num_notes > 0) {
1281     arr->append(notes);
1282     notes     += _node_notes_block_size;
1283     num_notes -= _node_notes_block_size;
1284   }
1285   assert(num_notes == 0, "exact multiple, please");
1286 }
1287 
1288 bool Compile::copy_node_notes_to(Node* dest, Node* source) {
1289   if (source == nullptr || dest == nullptr)  return false;
1290 
1291   if (dest->is_Con())
1292     return false;               // Do not push debug info onto constants.
1293 
1294 #ifdef ASSERT
1295   // Leave a bread crumb trail pointing to the original node:
1296   if (dest != nullptr && dest != source && dest->debug_orig() == nullptr) {
1297     dest->set_debug_orig(source);
1298   }
1299 #endif
1300 
1301   if (node_note_array() == nullptr)
1302     return false;               // Not collecting any notes now.
1303 
1304   // This is a copy onto a pre-existing node, which may already have notes.
1305   // If both nodes have notes, do not overwrite any pre-existing notes.
1306   Node_Notes* source_notes = node_notes_at(source->_idx);
1307   if (source_notes == nullptr || source_notes->is_clear())  return false;
1308   Node_Notes* dest_notes   = node_notes_at(dest->_idx);
1309   if (dest_notes == nullptr || dest_notes->is_clear()) {
1310     return set_node_notes_at(dest->_idx, source_notes);
1311   }
1312 
1313   Node_Notes merged_notes = (*source_notes);
1314   // The order of operations here ensures that dest notes will win...
1315   merged_notes.update_from(dest_notes);
1316   return set_node_notes_at(dest->_idx, &merged_notes);
1317 }
1318 
1319 
1320 //--------------------------allow_range_check_smearing-------------------------
1321 // Gating condition for coalescing similar range checks.
1322 // Sometimes we try 'speculatively' replacing a series of a range checks by a
1323 // single covering check that is at least as strong as any of them.
1324 // If the optimization succeeds, the simplified (strengthened) range check
1325 // will always succeed.  If it fails, we will deopt, and then give up
1326 // on the optimization.
1327 bool Compile::allow_range_check_smearing() const {
1328   // If this method has already thrown a range-check,
1329   // assume it was because we already tried range smearing
1330   // and it failed.
1331   uint already_trapped = trap_count(Deoptimization::Reason_range_check);
1332   return !already_trapped;
1333 }
1334 
1335 
1336 //------------------------------flatten_alias_type-----------------------------
1337 const TypePtr *Compile::flatten_alias_type( const TypePtr *tj ) const {
1338   assert(do_aliasing(), "Aliasing should be enabled");
1339   int offset = tj->offset();
1340   TypePtr::PTR ptr = tj->ptr();
1341 
1342   // Known instance (scalarizable allocation) alias only with itself.
1343   bool is_known_inst = tj->isa_oopptr() != nullptr &&
1344                        tj->is_oopptr()->is_known_instance();
1345 
1346   // Process weird unsafe references.
1347   if (offset == Type::OffsetBot && (tj->isa_instptr() /*|| tj->isa_klassptr()*/)) {
1348     assert(InlineUnsafeOps || StressReflectiveCode, "indeterminate pointers come only from unsafe ops");
1349     assert(!is_known_inst, "scalarizable allocation should not have unsafe references");
1350     tj = TypeOopPtr::BOTTOM;
1351     ptr = tj->ptr();
1352     offset = tj->offset();
1353   }
1354 
1355   // Array pointers need some flattening
1356   const TypeAryPtr* ta = tj->isa_aryptr();
1357   if (ta && ta->is_stable()) {
1358     // Erase stability property for alias analysis.
1359     tj = ta = ta->cast_to_stable(false);
1360   }
1361   if( ta && is_known_inst ) {
1362     if ( offset != Type::OffsetBot &&
1363          offset > arrayOopDesc::length_offset_in_bytes() ) {
1364       offset = Type::OffsetBot; // Flatten constant access into array body only
1365       tj = ta = ta->
1366               remove_speculative()->
1367               cast_to_ptr_type(ptr)->
1368               with_offset(offset);
1369     }
1370   } else if (ta) {
1371     // For arrays indexed by constant indices, we flatten the alias
1372     // space to include all of the array body.  Only the header, klass
1373     // and array length can be accessed un-aliased.
1374     if( offset != Type::OffsetBot ) {
1375       if( ta->const_oop() ) { // MethodData* or Method*
1376         offset = Type::OffsetBot;   // Flatten constant access into array body
1377         tj = ta = ta->
1378                 remove_speculative()->
1379                 cast_to_ptr_type(ptr)->
1380                 cast_to_exactness(false)->
1381                 with_offset(offset);
1382       } else if( offset == arrayOopDesc::length_offset_in_bytes() ) {
1383         // range is OK as-is.
1384         tj = ta = TypeAryPtr::RANGE;
1385       } else if( offset == oopDesc::klass_offset_in_bytes() ) {
1386         tj = TypeInstPtr::KLASS; // all klass loads look alike
1387         ta = TypeAryPtr::RANGE; // generic ignored junk
1388         ptr = TypePtr::BotPTR;
1389       } else if( offset == oopDesc::mark_offset_in_bytes() ) {
1390         tj = TypeInstPtr::MARK;
1391         ta = TypeAryPtr::RANGE; // generic ignored junk
1392         ptr = TypePtr::BotPTR;
1393       } else {                  // Random constant offset into array body
1394         offset = Type::OffsetBot;   // Flatten constant access into array body
1395         tj = ta = ta->
1396                 remove_speculative()->
1397                 cast_to_ptr_type(ptr)->
1398                 cast_to_exactness(false)->
1399                 with_offset(offset);
1400       }
1401     }
1402     // Arrays of fixed size alias with arrays of unknown size.
1403     if (ta->size() != TypeInt::POS) {
1404       const TypeAry *tary = TypeAry::make(ta->elem(), TypeInt::POS);
1405       tj = ta = ta->
1406               remove_speculative()->
1407               cast_to_ptr_type(ptr)->
1408               with_ary(tary)->
1409               cast_to_exactness(false);
1410     }
1411     // Arrays of known objects become arrays of unknown objects.
1412     if (ta->elem()->isa_narrowoop() && ta->elem() != TypeNarrowOop::BOTTOM) {
1413       const TypeAry *tary = TypeAry::make(TypeNarrowOop::BOTTOM, ta->size());
1414       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,nullptr,false,offset);
1415     }
1416     if (ta->elem()->isa_oopptr() && ta->elem() != TypeInstPtr::BOTTOM) {
1417       const TypeAry *tary = TypeAry::make(TypeInstPtr::BOTTOM, ta->size());
1418       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,nullptr,false,offset);
1419     }
1420     // Arrays of bytes and of booleans both use 'bastore' and 'baload' so
1421     // cannot be distinguished by bytecode alone.
1422     if (ta->elem() == TypeInt::BOOL) {
1423       const TypeAry *tary = TypeAry::make(TypeInt::BYTE, ta->size());
1424       ciKlass* aklass = ciTypeArrayKlass::make(T_BYTE);
1425       tj = ta = TypeAryPtr::make(ptr,ta->const_oop(),tary,aklass,false,offset);
1426     }
1427     // During the 2nd round of IterGVN, NotNull castings are removed.
1428     // Make sure the Bottom and NotNull variants alias the same.
1429     // Also, make sure exact and non-exact variants alias the same.
1430     if (ptr == TypePtr::NotNull || ta->klass_is_exact() || ta->speculative() != nullptr) {
1431       tj = ta = ta->
1432               remove_speculative()->
1433               cast_to_ptr_type(TypePtr::BotPTR)->
1434               cast_to_exactness(false)->
1435               with_offset(offset);
1436     }
1437   }
1438 
1439   // Oop pointers need some flattening
1440   const TypeInstPtr *to = tj->isa_instptr();
1441   if (to && to != TypeOopPtr::BOTTOM) {
1442     ciInstanceKlass* ik = to->instance_klass();
1443     if( ptr == TypePtr::Constant ) {
1444       if (ik != ciEnv::current()->Class_klass() ||
1445           offset < ik->layout_helper_size_in_bytes()) {
1446         // No constant oop pointers (such as Strings); they alias with
1447         // unknown strings.
1448         assert(!is_known_inst, "not scalarizable allocation");
1449         tj = to = to->
1450                 cast_to_instance_id(TypeOopPtr::InstanceBot)->
1451                 remove_speculative()->
1452                 cast_to_ptr_type(TypePtr::BotPTR)->
1453                 cast_to_exactness(false);
1454       }
1455     } else if( is_known_inst ) {
1456       tj = to; // Keep NotNull and klass_is_exact for instance type
1457     } else if( ptr == TypePtr::NotNull || to->klass_is_exact() ) {
1458       // During the 2nd round of IterGVN, NotNull castings are removed.
1459       // Make sure the Bottom and NotNull variants alias the same.
1460       // Also, make sure exact and non-exact variants alias the same.
1461       tj = to = to->
1462               remove_speculative()->
1463               cast_to_instance_id(TypeOopPtr::InstanceBot)->
1464               cast_to_ptr_type(TypePtr::BotPTR)->
1465               cast_to_exactness(false);
1466     }
1467     if (to->speculative() != nullptr) {
1468       tj = to = to->remove_speculative();
1469     }
1470     // Canonicalize the holder of this field
1471     if (offset >= 0 && offset < instanceOopDesc::base_offset_in_bytes()) {
1472       // First handle header references such as a LoadKlassNode, even if the
1473       // object's klass is unloaded at compile time (4965979).
1474       if (!is_known_inst) { // Do it only for non-instance types
1475         tj = to = TypeInstPtr::make(TypePtr::BotPTR, env()->Object_klass(), false, nullptr, offset);
1476       }
1477     } else if (offset < 0 || offset >= ik->layout_helper_size_in_bytes()) {
1478       // Static fields are in the space above the normal instance
1479       // fields in the java.lang.Class instance.
1480       if (ik != ciEnv::current()->Class_klass()) {
1481         to = nullptr;
1482         tj = TypeOopPtr::BOTTOM;
1483         offset = tj->offset();
1484       }
1485     } else {
1486       ciInstanceKlass *canonical_holder = ik->get_canonical_holder(offset);
1487       assert(offset < canonical_holder->layout_helper_size_in_bytes(), "");
1488       if (!ik->equals(canonical_holder) || tj->offset() != offset) {
1489         if( is_known_inst ) {
1490           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, true, nullptr, offset, to->instance_id());
1491         } else {
1492           tj = to = TypeInstPtr::make(to->ptr(), canonical_holder, false, nullptr, offset);
1493         }
1494       }
1495     }
1496   }
1497 
1498   // Klass pointers to object array klasses need some flattening
1499   const TypeKlassPtr *tk = tj->isa_klassptr();
1500   if( tk ) {
1501     // If we are referencing a field within a Klass, we need
1502     // to assume the worst case of an Object.  Both exact and
1503     // inexact types must flatten to the same alias class so
1504     // use NotNull as the PTR.
1505     if ( offset == Type::OffsetBot || (offset >= 0 && (size_t)offset < sizeof(Klass)) ) {
1506       tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull,
1507                                        env()->Object_klass(),
1508                                        offset);
1509     }
1510 
1511     if (tk->isa_aryklassptr() && tk->is_aryklassptr()->elem()->isa_klassptr()) {
1512       ciKlass* k = ciObjArrayKlass::make(env()->Object_klass());
1513       if (!k || !k->is_loaded()) {                  // Only fails for some -Xcomp runs
1514         tj = tk = TypeInstKlassPtr::make(TypePtr::NotNull, env()->Object_klass(), offset);
1515       } else {
1516         tj = tk = TypeAryKlassPtr::make(TypePtr::NotNull, tk->is_aryklassptr()->elem(), k, offset);
1517       }
1518     }
1519 
1520     // Check for precise loads from the primary supertype array and force them
1521     // to the supertype cache alias index.  Check for generic array loads from
1522     // the primary supertype array and also force them to the supertype cache
1523     // alias index.  Since the same load can reach both, we need to merge
1524     // these 2 disparate memories into the same alias class.  Since the
1525     // primary supertype array is read-only, there's no chance of confusion
1526     // where we bypass an array load and an array store.
1527     int primary_supers_offset = in_bytes(Klass::primary_supers_offset());
1528     if (offset == Type::OffsetBot ||
1529         (offset >= primary_supers_offset &&
1530          offset < (int)(primary_supers_offset + Klass::primary_super_limit() * wordSize)) ||
1531         offset == (int)in_bytes(Klass::secondary_super_cache_offset())) {
1532       offset = in_bytes(Klass::secondary_super_cache_offset());
1533       tj = tk = tk->with_offset(offset);
1534     }
1535   }
1536 
1537   // Flatten all Raw pointers together.
1538   if (tj->base() == Type::RawPtr)
1539     tj = TypeRawPtr::BOTTOM;
1540 
1541   if (tj->base() == Type::AnyPtr)
1542     tj = TypePtr::BOTTOM;      // An error, which the caller must check for.
1543 
1544   offset = tj->offset();
1545   assert( offset != Type::OffsetTop, "Offset has fallen from constant" );
1546 
1547   assert( (offset != Type::OffsetBot && tj->base() != Type::AryPtr) ||
1548           (offset == Type::OffsetBot && tj->base() == Type::AryPtr) ||
1549           (offset == Type::OffsetBot && tj == TypeOopPtr::BOTTOM) ||
1550           (offset == Type::OffsetBot && tj == TypePtr::BOTTOM) ||
1551           (offset == oopDesc::mark_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1552           (offset == oopDesc::klass_offset_in_bytes() && tj->base() == Type::AryPtr) ||
1553           (offset == arrayOopDesc::length_offset_in_bytes() && tj->base() == Type::AryPtr),
1554           "For oops, klasses, raw offset must be constant; for arrays the offset is never known" );
1555   assert( tj->ptr() != TypePtr::TopPTR &&
1556           tj->ptr() != TypePtr::AnyNull &&
1557           tj->ptr() != TypePtr::Null, "No imprecise addresses" );
1558 //    assert( tj->ptr() != TypePtr::Constant ||
1559 //            tj->base() == Type::RawPtr ||
1560 //            tj->base() == Type::KlassPtr, "No constant oop addresses" );
1561 
1562   return tj;
1563 }
1564 
1565 void Compile::AliasType::Init(int i, const TypePtr* at) {
1566   assert(AliasIdxTop <= i && i < Compile::current()->_max_alias_types, "Invalid alias index");
1567   _index = i;
1568   _adr_type = at;
1569   _field = nullptr;
1570   _element = nullptr;
1571   _is_rewritable = true; // default
1572   const TypeOopPtr *atoop = (at != nullptr) ? at->isa_oopptr() : nullptr;
1573   if (atoop != nullptr && atoop->is_known_instance()) {
1574     const TypeOopPtr *gt = atoop->cast_to_instance_id(TypeOopPtr::InstanceBot);
1575     _general_index = Compile::current()->get_alias_index(gt);
1576   } else {
1577     _general_index = 0;
1578   }
1579 }
1580 
1581 BasicType Compile::AliasType::basic_type() const {
1582   if (element() != nullptr) {
1583     const Type* element = adr_type()->is_aryptr()->elem();
1584     return element->isa_narrowoop() ? T_OBJECT : element->array_element_basic_type();
1585   } if (field() != nullptr) {
1586     return field()->layout_type();
1587   } else {
1588     return T_ILLEGAL; // unknown
1589   }
1590 }
1591 
1592 //---------------------------------print_on------------------------------------
1593 #ifndef PRODUCT
1594 void Compile::AliasType::print_on(outputStream* st) {
1595   if (index() < 10)
1596         st->print("@ <%d> ", index());
1597   else  st->print("@ <%d>",  index());
1598   st->print(is_rewritable() ? "   " : " RO");
1599   int offset = adr_type()->offset();
1600   if (offset == Type::OffsetBot)
1601         st->print(" +any");
1602   else  st->print(" +%-3d", offset);
1603   st->print(" in ");
1604   adr_type()->dump_on(st);
1605   const TypeOopPtr* tjp = adr_type()->isa_oopptr();
1606   if (field() != nullptr && tjp) {
1607     if (tjp->is_instptr()->instance_klass()  != field()->holder() ||
1608         tjp->offset() != field()->offset_in_bytes()) {
1609       st->print(" != ");
1610       field()->print();
1611       st->print(" ***");
1612     }
1613   }
1614 }
1615 
1616 void print_alias_types() {
1617   Compile* C = Compile::current();
1618   tty->print_cr("--- Alias types, AliasIdxBot .. %d", C->num_alias_types()-1);
1619   for (int idx = Compile::AliasIdxBot; idx < C->num_alias_types(); idx++) {
1620     C->alias_type(idx)->print_on(tty);
1621     tty->cr();
1622   }
1623 }
1624 #endif
1625 
1626 
1627 //----------------------------probe_alias_cache--------------------------------
1628 Compile::AliasCacheEntry* Compile::probe_alias_cache(const TypePtr* adr_type) {
1629   intptr_t key = (intptr_t) adr_type;
1630   key ^= key >> logAliasCacheSize;
1631   return &_alias_cache[key & right_n_bits(logAliasCacheSize)];
1632 }
1633 
1634 
1635 //-----------------------------grow_alias_types--------------------------------
1636 void Compile::grow_alias_types() {
1637   const int old_ats  = _max_alias_types; // how many before?
1638   const int new_ats  = old_ats;          // how many more?
1639   const int grow_ats = old_ats+new_ats;  // how many now?
1640   _max_alias_types = grow_ats;
1641   _alias_types =  REALLOC_ARENA_ARRAY(comp_arena(), AliasType*, _alias_types, old_ats, grow_ats);
1642   AliasType* ats =    NEW_ARENA_ARRAY(comp_arena(), AliasType, new_ats);
1643   Copy::zero_to_bytes(ats, sizeof(AliasType)*new_ats);
1644   for (int i = 0; i < new_ats; i++)  _alias_types[old_ats+i] = &ats[i];
1645 }
1646 
1647 
1648 //--------------------------------find_alias_type------------------------------
1649 Compile::AliasType* Compile::find_alias_type(const TypePtr* adr_type, bool no_create, ciField* original_field) {
1650   if (!do_aliasing()) {
1651     return alias_type(AliasIdxBot);
1652   }
1653 
1654   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1655   if (ace->_adr_type == adr_type) {
1656     return alias_type(ace->_index);
1657   }
1658 
1659   // Handle special cases.
1660   if (adr_type == nullptr)          return alias_type(AliasIdxTop);
1661   if (adr_type == TypePtr::BOTTOM)  return alias_type(AliasIdxBot);
1662 
1663   // Do it the slow way.
1664   const TypePtr* flat = flatten_alias_type(adr_type);
1665 
1666 #ifdef ASSERT
1667   {
1668     ResourceMark rm;
1669     assert(flat == flatten_alias_type(flat), "not idempotent: adr_type = %s; flat = %s => %s",
1670            Type::str(adr_type), Type::str(flat), Type::str(flatten_alias_type(flat)));
1671     assert(flat != TypePtr::BOTTOM, "cannot alias-analyze an untyped ptr: adr_type = %s",
1672            Type::str(adr_type));
1673     if (flat->isa_oopptr() && !flat->isa_klassptr()) {
1674       const TypeOopPtr* foop = flat->is_oopptr();
1675       // Scalarizable allocations have exact klass always.
1676       bool exact = !foop->klass_is_exact() || foop->is_known_instance();
1677       const TypePtr* xoop = foop->cast_to_exactness(exact)->is_ptr();
1678       assert(foop == flatten_alias_type(xoop), "exactness must not affect alias type: foop = %s; xoop = %s",
1679              Type::str(foop), Type::str(xoop));
1680     }
1681   }
1682 #endif
1683 
1684   int idx = AliasIdxTop;
1685   for (int i = 0; i < num_alias_types(); i++) {
1686     if (alias_type(i)->adr_type() == flat) {
1687       idx = i;
1688       break;
1689     }
1690   }
1691 
1692   if (idx == AliasIdxTop) {
1693     if (no_create)  return nullptr;
1694     // Grow the array if necessary.
1695     if (_num_alias_types == _max_alias_types)  grow_alias_types();
1696     // Add a new alias type.
1697     idx = _num_alias_types++;
1698     _alias_types[idx]->Init(idx, flat);
1699     if (flat == TypeInstPtr::KLASS)  alias_type(idx)->set_rewritable(false);
1700     if (flat == TypeAryPtr::RANGE)   alias_type(idx)->set_rewritable(false);
1701     if (flat->isa_instptr()) {
1702       if (flat->offset() == java_lang_Class::klass_offset()
1703           && flat->is_instptr()->instance_klass() == env()->Class_klass())
1704         alias_type(idx)->set_rewritable(false);
1705     }
1706     if (flat->isa_aryptr()) {
1707 #ifdef ASSERT
1708       const int header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
1709       // (T_BYTE has the weakest alignment and size restrictions...)
1710       assert(flat->offset() < header_size_min, "array body reference must be OffsetBot");
1711 #endif
1712       if (flat->offset() == TypePtr::OffsetBot) {
1713         alias_type(idx)->set_element(flat->is_aryptr()->elem());
1714       }
1715     }
1716     if (flat->isa_klassptr()) {
1717       if (flat->offset() == in_bytes(Klass::super_check_offset_offset()))
1718         alias_type(idx)->set_rewritable(false);
1719       if (flat->offset() == in_bytes(Klass::modifier_flags_offset()))
1720         alias_type(idx)->set_rewritable(false);
1721       if (flat->offset() == in_bytes(Klass::access_flags_offset()))
1722         alias_type(idx)->set_rewritable(false);
1723       if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1724         alias_type(idx)->set_rewritable(false);
1725       if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1726         alias_type(idx)->set_rewritable(false);
1727     }
1728     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1729     // but the base pointer type is not distinctive enough to identify
1730     // references into JavaThread.)
1731 
1732     // Check for final fields.
1733     const TypeInstPtr* tinst = flat->isa_instptr();
1734     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1735       ciField* field;
1736       if (tinst->const_oop() != nullptr &&
1737           tinst->instance_klass() == ciEnv::current()->Class_klass() &&
1738           tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) {
1739         // static field
1740         ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1741         field = k->get_field_by_offset(tinst->offset(), true);
1742       } else {
1743         ciInstanceKlass *k = tinst->instance_klass();
1744         field = k->get_field_by_offset(tinst->offset(), false);
1745       }
1746       assert(field == nullptr ||
1747              original_field == nullptr ||
1748              (field->holder() == original_field->holder() &&
1749               field->offset_in_bytes() == original_field->offset_in_bytes() &&
1750               field->is_static() == original_field->is_static()), "wrong field?");
1751       // Set field() and is_rewritable() attributes.
1752       if (field != nullptr)  alias_type(idx)->set_field(field);
1753     }
1754   }
1755 
1756   // Fill the cache for next time.
1757   ace->_adr_type = adr_type;
1758   ace->_index    = idx;
1759   assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1760 
1761   // Might as well try to fill the cache for the flattened version, too.
1762   AliasCacheEntry* face = probe_alias_cache(flat);
1763   if (face->_adr_type == nullptr) {
1764     face->_adr_type = flat;
1765     face->_index    = idx;
1766     assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1767   }
1768 
1769   return alias_type(idx);
1770 }
1771 
1772 
1773 Compile::AliasType* Compile::alias_type(ciField* field) {
1774   const TypeOopPtr* t;
1775   if (field->is_static())
1776     t = TypeInstPtr::make(field->holder()->java_mirror());
1777   else
1778     t = TypeOopPtr::make_from_klass_raw(field->holder());
1779   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1780   assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1781   return atp;
1782 }
1783 
1784 
1785 //------------------------------have_alias_type--------------------------------
1786 bool Compile::have_alias_type(const TypePtr* adr_type) {
1787   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1788   if (ace->_adr_type == adr_type) {
1789     return true;
1790   }
1791 
1792   // Handle special cases.
1793   if (adr_type == nullptr)             return true;
1794   if (adr_type == TypePtr::BOTTOM)  return true;
1795 
1796   return find_alias_type(adr_type, true, nullptr) != nullptr;
1797 }
1798 
1799 //-----------------------------must_alias--------------------------------------
1800 // True if all values of the given address type are in the given alias category.
1801 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1802   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1803   if (adr_type == nullptr)              return true;  // null serves as TypePtr::TOP
1804   if (alias_idx == AliasIdxTop)         return false; // the empty category
1805   if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1806 
1807   // the only remaining possible overlap is identity
1808   int adr_idx = get_alias_index(adr_type);
1809   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1810   assert(adr_idx == alias_idx ||
1811          (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1812           && adr_type                       != TypeOopPtr::BOTTOM),
1813          "should not be testing for overlap with an unsafe pointer");
1814   return adr_idx == alias_idx;
1815 }
1816 
1817 //------------------------------can_alias--------------------------------------
1818 // True if any values of the given address type are in the given alias category.
1819 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1820   if (alias_idx == AliasIdxTop)         return false; // the empty category
1821   if (adr_type == nullptr)              return false; // null serves as TypePtr::TOP
1822   // Known instance doesn't alias with bottom memory
1823   if (alias_idx == AliasIdxBot)         return !adr_type->is_known_instance();                   // the universal category
1824   if (adr_type->base() == Type::AnyPtr) return !C->get_adr_type(alias_idx)->is_known_instance(); // TypePtr::BOTTOM or its twins
1825 
1826   // the only remaining possible overlap is identity
1827   int adr_idx = get_alias_index(adr_type);
1828   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1829   return adr_idx == alias_idx;
1830 }
1831 
1832 // Mark all ParsePredicateNodes as useless. They will later be removed from the graph in IGVN together with their
1833 // uncommon traps if no Runtime Predicates were created from the Parse Predicates.
1834 void Compile::mark_parse_predicate_nodes_useless(PhaseIterGVN& igvn) {
1835   if (parse_predicate_count() == 0) {
1836     return;
1837   }
1838   for (int i = 0; i < parse_predicate_count(); i++) {
1839     ParsePredicateNode* parse_predicate = _parse_predicates.at(i);
1840     parse_predicate->mark_useless();
1841     igvn._worklist.push(parse_predicate);
1842   }
1843   _parse_predicates.clear();
1844 }
1845 
1846 void Compile::record_for_post_loop_opts_igvn(Node* n) {
1847   if (!n->for_post_loop_opts_igvn()) {
1848     assert(!_for_post_loop_igvn.contains(n), "duplicate");
1849     n->add_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1850     _for_post_loop_igvn.append(n);
1851   }
1852 }
1853 
1854 void Compile::remove_from_post_loop_opts_igvn(Node* n) {
1855   n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1856   _for_post_loop_igvn.remove(n);
1857 }
1858 
1859 void Compile::process_for_post_loop_opts_igvn(PhaseIterGVN& igvn) {
1860   // Verify that all previous optimizations produced a valid graph
1861   // at least to this point, even if no loop optimizations were done.
1862   PhaseIdealLoop::verify(igvn);
1863 
1864   C->set_post_loop_opts_phase(); // no more loop opts allowed
1865 
1866   assert(!C->major_progress(), "not cleared");
1867 
1868   if (_for_post_loop_igvn.length() > 0) {
1869     while (_for_post_loop_igvn.length() > 0) {
1870       Node* n = _for_post_loop_igvn.pop();
1871       n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1872       igvn._worklist.push(n);
1873     }
1874     igvn.optimize();
1875     if (failing()) return;
1876     assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1877     assert(C->parse_predicate_count() == 0, "all parse predicates should have been removed now");
1878 
1879     // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1880     if (C->major_progress()) {
1881       C->clear_major_progress(); // ensure that major progress is now clear
1882     }
1883   }
1884 }
1885 
1886 void Compile::record_unstable_if_trap(UnstableIfTrap* trap) {
1887   if (OptimizeUnstableIf) {
1888     _unstable_if_traps.append(trap);
1889   }
1890 }
1891 
1892 void Compile::remove_useless_unstable_if_traps(Unique_Node_List& useful) {
1893   for (int i = _unstable_if_traps.length() - 1; i >= 0; i--) {
1894     UnstableIfTrap* trap = _unstable_if_traps.at(i);
1895     Node* n = trap->uncommon_trap();
1896     if (!useful.member(n)) {
1897       _unstable_if_traps.delete_at(i); // replaces i-th with last element which is known to be useful (already processed)
1898     }
1899   }
1900 }
1901 
1902 // Remove the unstable if trap associated with 'unc' from candidates. It is either dead
1903 // or fold-compares case. Return true if succeed or not found.
1904 //
1905 // In rare cases, the found trap has been processed. It is too late to delete it. Return
1906 // false and ask fold-compares to yield.
1907 //
1908 // 'fold-compares' may use the uncommon_trap of the dominating IfNode to cover the fused
1909 // IfNode. This breaks the unstable_if trap invariant: control takes the unstable path
1910 // when deoptimization does happen.
1911 bool Compile::remove_unstable_if_trap(CallStaticJavaNode* unc, bool yield) {
1912   for (int i = 0; i < _unstable_if_traps.length(); ++i) {
1913     UnstableIfTrap* trap = _unstable_if_traps.at(i);
1914     if (trap->uncommon_trap() == unc) {
1915       if (yield && trap->modified()) {
1916         return false;
1917       }
1918       _unstable_if_traps.delete_at(i);
1919       break;
1920     }
1921   }
1922   return true;
1923 }
1924 
1925 // Re-calculate unstable_if traps with the liveness of next_bci, which points to the unlikely path.
1926 // It needs to be done after igvn because fold-compares may fuse uncommon_traps and before renumbering.
1927 void Compile::process_for_unstable_if_traps(PhaseIterGVN& igvn) {
1928   for (int i = _unstable_if_traps.length() - 1; i >= 0; --i) {
1929     UnstableIfTrap* trap = _unstable_if_traps.at(i);
1930     CallStaticJavaNode* unc = trap->uncommon_trap();
1931     int next_bci = trap->next_bci();
1932     bool modified = trap->modified();
1933 
1934     if (next_bci != -1 && !modified) {
1935       assert(!_dead_node_list.test(unc->_idx), "changing a dead node!");
1936       JVMState* jvms = unc->jvms();
1937       ciMethod* method = jvms->method();
1938       ciBytecodeStream iter(method);
1939 
1940       iter.force_bci(jvms->bci());
1941       assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
1942       Bytecodes::Code c = iter.cur_bc();
1943       Node* lhs = nullptr;
1944       Node* rhs = nullptr;
1945       if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
1946         lhs = unc->peek_operand(0);
1947         rhs = unc->peek_operand(1);
1948       } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
1949         lhs = unc->peek_operand(0);
1950       }
1951 
1952       ResourceMark rm;
1953       const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
1954       assert(live_locals.is_valid(), "broken liveness info");
1955       int len = (int)live_locals.size();
1956 
1957       for (int i = 0; i < len; i++) {
1958         Node* local = unc->local(jvms, i);
1959         // kill local using the liveness of next_bci.
1960         // give up when the local looks like an operand to secure reexecution.
1961         if (!live_locals.at(i) && !local->is_top() && local != lhs && local!= rhs) {
1962           uint idx = jvms->locoff() + i;
1963 #ifdef ASSERT
1964           if (PrintOpto && Verbose) {
1965             tty->print("[unstable_if] kill local#%d: ", idx);
1966             local->dump();
1967             tty->cr();
1968           }
1969 #endif
1970           igvn.replace_input_of(unc, idx, top());
1971           modified = true;
1972         }
1973       }
1974     }
1975 
1976     // keep the mondified trap for late query
1977     if (modified) {
1978       trap->set_modified();
1979     } else {
1980       _unstable_if_traps.delete_at(i);
1981     }
1982   }
1983   igvn.optimize();
1984 }
1985 
1986 // StringOpts and late inlining of string methods
1987 void Compile::inline_string_calls(bool parse_time) {
1988   {
1989     // remove useless nodes to make the usage analysis simpler
1990     ResourceMark rm;
1991     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
1992   }
1993 
1994   {
1995     ResourceMark rm;
1996     print_method(PHASE_BEFORE_STRINGOPTS, 3);
1997     PhaseStringOpts pso(initial_gvn());
1998     print_method(PHASE_AFTER_STRINGOPTS, 3);
1999   }
2000 
2001   // now inline anything that we skipped the first time around
2002   if (!parse_time) {
2003     _late_inlines_pos = _late_inlines.length();
2004   }
2005 
2006   while (_string_late_inlines.length() > 0) {
2007     CallGenerator* cg = _string_late_inlines.pop();
2008     cg->do_late_inline();
2009     if (failing())  return;
2010   }
2011   _string_late_inlines.trunc_to(0);
2012 }
2013 
2014 // Late inlining of boxing methods
2015 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
2016   if (_boxing_late_inlines.length() > 0) {
2017     assert(has_boxed_value(), "inconsistent");
2018 
2019     set_inlining_incrementally(true);
2020 
2021     igvn_worklist()->ensure_empty(); // should be done with igvn
2022 
2023     _late_inlines_pos = _late_inlines.length();
2024 
2025     while (_boxing_late_inlines.length() > 0) {
2026       CallGenerator* cg = _boxing_late_inlines.pop();
2027       cg->do_late_inline();
2028       if (failing())  return;
2029     }
2030     _boxing_late_inlines.trunc_to(0);
2031 
2032     inline_incrementally_cleanup(igvn);
2033 
2034     set_inlining_incrementally(false);
2035   }
2036 }
2037 
2038 bool Compile::inline_incrementally_one() {
2039   assert(IncrementalInline, "incremental inlining should be on");
2040 
2041   TracePhase tp("incrementalInline_inline", &timers[_t_incrInline_inline]);
2042 
2043   set_inlining_progress(false);
2044   set_do_cleanup(false);
2045 
2046   for (int i = 0; i < _late_inlines.length(); i++) {
2047     _late_inlines_pos = i+1;
2048     CallGenerator* cg = _late_inlines.at(i);
2049     bool does_dispatch = cg->is_virtual_late_inline() || cg->is_mh_late_inline();
2050     if (inlining_incrementally() || does_dispatch) { // a call can be either inlined or strength-reduced to a direct call
2051       cg->do_late_inline();
2052       assert(_late_inlines.at(i) == cg, "no insertions before current position allowed");
2053       if (failing()) {
2054         return false;
2055       } else if (inlining_progress()) {
2056         _late_inlines_pos = i+1; // restore the position in case new elements were inserted
2057         print_method(PHASE_INCREMENTAL_INLINE_STEP, 3, cg->call_node());
2058         break; // process one call site at a time
2059       }
2060     } else {
2061       // Ignore late inline direct calls when inlining is not allowed.
2062       // They are left in the late inline list when node budget is exhausted until the list is fully drained.
2063     }
2064   }
2065   // Remove processed elements.
2066   _late_inlines.remove_till(_late_inlines_pos);
2067   _late_inlines_pos = 0;
2068 
2069   assert(inlining_progress() || _late_inlines.length() == 0, "no progress");
2070 
2071   bool needs_cleanup = do_cleanup() || over_inlining_cutoff();
2072 
2073   set_inlining_progress(false);
2074   set_do_cleanup(false);
2075 
2076   bool force_cleanup = directive()->IncrementalInlineForceCleanupOption;
2077   return (_late_inlines.length() > 0) && !needs_cleanup && !force_cleanup;
2078 }
2079 
2080 void Compile::inline_incrementally_cleanup(PhaseIterGVN& igvn) {
2081   {
2082     TracePhase tp("incrementalInline_pru", &timers[_t_incrInline_pru]);
2083     ResourceMark rm;
2084     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2085   }
2086   {
2087     TracePhase tp("incrementalInline_igvn", &timers[_t_incrInline_igvn]);
2088     igvn.reset_from_gvn(initial_gvn());
2089     igvn.optimize();
2090     if (failing()) return;
2091   }
2092   print_method(PHASE_INCREMENTAL_INLINE_CLEANUP, 3);
2093 }
2094 
2095 // Perform incremental inlining until bound on number of live nodes is reached
2096 void Compile::inline_incrementally(PhaseIterGVN& igvn) {
2097   TracePhase tp("incrementalInline", &timers[_t_incrInline]);
2098 
2099   set_inlining_incrementally(true);
2100   uint low_live_nodes = 0;
2101 
2102   while (_late_inlines.length() > 0) {
2103     if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2104       if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
2105         TracePhase tp("incrementalInline_ideal", &timers[_t_incrInline_ideal]);
2106         // PhaseIdealLoop is expensive so we only try it once we are
2107         // out of live nodes and we only try it again if the previous
2108         // helped got the number of nodes down significantly
2109         PhaseIdealLoop::optimize(igvn, LoopOptsNone);
2110         if (failing())  return;
2111         low_live_nodes = live_nodes();
2112         _major_progress = true;
2113       }
2114 
2115       if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2116         bool do_print_inlining = print_inlining() || print_intrinsics();
2117         if (do_print_inlining || log() != nullptr) {
2118           // Print inlining message for candidates that we couldn't inline for lack of space.
2119           for (int i = 0; i < _late_inlines.length(); i++) {
2120             CallGenerator* cg = _late_inlines.at(i);
2121             const char* msg = "live nodes > LiveNodeCountInliningCutoff";
2122             if (do_print_inlining) {
2123               cg->print_inlining_late(InliningResult::FAILURE, msg);
2124             }
2125             log_late_inline_failure(cg, msg);
2126           }
2127         }
2128         break; // finish
2129       }
2130     }
2131 
2132     igvn_worklist()->ensure_empty(); // should be done with igvn
2133 
2134     while (inline_incrementally_one()) {
2135       assert(!failing(), "inconsistent");
2136     }
2137     if (failing())  return;
2138 
2139     inline_incrementally_cleanup(igvn);
2140 
2141     print_method(PHASE_INCREMENTAL_INLINE_STEP, 3);
2142 
2143     if (failing())  return;
2144 
2145     if (_late_inlines.length() == 0) {
2146       break; // no more progress
2147     }
2148   }
2149 
2150   igvn_worklist()->ensure_empty(); // should be done with igvn
2151 
2152   if (_string_late_inlines.length() > 0) {
2153     assert(has_stringbuilder(), "inconsistent");
2154 
2155     inline_string_calls(false);
2156 
2157     if (failing())  return;
2158 
2159     inline_incrementally_cleanup(igvn);
2160   }
2161 
2162   set_inlining_incrementally(false);
2163 }
2164 
2165 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2166   // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2167   // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2168   // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2169   // as if "inlining_incrementally() == true" were set.
2170   assert(inlining_incrementally() == false, "not allowed");
2171   assert(_modified_nodes == nullptr, "not allowed");
2172   assert(_late_inlines.length() > 0, "sanity");
2173 
2174   while (_late_inlines.length() > 0) {
2175     igvn_worklist()->ensure_empty(); // should be done with igvn
2176 
2177     while (inline_incrementally_one()) {
2178       assert(!failing(), "inconsistent");
2179     }
2180     if (failing())  return;
2181 
2182     inline_incrementally_cleanup(igvn);
2183   }
2184 }
2185 
2186 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2187   if (_loop_opts_cnt > 0) {
2188     while (major_progress() && (_loop_opts_cnt > 0)) {
2189       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2190       PhaseIdealLoop::optimize(igvn, mode);
2191       _loop_opts_cnt--;
2192       if (failing())  return false;
2193       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2194     }
2195   }
2196   return true;
2197 }
2198 
2199 // Remove edges from "root" to each SafePoint at a backward branch.
2200 // They were inserted during parsing (see add_safepoint()) to make
2201 // infinite loops without calls or exceptions visible to root, i.e.,
2202 // useful.
2203 void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) {
2204   Node *r = root();
2205   if (r != nullptr) {
2206     for (uint i = r->req(); i < r->len(); ++i) {
2207       Node *n = r->in(i);
2208       if (n != nullptr && n->is_SafePoint()) {
2209         r->rm_prec(i);
2210         if (n->outcnt() == 0) {
2211           igvn.remove_dead_node(n);
2212         }
2213         --i;
2214       }
2215     }
2216     // Parsing may have added top inputs to the root node (Path
2217     // leading to the Halt node proven dead). Make sure we get a
2218     // chance to clean them up.
2219     igvn._worklist.push(r);
2220     igvn.optimize();
2221   }
2222 }
2223 
2224 //------------------------------Optimize---------------------------------------
2225 // Given a graph, optimize it.
2226 void Compile::Optimize() {
2227   TracePhase tp("optimizer", &timers[_t_optimizer]);
2228 
2229 #ifndef PRODUCT
2230   if (env()->break_at_compile()) {
2231     BREAKPOINT;
2232   }
2233 
2234 #endif
2235 
2236   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2237 #ifdef ASSERT
2238   bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize);
2239 #endif
2240 
2241   ResourceMark rm;
2242 
2243   print_inlining_reinit();
2244 
2245   NOT_PRODUCT( verify_graph_edges(); )
2246 
2247   print_method(PHASE_AFTER_PARSING, 1);
2248 
2249  {
2250   // Iterative Global Value Numbering, including ideal transforms
2251   // Initialize IterGVN with types and values from parse-time GVN
2252   PhaseIterGVN igvn(initial_gvn());
2253 #ifdef ASSERT
2254   _modified_nodes = new (comp_arena()) Unique_Node_List(comp_arena());
2255 #endif
2256   {
2257     TracePhase tp("iterGVN", &timers[_t_iterGVN]);
2258     igvn.optimize();
2259   }
2260 
2261   if (failing())  return;
2262 
2263   print_method(PHASE_ITER_GVN1, 2);
2264 
2265   process_for_unstable_if_traps(igvn);
2266 
2267   if (failing())  return;
2268 
2269   inline_incrementally(igvn);
2270 
2271   print_method(PHASE_INCREMENTAL_INLINE, 2);
2272 
2273   if (failing())  return;
2274 
2275   if (eliminate_boxing()) {
2276     // Inline valueOf() methods now.
2277     inline_boxing_calls(igvn);
2278 
2279     if (failing())  return;
2280 
2281     if (AlwaysIncrementalInline || StressIncrementalInlining) {
2282       inline_incrementally(igvn);
2283     }
2284 
2285     print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2286 
2287     if (failing())  return;
2288   }
2289 
2290   // Remove the speculative part of types and clean up the graph from
2291   // the extra CastPP nodes whose only purpose is to carry them. Do
2292   // that early so that optimizations are not disrupted by the extra
2293   // CastPP nodes.
2294   remove_speculative_types(igvn);
2295 
2296   if (failing())  return;
2297 
2298   // No more new expensive nodes will be added to the list from here
2299   // so keep only the actual candidates for optimizations.
2300   cleanup_expensive_nodes(igvn);
2301 
2302   if (failing())  return;
2303 
2304   assert(EnableVectorSupport || !has_vbox_nodes(), "sanity");
2305   if (EnableVectorSupport && has_vbox_nodes()) {
2306     TracePhase tp("", &timers[_t_vector]);
2307     PhaseVector pv(igvn);
2308     pv.optimize_vector_boxes();
2309     if (failing())  return;
2310     print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
2311   }
2312   assert(!has_vbox_nodes(), "sanity");
2313 
2314   if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2315     Compile::TracePhase tp("", &timers[_t_renumberLive]);
2316     igvn_worklist()->ensure_empty(); // should be done with igvn
2317     {
2318       ResourceMark rm;
2319       PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
2320     }
2321     igvn.reset_from_gvn(initial_gvn());
2322     igvn.optimize();
2323     if (failing()) return;
2324   }
2325 
2326   // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
2327   // safepoints
2328   remove_root_to_sfpts_edges(igvn);
2329 
2330   if (failing())  return;
2331 
2332   // Perform escape analysis
2333   if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
2334     if (has_loops()) {
2335       // Cleanup graph (remove dead nodes).
2336       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2337       PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2338       if (failing())  return;
2339     }
2340     bool progress;
2341     print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2342     do {
2343       ConnectionGraph::do_analysis(this, &igvn);
2344 
2345       if (failing())  return;
2346 
2347       int mcount = macro_count(); // Record number of allocations and locks before IGVN
2348 
2349       // Optimize out fields loads from scalar replaceable allocations.
2350       igvn.optimize();
2351       print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2352 
2353       if (failing()) return;
2354 
2355       if (congraph() != nullptr && macro_count() > 0) {
2356         TracePhase tp("macroEliminate", &timers[_t_macroEliminate]);
2357         PhaseMacroExpand mexp(igvn);
2358         mexp.eliminate_macro_nodes();
2359         if (failing()) return;
2360 
2361         igvn.set_delay_transform(false);
2362         igvn.optimize();
2363         if (failing()) return;
2364 
2365         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2366       }
2367 
2368       ConnectionGraph::verify_ram_nodes(this, root());
2369       if (failing())  return;
2370 
2371       progress = do_iterative_escape_analysis() &&
2372                  (macro_count() < mcount) &&
2373                  ConnectionGraph::has_candidates(this);
2374       // Try again if candidates exist and made progress
2375       // by removing some allocations and/or locks.
2376     } while (progress);
2377   }
2378 
2379   // Loop transforms on the ideal graph.  Range Check Elimination,
2380   // peeling, unrolling, etc.
2381 
2382   // Set loop opts counter
2383   if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2384     {
2385       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2386       PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
2387       _loop_opts_cnt--;
2388       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2389       if (failing())  return;
2390     }
2391     // Loop opts pass if partial peeling occurred in previous pass
2392     if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
2393       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2394       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2395       _loop_opts_cnt--;
2396       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2397       if (failing())  return;
2398     }
2399     // Loop opts pass for loop-unrolling before CCP
2400     if(major_progress() && (_loop_opts_cnt > 0)) {
2401       TracePhase tp("idealLoop", &timers[_t_idealLoop]);
2402       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2403       _loop_opts_cnt--;
2404       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
2405     }
2406     if (!failing()) {
2407       // Verify that last round of loop opts produced a valid graph
2408       PhaseIdealLoop::verify(igvn);
2409     }
2410   }
2411   if (failing())  return;
2412 
2413   // Conditional Constant Propagation;
2414   print_method(PHASE_BEFORE_CCP1, 2);
2415   PhaseCCP ccp( &igvn );
2416   assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
2417   {
2418     TracePhase tp("ccp", &timers[_t_ccp]);
2419     ccp.do_transform();
2420   }
2421   print_method(PHASE_CCP1, 2);
2422 
2423   assert( true, "Break here to ccp.dump_old2new_map()");
2424 
2425   // Iterative Global Value Numbering, including ideal transforms
2426   {
2427     TracePhase tp("iterGVN2", &timers[_t_iterGVN2]);
2428     igvn.reset_from_igvn(&ccp);
2429     igvn.optimize();
2430   }
2431   print_method(PHASE_ITER_GVN2, 2);
2432 
2433   if (failing())  return;
2434 
2435   // Loop transforms on the ideal graph.  Range Check Elimination,
2436   // peeling, unrolling, etc.
2437   if (!optimize_loops(igvn, LoopOptsDefault)) {
2438     return;
2439   }
2440 
2441   if (failing())  return;
2442 
2443   C->clear_major_progress(); // ensure that major progress is now clear
2444 
2445   process_for_post_loop_opts_igvn(igvn);
2446 
2447   if (failing())  return;
2448 
2449 #ifdef ASSERT
2450   bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
2451 #endif
2452 
2453   {
2454     TracePhase tp("macroExpand", &timers[_t_macroExpand]);
2455     print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);
2456     PhaseMacroExpand  mex(igvn);
2457     if (mex.expand_macro_nodes()) {
2458       assert(failing(), "must bail out w/ explicit message");
2459       return;
2460     }
2461     print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
2462   }
2463 
2464   {
2465     TracePhase tp("barrierExpand", &timers[_t_barrierExpand]);
2466     if (bs->expand_barriers(this, igvn)) {
2467       assert(failing(), "must bail out w/ explicit message");
2468       return;
2469     }
2470     print_method(PHASE_BARRIER_EXPANSION, 2);
2471   }
2472 
2473   if (C->max_vector_size() > 0) {
2474     C->optimize_logic_cones(igvn);
2475     igvn.optimize();
2476     if (failing()) return;
2477   }
2478 
2479   DEBUG_ONLY( _modified_nodes = nullptr; )
2480 
2481   assert(igvn._worklist.size() == 0, "not empty");
2482 
2483   assert(_late_inlines.length() == 0 || IncrementalInlineMH || IncrementalInlineVirtual, "not empty");
2484 
2485   if (_late_inlines.length() > 0) {
2486     // More opportunities to optimize virtual and MH calls.
2487     // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
2488     process_late_inline_calls_no_inline(igvn);
2489     if (failing())  return;
2490   }
2491  } // (End scope of igvn; run destructor if necessary for asserts.)
2492 
2493  check_no_dead_use();
2494 
2495  process_print_inlining();
2496 
2497  // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
2498  // to remove hashes to unlock nodes for modifications.
2499  C->node_hash()->clear();
2500 
2501  // A method with only infinite loops has no edges entering loops from root
2502  {
2503    TracePhase tp("graphReshape", &timers[_t_graphReshaping]);
2504    if (final_graph_reshaping()) {
2505      assert(failing(), "must bail out w/ explicit message");
2506      return;
2507    }
2508  }
2509 
2510  print_method(PHASE_OPTIMIZE_FINISHED, 2);
2511  DEBUG_ONLY(set_phase_optimize_finished();)
2512 }
2513 
2514 #ifdef ASSERT
2515 void Compile::check_no_dead_use() const {
2516   ResourceMark rm;
2517   Unique_Node_List wq;
2518   wq.push(root());
2519   for (uint i = 0; i < wq.size(); ++i) {
2520     Node* n = wq.at(i);
2521     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2522       Node* u = n->fast_out(j);
2523       if (u->outcnt() == 0 && !u->is_Con()) {
2524         u->dump();
2525         fatal("no reachable node should have no use");
2526       }
2527       wq.push(u);
2528     }
2529   }
2530 }
2531 #endif
2532 
2533 void Compile::inline_vector_reboxing_calls() {
2534   if (C->_vector_reboxing_late_inlines.length() > 0) {
2535     _late_inlines_pos = C->_late_inlines.length();
2536     while (_vector_reboxing_late_inlines.length() > 0) {
2537       CallGenerator* cg = _vector_reboxing_late_inlines.pop();
2538       cg->do_late_inline();
2539       if (failing())  return;
2540       print_method(PHASE_INLINE_VECTOR_REBOX, 3, cg->call_node());
2541     }
2542     _vector_reboxing_late_inlines.trunc_to(0);
2543   }
2544 }
2545 
2546 bool Compile::has_vbox_nodes() {
2547   if (C->_vector_reboxing_late_inlines.length() > 0) {
2548     return true;
2549   }
2550   for (int macro_idx = C->macro_count() - 1; macro_idx >= 0; macro_idx--) {
2551     Node * n = C->macro_node(macro_idx);
2552     assert(n->is_macro(), "only macro nodes expected here");
2553     if (n->Opcode() == Op_VectorUnbox || n->Opcode() == Op_VectorBox || n->Opcode() == Op_VectorBoxAllocate) {
2554       return true;
2555     }
2556   }
2557   return false;
2558 }
2559 
2560 //---------------------------- Bitwise operation packing optimization ---------------------------
2561 
2562 static bool is_vector_unary_bitwise_op(Node* n) {
2563   return n->Opcode() == Op_XorV &&
2564          VectorNode::is_vector_bitwise_not_pattern(n);
2565 }
2566 
2567 static bool is_vector_binary_bitwise_op(Node* n) {
2568   switch (n->Opcode()) {
2569     case Op_AndV:
2570     case Op_OrV:
2571       return true;
2572 
2573     case Op_XorV:
2574       return !is_vector_unary_bitwise_op(n);
2575 
2576     default:
2577       return false;
2578   }
2579 }
2580 
2581 static bool is_vector_ternary_bitwise_op(Node* n) {
2582   return n->Opcode() == Op_MacroLogicV;
2583 }
2584 
2585 static bool is_vector_bitwise_op(Node* n) {
2586   return is_vector_unary_bitwise_op(n)  ||
2587          is_vector_binary_bitwise_op(n) ||
2588          is_vector_ternary_bitwise_op(n);
2589 }
2590 
2591 static bool is_vector_bitwise_cone_root(Node* n) {
2592   if (n->bottom_type()->isa_vectmask() || !is_vector_bitwise_op(n)) {
2593     return false;
2594   }
2595   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2596     if (is_vector_bitwise_op(n->fast_out(i))) {
2597       return false;
2598     }
2599   }
2600   return true;
2601 }
2602 
2603 static uint collect_unique_inputs(Node* n, Unique_Node_List& inputs) {
2604   uint cnt = 0;
2605   if (is_vector_bitwise_op(n)) {
2606     uint inp_cnt = n->is_predicated_vector() ? n->req()-1 : n->req();
2607     if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2608       for (uint i = 1; i < inp_cnt; i++) {
2609         Node* in = n->in(i);
2610         bool skip = VectorNode::is_all_ones_vector(in);
2611         if (!skip && !inputs.member(in)) {
2612           inputs.push(in);
2613           cnt++;
2614         }
2615       }
2616       assert(cnt <= 1, "not unary");
2617     } else {
2618       uint last_req = inp_cnt;
2619       if (is_vector_ternary_bitwise_op(n)) {
2620         last_req = inp_cnt - 1; // skip last input
2621       }
2622       for (uint i = 1; i < last_req; i++) {
2623         Node* def = n->in(i);
2624         if (!inputs.member(def)) {
2625           inputs.push(def);
2626           cnt++;
2627         }
2628       }
2629     }
2630   } else { // not a bitwise operations
2631     if (!inputs.member(n)) {
2632       inputs.push(n);
2633       cnt++;
2634     }
2635   }
2636   return cnt;
2637 }
2638 
2639 void Compile::collect_logic_cone_roots(Unique_Node_List& list) {
2640   Unique_Node_List useful_nodes;
2641   C->identify_useful_nodes(useful_nodes);
2642 
2643   for (uint i = 0; i < useful_nodes.size(); i++) {
2644     Node* n = useful_nodes.at(i);
2645     if (is_vector_bitwise_cone_root(n)) {
2646       list.push(n);
2647     }
2648   }
2649 }
2650 
2651 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn,
2652                                     const TypeVect* vt,
2653                                     Unique_Node_List& partition,
2654                                     Unique_Node_List& inputs) {
2655   assert(partition.size() == 2 || partition.size() == 3, "not supported");
2656   assert(inputs.size()    == 2 || inputs.size()    == 3, "not supported");
2657   assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported");
2658 
2659   Node* in1 = inputs.at(0);
2660   Node* in2 = inputs.at(1);
2661   Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2);
2662 
2663   uint func = compute_truth_table(partition, inputs);
2664 
2665   Node* pn = partition.at(partition.size() - 1);
2666   Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr;
2667   return igvn.transform(MacroLogicVNode::make(igvn, in1, in2, in3, mask, func, vt));
2668 }
2669 
2670 static uint extract_bit(uint func, uint pos) {
2671   return (func & (1 << pos)) >> pos;
2672 }
2673 
2674 //
2675 //  A macro logic node represents a truth table. It has 4 inputs,
2676 //  First three inputs corresponds to 3 columns of a truth table
2677 //  and fourth input captures the logic function.
2678 //
2679 //  eg.  fn = (in1 AND in2) OR in3;
2680 //
2681 //      MacroNode(in1,in2,in3,fn)
2682 //
2683 //  -----------------
2684 //  in1 in2 in3  fn
2685 //  -----------------
2686 //  0    0   0    0
2687 //  0    0   1    1
2688 //  0    1   0    0
2689 //  0    1   1    1
2690 //  1    0   0    0
2691 //  1    0   1    1
2692 //  1    1   0    1
2693 //  1    1   1    1
2694 //
2695 
2696 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) {
2697   int res = 0;
2698   for (int i = 0; i < 8; i++) {
2699     int bit1 = extract_bit(in1, i);
2700     int bit2 = extract_bit(in2, i);
2701     int bit3 = extract_bit(in3, i);
2702 
2703     int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3);
2704     int func_bit = extract_bit(func, func_bit_pos);
2705 
2706     res |= func_bit << i;
2707   }
2708   return res;
2709 }
2710 
2711 static uint eval_operand(Node* n, ResourceHashtable<Node*,uint>& eval_map) {
2712   assert(n != nullptr, "");
2713   assert(eval_map.contains(n), "absent");
2714   return *(eval_map.get(n));
2715 }
2716 
2717 static void eval_operands(Node* n,
2718                           uint& func1, uint& func2, uint& func3,
2719                           ResourceHashtable<Node*,uint>& eval_map) {
2720   assert(is_vector_bitwise_op(n), "");
2721 
2722   if (is_vector_unary_bitwise_op(n)) {
2723     Node* opnd = n->in(1);
2724     if (VectorNode::is_vector_bitwise_not_pattern(n) && VectorNode::is_all_ones_vector(opnd)) {
2725       opnd = n->in(2);
2726     }
2727     func1 = eval_operand(opnd, eval_map);
2728   } else if (is_vector_binary_bitwise_op(n)) {
2729     func1 = eval_operand(n->in(1), eval_map);
2730     func2 = eval_operand(n->in(2), eval_map);
2731   } else {
2732     assert(is_vector_ternary_bitwise_op(n), "unknown operation");
2733     func1 = eval_operand(n->in(1), eval_map);
2734     func2 = eval_operand(n->in(2), eval_map);
2735     func3 = eval_operand(n->in(3), eval_map);
2736   }
2737 }
2738 
2739 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) {
2740   assert(inputs.size() <= 3, "sanity");
2741   ResourceMark rm;
2742   uint res = 0;
2743   ResourceHashtable<Node*,uint> eval_map;
2744 
2745   // Populate precomputed functions for inputs.
2746   // Each input corresponds to one column of 3 input truth-table.
2747   uint input_funcs[] = { 0xAA,   // (_, _, c) -> c
2748                          0xCC,   // (_, b, _) -> b
2749                          0xF0 }; // (a, _, _) -> a
2750   for (uint i = 0; i < inputs.size(); i++) {
2751     eval_map.put(inputs.at(i), input_funcs[2-i]);
2752   }
2753 
2754   for (uint i = 0; i < partition.size(); i++) {
2755     Node* n = partition.at(i);
2756 
2757     uint func1 = 0, func2 = 0, func3 = 0;
2758     eval_operands(n, func1, func2, func3, eval_map);
2759 
2760     switch (n->Opcode()) {
2761       case Op_OrV:
2762         assert(func3 == 0, "not binary");
2763         res = func1 | func2;
2764         break;
2765       case Op_AndV:
2766         assert(func3 == 0, "not binary");
2767         res = func1 & func2;
2768         break;
2769       case Op_XorV:
2770         if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2771           assert(func2 == 0 && func3 == 0, "not unary");
2772           res = (~func1) & 0xFF;
2773         } else {
2774           assert(func3 == 0, "not binary");
2775           res = func1 ^ func2;
2776         }
2777         break;
2778       case Op_MacroLogicV:
2779         // Ordering of inputs may change during evaluation of sub-tree
2780         // containing MacroLogic node as a child node, thus a re-evaluation
2781         // makes sure that function is evaluated in context of current
2782         // inputs.
2783         res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3);
2784         break;
2785 
2786       default: assert(false, "not supported: %s", n->Name());
2787     }
2788     assert(res <= 0xFF, "invalid");
2789     eval_map.put(n, res);
2790   }
2791   return res;
2792 }
2793 
2794 // Criteria under which nodes gets packed into a macro logic node:-
2795 //  1) Parent and both child nodes are all unmasked or masked with
2796 //     same predicates.
2797 //  2) Masked parent can be packed with left child if it is predicated
2798 //     and both have same predicates.
2799 //  3) Masked parent can be packed with right child if its un-predicated
2800 //     or has matching predication condition.
2801 //  4) An unmasked parent can be packed with an unmasked child.
2802 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
2803   assert(partition.size() == 0, "not empty");
2804   assert(inputs.size() == 0, "not empty");
2805   if (is_vector_ternary_bitwise_op(n)) {
2806     return false;
2807   }
2808 
2809   bool is_unary_op = is_vector_unary_bitwise_op(n);
2810   if (is_unary_op) {
2811     assert(collect_unique_inputs(n, inputs) == 1, "not unary");
2812     return false; // too few inputs
2813   }
2814 
2815   bool pack_left_child = true;
2816   bool pack_right_child = true;
2817 
2818   bool left_child_LOP = is_vector_bitwise_op(n->in(1));
2819   bool right_child_LOP = is_vector_bitwise_op(n->in(2));
2820 
2821   int left_child_input_cnt = 0;
2822   int right_child_input_cnt = 0;
2823 
2824   bool parent_is_predicated = n->is_predicated_vector();
2825   bool left_child_predicated = n->in(1)->is_predicated_vector();
2826   bool right_child_predicated = n->in(2)->is_predicated_vector();
2827 
2828   Node* parent_pred = parent_is_predicated ? n->in(n->req()-1) : nullptr;
2829   Node* left_child_pred = left_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr;
2830   Node* right_child_pred = right_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr;
2831 
2832   do {
2833     if (pack_left_child && left_child_LOP &&
2834         ((!parent_is_predicated && !left_child_predicated) ||
2835         ((parent_is_predicated && left_child_predicated &&
2836           parent_pred == left_child_pred)))) {
2837        partition.push(n->in(1));
2838        left_child_input_cnt = collect_unique_inputs(n->in(1), inputs);
2839     } else {
2840        inputs.push(n->in(1));
2841        left_child_input_cnt = 1;
2842     }
2843 
2844     if (pack_right_child && right_child_LOP &&
2845         (!right_child_predicated ||
2846          (right_child_predicated && parent_is_predicated &&
2847           parent_pred == right_child_pred))) {
2848        partition.push(n->in(2));
2849        right_child_input_cnt = collect_unique_inputs(n->in(2), inputs);
2850     } else {
2851        inputs.push(n->in(2));
2852        right_child_input_cnt = 1;
2853     }
2854 
2855     if (inputs.size() > 3) {
2856       assert(partition.size() > 0, "");
2857       inputs.clear();
2858       partition.clear();
2859       if (left_child_input_cnt > right_child_input_cnt) {
2860         pack_left_child = false;
2861       } else {
2862         pack_right_child = false;
2863       }
2864     } else {
2865       break;
2866     }
2867   } while(true);
2868 
2869   if(partition.size()) {
2870     partition.push(n);
2871   }
2872 
2873   return (partition.size() == 2 || partition.size() == 3) &&
2874          (inputs.size()    == 2 || inputs.size()    == 3);
2875 }
2876 
2877 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) {
2878   assert(is_vector_bitwise_op(n), "not a root");
2879 
2880   visited.set(n->_idx);
2881 
2882   // 1) Do a DFS walk over the logic cone.
2883   for (uint i = 1; i < n->req(); i++) {
2884     Node* in = n->in(i);
2885     if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) {
2886       process_logic_cone_root(igvn, in, visited);
2887     }
2888   }
2889 
2890   // 2) Bottom up traversal: Merge node[s] with
2891   // the parent to form macro logic node.
2892   Unique_Node_List partition;
2893   Unique_Node_List inputs;
2894   if (compute_logic_cone(n, partition, inputs)) {
2895     const TypeVect* vt = n->bottom_type()->is_vect();
2896     Node* pn = partition.at(partition.size() - 1);
2897     Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr;
2898     if (mask == nullptr ||
2899         Matcher::match_rule_supported_vector_masked(Op_MacroLogicV, vt->length(), vt->element_basic_type())) {
2900       Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs);
2901       VectorNode::trace_new_vector(macro_logic, "MacroLogic");
2902       igvn.replace_node(n, macro_logic);
2903     }
2904   }
2905 }
2906 
2907 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) {
2908   ResourceMark rm;
2909   if (Matcher::match_rule_supported(Op_MacroLogicV)) {
2910     Unique_Node_List list;
2911     collect_logic_cone_roots(list);
2912 
2913     while (list.size() > 0) {
2914       Node* n = list.pop();
2915       const TypeVect* vt = n->bottom_type()->is_vect();
2916       bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type());
2917       if (supported) {
2918         VectorSet visited(comp_arena());
2919         process_logic_cone_root(igvn, n, visited);
2920       }
2921     }
2922   }
2923 }
2924 
2925 //------------------------------Code_Gen---------------------------------------
2926 // Given a graph, generate code for it
2927 void Compile::Code_Gen() {
2928   if (failing()) {
2929     return;
2930   }
2931 
2932   // Perform instruction selection.  You might think we could reclaim Matcher
2933   // memory PDQ, but actually the Matcher is used in generating spill code.
2934   // Internals of the Matcher (including some VectorSets) must remain live
2935   // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2936   // set a bit in reclaimed memory.
2937 
2938   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2939   // nodes.  Mapping is only valid at the root of each matched subtree.
2940   NOT_PRODUCT( verify_graph_edges(); )
2941 
2942   Matcher matcher;
2943   _matcher = &matcher;
2944   {
2945     TracePhase tp("matcher", &timers[_t_matcher]);
2946     matcher.match();
2947     if (failing()) {
2948       return;
2949     }
2950   }
2951   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2952   // nodes.  Mapping is only valid at the root of each matched subtree.
2953   NOT_PRODUCT( verify_graph_edges(); )
2954 
2955   // If you have too many nodes, or if matching has failed, bail out
2956   check_node_count(0, "out of nodes matching instructions");
2957   if (failing()) {
2958     return;
2959   }
2960 
2961   print_method(PHASE_MATCHING, 2);
2962 
2963   // Build a proper-looking CFG
2964   PhaseCFG cfg(node_arena(), root(), matcher);
2965   _cfg = &cfg;
2966   {
2967     TracePhase tp("scheduler", &timers[_t_scheduler]);
2968     bool success = cfg.do_global_code_motion();
2969     if (!success) {
2970       return;
2971     }
2972 
2973     print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2974     NOT_PRODUCT( verify_graph_edges(); )
2975     cfg.verify();
2976   }
2977 
2978   PhaseChaitin regalloc(unique(), cfg, matcher, false);
2979   _regalloc = &regalloc;
2980   {
2981     TracePhase tp("regalloc", &timers[_t_registerAllocation]);
2982     // Perform register allocation.  After Chaitin, use-def chains are
2983     // no longer accurate (at spill code) and so must be ignored.
2984     // Node->LRG->reg mappings are still accurate.
2985     _regalloc->Register_Allocate();
2986 
2987     // Bail out if the allocator builds too many nodes
2988     if (failing()) {
2989       return;
2990     }
2991 
2992     print_method(PHASE_REGISTER_ALLOCATION, 2);
2993   }
2994 
2995   // Prior to register allocation we kept empty basic blocks in case the
2996   // the allocator needed a place to spill.  After register allocation we
2997   // are not adding any new instructions.  If any basic block is empty, we
2998   // can now safely remove it.
2999   {
3000     TracePhase tp("blockOrdering", &timers[_t_blockOrdering]);
3001     cfg.remove_empty_blocks();
3002     if (do_freq_based_layout()) {
3003       PhaseBlockLayout layout(cfg);
3004     } else {
3005       cfg.set_loop_alignment();
3006     }
3007     cfg.fixup_flow();
3008     cfg.remove_unreachable_blocks();
3009     cfg.verify_dominator_tree();
3010     print_method(PHASE_BLOCK_ORDERING, 3);
3011   }
3012 
3013   // Apply peephole optimizations
3014   if( OptoPeephole ) {
3015     TracePhase tp("peephole", &timers[_t_peephole]);
3016     PhasePeephole peep( _regalloc, cfg);
3017     peep.do_transform();
3018     print_method(PHASE_PEEPHOLE, 3);
3019   }
3020 
3021   // Do late expand if CPU requires this.
3022   if (Matcher::require_postalloc_expand) {
3023     TracePhase tp("postalloc_expand", &timers[_t_postalloc_expand]);
3024     cfg.postalloc_expand(_regalloc);
3025     print_method(PHASE_POSTALLOC_EXPAND, 3);
3026   }
3027 
3028   // Convert Nodes to instruction bits in a buffer
3029   {
3030     TracePhase tp("output", &timers[_t_output]);
3031     PhaseOutput output;
3032     output.Output();
3033     if (failing())  return;
3034     output.install();
3035     print_method(PHASE_FINAL_CODE, 1); // Compile::_output is not null here
3036   }
3037 
3038   // He's dead, Jim.
3039   _cfg     = (PhaseCFG*)((intptr_t)0xdeadbeef);
3040   _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
3041 }
3042 
3043 //------------------------------Final_Reshape_Counts---------------------------
3044 // This class defines counters to help identify when a method
3045 // may/must be executed using hardware with only 24-bit precision.
3046 struct Final_Reshape_Counts : public StackObj {
3047   int  _call_count;             // count non-inlined 'common' calls
3048   int  _float_count;            // count float ops requiring 24-bit precision
3049   int  _double_count;           // count double ops requiring more precision
3050   int  _java_call_count;        // count non-inlined 'java' calls
3051   int  _inner_loop_count;       // count loops which need alignment
3052   VectorSet _visited;           // Visitation flags
3053   Node_List _tests;             // Set of IfNodes & PCTableNodes
3054 
3055   Final_Reshape_Counts() :
3056     _call_count(0), _float_count(0), _double_count(0),
3057     _java_call_count(0), _inner_loop_count(0) { }
3058 
3059   void inc_call_count  () { _call_count  ++; }
3060   void inc_float_count () { _float_count ++; }
3061   void inc_double_count() { _double_count++; }
3062   void inc_java_call_count() { _java_call_count++; }
3063   void inc_inner_loop_count() { _inner_loop_count++; }
3064 
3065   int  get_call_count  () const { return _call_count  ; }
3066   int  get_float_count () const { return _float_count ; }
3067   int  get_double_count() const { return _double_count; }
3068   int  get_java_call_count() const { return _java_call_count; }
3069   int  get_inner_loop_count() const { return _inner_loop_count; }
3070 };
3071 
3072 // Eliminate trivially redundant StoreCMs and accumulate their
3073 // precedence edges.
3074 void Compile::eliminate_redundant_card_marks(Node* n) {
3075   assert(n->Opcode() == Op_StoreCM, "expected StoreCM");
3076   if (n->in(MemNode::Address)->outcnt() > 1) {
3077     // There are multiple users of the same address so it might be
3078     // possible to eliminate some of the StoreCMs
3079     Node* mem = n->in(MemNode::Memory);
3080     Node* adr = n->in(MemNode::Address);
3081     Node* val = n->in(MemNode::ValueIn);
3082     Node* prev = n;
3083     bool done = false;
3084     // Walk the chain of StoreCMs eliminating ones that match.  As
3085     // long as it's a chain of single users then the optimization is
3086     // safe.  Eliminating partially redundant StoreCMs would require
3087     // cloning copies down the other paths.
3088     while (mem->Opcode() == Op_StoreCM && mem->outcnt() == 1 && !done) {
3089       if (adr == mem->in(MemNode::Address) &&
3090           val == mem->in(MemNode::ValueIn)) {
3091         // redundant StoreCM
3092         if (mem->req() > MemNode::OopStore) {
3093           // Hasn't been processed by this code yet.
3094           n->add_prec(mem->in(MemNode::OopStore));
3095         } else {
3096           // Already converted to precedence edge
3097           for (uint i = mem->req(); i < mem->len(); i++) {
3098             // Accumulate any precedence edges
3099             if (mem->in(i) != nullptr) {
3100               n->add_prec(mem->in(i));
3101             }
3102           }
3103           // Everything above this point has been processed.
3104           done = true;
3105         }
3106         // Eliminate the previous StoreCM
3107         prev->set_req(MemNode::Memory, mem->in(MemNode::Memory));
3108         assert(mem->outcnt() == 0, "should be dead");
3109         mem->disconnect_inputs(this);
3110       } else {
3111         prev = mem;
3112       }
3113       mem = prev->in(MemNode::Memory);
3114     }
3115   }
3116 }
3117 
3118 //------------------------------final_graph_reshaping_impl----------------------
3119 // Implement items 1-5 from final_graph_reshaping below.
3120 void Compile::final_graph_reshaping_impl(Node *n, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3121 
3122   if ( n->outcnt() == 0 ) return; // dead node
3123   uint nop = n->Opcode();
3124 
3125   // Check for 2-input instruction with "last use" on right input.
3126   // Swap to left input.  Implements item (2).
3127   if( n->req() == 3 &&          // two-input instruction
3128       n->in(1)->outcnt() > 1 && // left use is NOT a last use
3129       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
3130       n->in(2)->outcnt() == 1 &&// right use IS a last use
3131       !n->in(2)->is_Con() ) {   // right use is not a constant
3132     // Check for commutative opcode
3133     switch( nop ) {
3134     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
3135     case Op_MaxI:  case Op_MaxL:  case Op_MaxF:  case Op_MaxD:
3136     case Op_MinI:  case Op_MinL:  case Op_MinF:  case Op_MinD:
3137     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
3138     case Op_AndL:  case Op_XorL:  case Op_OrL:
3139     case Op_AndI:  case Op_XorI:  case Op_OrI: {
3140       // Move "last use" input to left by swapping inputs
3141       n->swap_edges(1, 2);
3142       break;
3143     }
3144     default:
3145       break;
3146     }
3147   }
3148 
3149 #ifdef ASSERT
3150   if( n->is_Mem() ) {
3151     int alias_idx = get_alias_index(n->as_Mem()->adr_type());
3152     assert( n->in(0) != nullptr || alias_idx != Compile::AliasIdxRaw ||
3153             // oop will be recorded in oop map if load crosses safepoint
3154             (n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
3155                               LoadNode::is_immutable_value(n->in(MemNode::Address)))),
3156             "raw memory operations should have control edge");
3157   }
3158   if (n->is_MemBar()) {
3159     MemBarNode* mb = n->as_MemBar();
3160     if (mb->trailing_store() || mb->trailing_load_store()) {
3161       assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
3162       Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent));
3163       assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
3164              (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
3165     } else if (mb->leading()) {
3166       assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
3167     }
3168   }
3169 #endif
3170   // Count FPU ops and common calls, implements item (3)
3171   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop, dead_nodes);
3172   if (!gc_handled) {
3173     final_graph_reshaping_main_switch(n, frc, nop, dead_nodes);
3174   }
3175 
3176   // Collect CFG split points
3177   if (n->is_MultiBranch() && !n->is_RangeCheck()) {
3178     frc._tests.push(n);
3179   }
3180 }
3181 
3182 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
3183   switch( nop ) {
3184   // Count all float operations that may use FPU
3185   case Op_AddF:
3186   case Op_SubF:
3187   case Op_MulF:
3188   case Op_DivF:
3189   case Op_NegF:
3190   case Op_ModF:
3191   case Op_ConvI2F:
3192   case Op_ConF:
3193   case Op_CmpF:
3194   case Op_CmpF3:
3195   case Op_StoreF:
3196   case Op_LoadF:
3197   // case Op_ConvL2F: // longs are split into 32-bit halves
3198     frc.inc_float_count();
3199     break;
3200 
3201   case Op_ConvF2D:
3202   case Op_ConvD2F:
3203     frc.inc_float_count();
3204     frc.inc_double_count();
3205     break;
3206 
3207   // Count all double operations that may use FPU
3208   case Op_AddD:
3209   case Op_SubD:
3210   case Op_MulD:
3211   case Op_DivD:
3212   case Op_NegD:
3213   case Op_ModD:
3214   case Op_ConvI2D:
3215   case Op_ConvD2I:
3216   // case Op_ConvL2D: // handled by leaf call
3217   // case Op_ConvD2L: // handled by leaf call
3218   case Op_ConD:
3219   case Op_CmpD:
3220   case Op_CmpD3:
3221   case Op_StoreD:
3222   case Op_LoadD:
3223   case Op_LoadD_unaligned:
3224     frc.inc_double_count();
3225     break;
3226   case Op_Opaque1:              // Remove Opaque Nodes before matching
3227   case Op_Opaque3:
3228     n->subsume_by(n->in(1), this);
3229     break;
3230   case Op_CallStaticJava:
3231   case Op_CallJava:
3232   case Op_CallDynamicJava:
3233     frc.inc_java_call_count(); // Count java call site;
3234   case Op_CallRuntime:
3235   case Op_CallLeaf:
3236   case Op_CallLeafVector:
3237   case Op_CallLeafNoFP: {
3238     assert (n->is_Call(), "");
3239     CallNode *call = n->as_Call();
3240     // Count call sites where the FP mode bit would have to be flipped.
3241     // Do not count uncommon runtime calls:
3242     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
3243     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
3244     if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
3245       frc.inc_call_count();   // Count the call site
3246     } else {                  // See if uncommon argument is shared
3247       Node *n = call->in(TypeFunc::Parms);
3248       int nop = n->Opcode();
3249       // Clone shared simple arguments to uncommon calls, item (1).
3250       if (n->outcnt() > 1 &&
3251           !n->is_Proj() &&
3252           nop != Op_CreateEx &&
3253           nop != Op_CheckCastPP &&
3254           nop != Op_DecodeN &&
3255           nop != Op_DecodeNKlass &&
3256           !n->is_Mem() &&
3257           !n->is_Phi()) {
3258         Node *x = n->clone();
3259         call->set_req(TypeFunc::Parms, x);
3260       }
3261     }
3262     break;
3263   }
3264 
3265   case Op_StoreCM:
3266     {
3267       // Convert OopStore dependence into precedence edge
3268       Node* prec = n->in(MemNode::OopStore);
3269       n->del_req(MemNode::OopStore);
3270       n->add_prec(prec);
3271       eliminate_redundant_card_marks(n);
3272     }
3273 
3274     // fall through
3275 
3276   case Op_StoreB:
3277   case Op_StoreC:
3278   case Op_StoreI:
3279   case Op_StoreL:
3280   case Op_CompareAndSwapB:
3281   case Op_CompareAndSwapS:
3282   case Op_CompareAndSwapI:
3283   case Op_CompareAndSwapL:
3284   case Op_CompareAndSwapP:
3285   case Op_CompareAndSwapN:
3286   case Op_WeakCompareAndSwapB:
3287   case Op_WeakCompareAndSwapS:
3288   case Op_WeakCompareAndSwapI:
3289   case Op_WeakCompareAndSwapL:
3290   case Op_WeakCompareAndSwapP:
3291   case Op_WeakCompareAndSwapN:
3292   case Op_CompareAndExchangeB:
3293   case Op_CompareAndExchangeS:
3294   case Op_CompareAndExchangeI:
3295   case Op_CompareAndExchangeL:
3296   case Op_CompareAndExchangeP:
3297   case Op_CompareAndExchangeN:
3298   case Op_GetAndAddS:
3299   case Op_GetAndAddB:
3300   case Op_GetAndAddI:
3301   case Op_GetAndAddL:
3302   case Op_GetAndSetS:
3303   case Op_GetAndSetB:
3304   case Op_GetAndSetI:
3305   case Op_GetAndSetL:
3306   case Op_GetAndSetP:
3307   case Op_GetAndSetN:
3308   case Op_StoreP:
3309   case Op_StoreN:
3310   case Op_StoreNKlass:
3311   case Op_LoadB:
3312   case Op_LoadUB:
3313   case Op_LoadUS:
3314   case Op_LoadI:
3315   case Op_LoadKlass:
3316   case Op_LoadNKlass:
3317   case Op_LoadL:
3318   case Op_LoadL_unaligned:
3319   case Op_LoadP:
3320   case Op_LoadN:
3321   case Op_LoadRange:
3322   case Op_LoadS:
3323     break;
3324 
3325   case Op_AddP: {               // Assert sane base pointers
3326     Node *addp = n->in(AddPNode::Address);
3327     assert( !addp->is_AddP() ||
3328             addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
3329             addp->in(AddPNode::Base) == n->in(AddPNode::Base),
3330             "Base pointers must match (addp %u)", addp->_idx );
3331 #ifdef _LP64
3332     if ((UseCompressedOops || UseCompressedClassPointers) &&
3333         addp->Opcode() == Op_ConP &&
3334         addp == n->in(AddPNode::Base) &&
3335         n->in(AddPNode::Offset)->is_Con()) {
3336       // If the transformation of ConP to ConN+DecodeN is beneficial depends
3337       // on the platform and on the compressed oops mode.
3338       // Use addressing with narrow klass to load with offset on x86.
3339       // Some platforms can use the constant pool to load ConP.
3340       // Do this transformation here since IGVN will convert ConN back to ConP.
3341       const Type* t = addp->bottom_type();
3342       bool is_oop   = t->isa_oopptr() != nullptr;
3343       bool is_klass = t->isa_klassptr() != nullptr;
3344 
3345       if ((is_oop   && Matcher::const_oop_prefer_decode()  ) ||
3346           (is_klass && Matcher::const_klass_prefer_decode())) {
3347         Node* nn = nullptr;
3348 
3349         int op = is_oop ? Op_ConN : Op_ConNKlass;
3350 
3351         // Look for existing ConN node of the same exact type.
3352         Node* r  = root();
3353         uint cnt = r->outcnt();
3354         for (uint i = 0; i < cnt; i++) {
3355           Node* m = r->raw_out(i);
3356           if (m!= nullptr && m->Opcode() == op &&
3357               m->bottom_type()->make_ptr() == t) {
3358             nn = m;
3359             break;
3360           }
3361         }
3362         if (nn != nullptr) {
3363           // Decode a narrow oop to match address
3364           // [R12 + narrow_oop_reg<<3 + offset]
3365           if (is_oop) {
3366             nn = new DecodeNNode(nn, t);
3367           } else {
3368             nn = new DecodeNKlassNode(nn, t);
3369           }
3370           // Check for succeeding AddP which uses the same Base.
3371           // Otherwise we will run into the assertion above when visiting that guy.
3372           for (uint i = 0; i < n->outcnt(); ++i) {
3373             Node *out_i = n->raw_out(i);
3374             if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
3375               out_i->set_req(AddPNode::Base, nn);
3376 #ifdef ASSERT
3377               for (uint j = 0; j < out_i->outcnt(); ++j) {
3378                 Node *out_j = out_i->raw_out(j);
3379                 assert(out_j == nullptr || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
3380                        "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
3381               }
3382 #endif
3383             }
3384           }
3385           n->set_req(AddPNode::Base, nn);
3386           n->set_req(AddPNode::Address, nn);
3387           if (addp->outcnt() == 0) {
3388             addp->disconnect_inputs(this);
3389           }
3390         }
3391       }
3392     }
3393 #endif
3394     break;
3395   }
3396 
3397   case Op_CastPP: {
3398     // Remove CastPP nodes to gain more freedom during scheduling but
3399     // keep the dependency they encode as control or precedence edges
3400     // (if control is set already) on memory operations. Some CastPP
3401     // nodes don't have a control (don't carry a dependency): skip
3402     // those.
3403     if (n->in(0) != nullptr) {
3404       ResourceMark rm;
3405       Unique_Node_List wq;
3406       wq.push(n);
3407       for (uint next = 0; next < wq.size(); ++next) {
3408         Node *m = wq.at(next);
3409         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3410           Node* use = m->fast_out(i);
3411           if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
3412             use->ensure_control_or_add_prec(n->in(0));
3413           } else {
3414             switch(use->Opcode()) {
3415             case Op_AddP:
3416             case Op_DecodeN:
3417             case Op_DecodeNKlass:
3418             case Op_CheckCastPP:
3419             case Op_CastPP:
3420               wq.push(use);
3421               break;
3422             }
3423           }
3424         }
3425       }
3426     }
3427     const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
3428     if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
3429       Node* in1 = n->in(1);
3430       const Type* t = n->bottom_type();
3431       Node* new_in1 = in1->clone();
3432       new_in1->as_DecodeN()->set_type(t);
3433 
3434       if (!Matcher::narrow_oop_use_complex_address()) {
3435         //
3436         // x86, ARM and friends can handle 2 adds in addressing mode
3437         // and Matcher can fold a DecodeN node into address by using
3438         // a narrow oop directly and do implicit null check in address:
3439         //
3440         // [R12 + narrow_oop_reg<<3 + offset]
3441         // NullCheck narrow_oop_reg
3442         //
3443         // On other platforms (Sparc) we have to keep new DecodeN node and
3444         // use it to do implicit null check in address:
3445         //
3446         // decode_not_null narrow_oop_reg, base_reg
3447         // [base_reg + offset]
3448         // NullCheck base_reg
3449         //
3450         // Pin the new DecodeN node to non-null path on these platform (Sparc)
3451         // to keep the information to which null check the new DecodeN node
3452         // corresponds to use it as value in implicit_null_check().
3453         //
3454         new_in1->set_req(0, n->in(0));
3455       }
3456 
3457       n->subsume_by(new_in1, this);
3458       if (in1->outcnt() == 0) {
3459         in1->disconnect_inputs(this);
3460       }
3461     } else {
3462       n->subsume_by(n->in(1), this);
3463       if (n->outcnt() == 0) {
3464         n->disconnect_inputs(this);
3465       }
3466     }
3467     break;
3468   }
3469 #ifdef _LP64
3470   case Op_CmpP:
3471     // Do this transformation here to preserve CmpPNode::sub() and
3472     // other TypePtr related Ideal optimizations (for example, ptr nullness).
3473     if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
3474       Node* in1 = n->in(1);
3475       Node* in2 = n->in(2);
3476       if (!in1->is_DecodeNarrowPtr()) {
3477         in2 = in1;
3478         in1 = n->in(2);
3479       }
3480       assert(in1->is_DecodeNarrowPtr(), "sanity");
3481 
3482       Node* new_in2 = nullptr;
3483       if (in2->is_DecodeNarrowPtr()) {
3484         assert(in2->Opcode() == in1->Opcode(), "must be same node type");
3485         new_in2 = in2->in(1);
3486       } else if (in2->Opcode() == Op_ConP) {
3487         const Type* t = in2->bottom_type();
3488         if (t == TypePtr::NULL_PTR) {
3489           assert(in1->is_DecodeN(), "compare klass to null?");
3490           // Don't convert CmpP null check into CmpN if compressed
3491           // oops implicit null check is not generated.
3492           // This will allow to generate normal oop implicit null check.
3493           if (Matcher::gen_narrow_oop_implicit_null_checks())
3494             new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
3495           //
3496           // This transformation together with CastPP transformation above
3497           // will generated code for implicit null checks for compressed oops.
3498           //
3499           // The original code after Optimize()
3500           //
3501           //    LoadN memory, narrow_oop_reg
3502           //    decode narrow_oop_reg, base_reg
3503           //    CmpP base_reg, nullptr
3504           //    CastPP base_reg // NotNull
3505           //    Load [base_reg + offset], val_reg
3506           //
3507           // after these transformations will be
3508           //
3509           //    LoadN memory, narrow_oop_reg
3510           //    CmpN narrow_oop_reg, nullptr
3511           //    decode_not_null narrow_oop_reg, base_reg
3512           //    Load [base_reg + offset], val_reg
3513           //
3514           // and the uncommon path (== nullptr) will use narrow_oop_reg directly
3515           // since narrow oops can be used in debug info now (see the code in
3516           // final_graph_reshaping_walk()).
3517           //
3518           // At the end the code will be matched to
3519           // on x86:
3520           //
3521           //    Load_narrow_oop memory, narrow_oop_reg
3522           //    Load [R12 + narrow_oop_reg<<3 + offset], val_reg
3523           //    NullCheck narrow_oop_reg
3524           //
3525           // and on sparc:
3526           //
3527           //    Load_narrow_oop memory, narrow_oop_reg
3528           //    decode_not_null narrow_oop_reg, base_reg
3529           //    Load [base_reg + offset], val_reg
3530           //    NullCheck base_reg
3531           //
3532         } else if (t->isa_oopptr()) {
3533           new_in2 = ConNode::make(t->make_narrowoop());
3534         } else if (t->isa_klassptr()) {
3535           new_in2 = ConNode::make(t->make_narrowklass());
3536         }
3537       }
3538       if (new_in2 != nullptr) {
3539         Node* cmpN = new CmpNNode(in1->in(1), new_in2);
3540         n->subsume_by(cmpN, this);
3541         if (in1->outcnt() == 0) {
3542           in1->disconnect_inputs(this);
3543         }
3544         if (in2->outcnt() == 0) {
3545           in2->disconnect_inputs(this);
3546         }
3547       }
3548     }
3549     break;
3550 
3551   case Op_DecodeN:
3552   case Op_DecodeNKlass:
3553     assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3554     // DecodeN could be pinned when it can't be fold into
3555     // an address expression, see the code for Op_CastPP above.
3556     assert(n->in(0) == nullptr || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3557     break;
3558 
3559   case Op_EncodeP:
3560   case Op_EncodePKlass: {
3561     Node* in1 = n->in(1);
3562     if (in1->is_DecodeNarrowPtr()) {
3563       n->subsume_by(in1->in(1), this);
3564     } else if (in1->Opcode() == Op_ConP) {
3565       const Type* t = in1->bottom_type();
3566       if (t == TypePtr::NULL_PTR) {
3567         assert(t->isa_oopptr(), "null klass?");
3568         n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
3569       } else if (t->isa_oopptr()) {
3570         n->subsume_by(ConNode::make(t->make_narrowoop()), this);
3571       } else if (t->isa_klassptr()) {
3572         n->subsume_by(ConNode::make(t->make_narrowklass()), this);
3573       }
3574     }
3575     if (in1->outcnt() == 0) {
3576       in1->disconnect_inputs(this);
3577     }
3578     break;
3579   }
3580 
3581   case Op_Proj: {
3582     if (OptimizeStringConcat || IncrementalInline) {
3583       ProjNode* proj = n->as_Proj();
3584       if (proj->_is_io_use) {
3585         assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, "");
3586         // Separate projections were used for the exception path which
3587         // are normally removed by a late inline.  If it wasn't inlined
3588         // then they will hang around and should just be replaced with
3589         // the original one. Merge them.
3590         Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/);
3591         if (non_io_proj  != nullptr) {
3592           proj->subsume_by(non_io_proj , this);
3593         }
3594       }
3595     }
3596     break;
3597   }
3598 
3599   case Op_Phi:
3600     if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3601       // The EncodeP optimization may create Phi with the same edges
3602       // for all paths. It is not handled well by Register Allocator.
3603       Node* unique_in = n->in(1);
3604       assert(unique_in != nullptr, "");
3605       uint cnt = n->req();
3606       for (uint i = 2; i < cnt; i++) {
3607         Node* m = n->in(i);
3608         assert(m != nullptr, "");
3609         if (unique_in != m)
3610           unique_in = nullptr;
3611       }
3612       if (unique_in != nullptr) {
3613         n->subsume_by(unique_in, this);
3614       }
3615     }
3616     break;
3617 
3618 #endif
3619 
3620 #ifdef ASSERT
3621   case Op_CastII:
3622     // Verify that all range check dependent CastII nodes were removed.
3623     if (n->isa_CastII()->has_range_check()) {
3624       n->dump(3);
3625       assert(false, "Range check dependent CastII node was not removed");
3626     }
3627     break;
3628 #endif
3629 
3630   case Op_ModI:
3631     if (UseDivMod) {
3632       // Check if a%b and a/b both exist
3633       Node* d = n->find_similar(Op_DivI);
3634       if (d) {
3635         // Replace them with a fused divmod if supported
3636         if (Matcher::has_match_rule(Op_DivModI)) {
3637           DivModINode* divmod = DivModINode::make(n);
3638           d->subsume_by(divmod->div_proj(), this);
3639           n->subsume_by(divmod->mod_proj(), this);
3640         } else {
3641           // replace a%b with a-((a/b)*b)
3642           Node* mult = new MulINode(d, d->in(2));
3643           Node* sub  = new SubINode(d->in(1), mult);
3644           n->subsume_by(sub, this);
3645         }
3646       }
3647     }
3648     break;
3649 
3650   case Op_ModL:
3651     if (UseDivMod) {
3652       // Check if a%b and a/b both exist
3653       Node* d = n->find_similar(Op_DivL);
3654       if (d) {
3655         // Replace them with a fused divmod if supported
3656         if (Matcher::has_match_rule(Op_DivModL)) {
3657           DivModLNode* divmod = DivModLNode::make(n);
3658           d->subsume_by(divmod->div_proj(), this);
3659           n->subsume_by(divmod->mod_proj(), this);
3660         } else {
3661           // replace a%b with a-((a/b)*b)
3662           Node* mult = new MulLNode(d, d->in(2));
3663           Node* sub  = new SubLNode(d->in(1), mult);
3664           n->subsume_by(sub, this);
3665         }
3666       }
3667     }
3668     break;
3669 
3670   case Op_UModI:
3671     if (UseDivMod) {
3672       // Check if a%b and a/b both exist
3673       Node* d = n->find_similar(Op_UDivI);
3674       if (d) {
3675         // Replace them with a fused unsigned divmod if supported
3676         if (Matcher::has_match_rule(Op_UDivModI)) {
3677           UDivModINode* divmod = UDivModINode::make(n);
3678           d->subsume_by(divmod->div_proj(), this);
3679           n->subsume_by(divmod->mod_proj(), this);
3680         } else {
3681           // replace a%b with a-((a/b)*b)
3682           Node* mult = new MulINode(d, d->in(2));
3683           Node* sub  = new SubINode(d->in(1), mult);
3684           n->subsume_by(sub, this);
3685         }
3686       }
3687     }
3688     break;
3689 
3690   case Op_UModL:
3691     if (UseDivMod) {
3692       // Check if a%b and a/b both exist
3693       Node* d = n->find_similar(Op_UDivL);
3694       if (d) {
3695         // Replace them with a fused unsigned divmod if supported
3696         if (Matcher::has_match_rule(Op_UDivModL)) {
3697           UDivModLNode* divmod = UDivModLNode::make(n);
3698           d->subsume_by(divmod->div_proj(), this);
3699           n->subsume_by(divmod->mod_proj(), this);
3700         } else {
3701           // replace a%b with a-((a/b)*b)
3702           Node* mult = new MulLNode(d, d->in(2));
3703           Node* sub  = new SubLNode(d->in(1), mult);
3704           n->subsume_by(sub, this);
3705         }
3706       }
3707     }
3708     break;
3709 
3710   case Op_LoadVector:
3711   case Op_StoreVector:
3712 #ifdef ASSERT
3713     // Add VerifyVectorAlignment node between adr and load / store.
3714     if (VerifyAlignVector && Matcher::has_match_rule(Op_VerifyVectorAlignment)) {
3715       bool must_verify_alignment = n->is_LoadVector() ? n->as_LoadVector()->must_verify_alignment() :
3716                                                         n->as_StoreVector()->must_verify_alignment();
3717       if (must_verify_alignment) {
3718         jlong vector_width = n->is_LoadVector() ? n->as_LoadVector()->memory_size() :
3719                                                   n->as_StoreVector()->memory_size();
3720         // The memory access should be aligned to the vector width in bytes.
3721         // However, the underlying array is possibly less well aligned, but at least
3722         // to ObjectAlignmentInBytes. Hence, even if multiple arrays are accessed in
3723         // a loop we can expect at least the following alignment:
3724         jlong guaranteed_alignment = MIN2(vector_width, (jlong)ObjectAlignmentInBytes);
3725         assert(2 <= guaranteed_alignment && guaranteed_alignment <= 64, "alignment must be in range");
3726         assert(is_power_of_2(guaranteed_alignment), "alignment must be power of 2");
3727         // Create mask from alignment. e.g. 0b1000 -> 0b0111
3728         jlong mask = guaranteed_alignment - 1;
3729         Node* mask_con = ConLNode::make(mask);
3730         VerifyVectorAlignmentNode* va = new VerifyVectorAlignmentNode(n->in(MemNode::Address), mask_con);
3731         n->set_req(MemNode::Address, va);
3732       }
3733     }
3734 #endif
3735     break;
3736 
3737   case Op_LoadVectorGather:
3738   case Op_StoreVectorScatter:
3739   case Op_LoadVectorGatherMasked:
3740   case Op_StoreVectorScatterMasked:
3741   case Op_VectorCmpMasked:
3742   case Op_VectorMaskGen:
3743   case Op_LoadVectorMasked:
3744   case Op_StoreVectorMasked:
3745     break;
3746 
3747   case Op_AddReductionVI:
3748   case Op_AddReductionVL:
3749   case Op_AddReductionVF:
3750   case Op_AddReductionVD:
3751   case Op_MulReductionVI:
3752   case Op_MulReductionVL:
3753   case Op_MulReductionVF:
3754   case Op_MulReductionVD:
3755   case Op_MinReductionV:
3756   case Op_MaxReductionV:
3757   case Op_AndReductionV:
3758   case Op_OrReductionV:
3759   case Op_XorReductionV:
3760     break;
3761 
3762   case Op_PackB:
3763   case Op_PackS:
3764   case Op_PackI:
3765   case Op_PackF:
3766   case Op_PackL:
3767   case Op_PackD:
3768     if (n->req()-1 > 2) {
3769       // Replace many operand PackNodes with a binary tree for matching
3770       PackNode* p = (PackNode*) n;
3771       Node* btp = p->binary_tree_pack(1, n->req());
3772       n->subsume_by(btp, this);
3773     }
3774     break;
3775   case Op_Loop:
3776     assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop");
3777   case Op_CountedLoop:
3778   case Op_LongCountedLoop:
3779   case Op_OuterStripMinedLoop:
3780     if (n->as_Loop()->is_inner_loop()) {
3781       frc.inc_inner_loop_count();
3782     }
3783     n->as_Loop()->verify_strip_mined(0);
3784     break;
3785   case Op_LShiftI:
3786   case Op_RShiftI:
3787   case Op_URShiftI:
3788   case Op_LShiftL:
3789   case Op_RShiftL:
3790   case Op_URShiftL:
3791     if (Matcher::need_masked_shift_count) {
3792       // The cpu's shift instructions don't restrict the count to the
3793       // lower 5/6 bits. We need to do the masking ourselves.
3794       Node* in2 = n->in(2);
3795       juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3796       const TypeInt* t = in2->find_int_type();
3797       if (t != nullptr && t->is_con()) {
3798         juint shift = t->get_con();
3799         if (shift > mask) { // Unsigned cmp
3800           n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
3801         }
3802       } else {
3803         if (t == nullptr || t->_lo < 0 || t->_hi > (int)mask) {
3804           Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
3805           n->set_req(2, shift);
3806         }
3807       }
3808       if (in2->outcnt() == 0) { // Remove dead node
3809         in2->disconnect_inputs(this);
3810       }
3811     }
3812     break;
3813   case Op_MemBarStoreStore:
3814   case Op_MemBarRelease:
3815     // Break the link with AllocateNode: it is no longer useful and
3816     // confuses register allocation.
3817     if (n->req() > MemBarNode::Precedent) {
3818       n->set_req(MemBarNode::Precedent, top());
3819     }
3820     break;
3821   case Op_MemBarAcquire: {
3822     if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) {
3823       // At parse time, the trailing MemBarAcquire for a volatile load
3824       // is created with an edge to the load. After optimizations,
3825       // that input may be a chain of Phis. If those phis have no
3826       // other use, then the MemBarAcquire keeps them alive and
3827       // register allocation can be confused.
3828       dead_nodes.push(n->in(MemBarNode::Precedent));
3829       n->set_req(MemBarNode::Precedent, top());
3830     }
3831     break;
3832   }
3833   case Op_Blackhole:
3834     break;
3835   case Op_RangeCheck: {
3836     RangeCheckNode* rc = n->as_RangeCheck();
3837     Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
3838     n->subsume_by(iff, this);
3839     frc._tests.push(iff);
3840     break;
3841   }
3842   case Op_ConvI2L: {
3843     if (!Matcher::convi2l_type_required) {
3844       // Code generation on some platforms doesn't need accurate
3845       // ConvI2L types. Widening the type can help remove redundant
3846       // address computations.
3847       n->as_Type()->set_type(TypeLong::INT);
3848       ResourceMark rm;
3849       Unique_Node_List wq;
3850       wq.push(n);
3851       for (uint next = 0; next < wq.size(); next++) {
3852         Node *m = wq.at(next);
3853 
3854         for(;;) {
3855           // Loop over all nodes with identical inputs edges as m
3856           Node* k = m->find_similar(m->Opcode());
3857           if (k == nullptr) {
3858             break;
3859           }
3860           // Push their uses so we get a chance to remove node made
3861           // redundant
3862           for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
3863             Node* u = k->fast_out(i);
3864             if (u->Opcode() == Op_LShiftL ||
3865                 u->Opcode() == Op_AddL ||
3866                 u->Opcode() == Op_SubL ||
3867                 u->Opcode() == Op_AddP) {
3868               wq.push(u);
3869             }
3870           }
3871           // Replace all nodes with identical edges as m with m
3872           k->subsume_by(m, this);
3873         }
3874       }
3875     }
3876     break;
3877   }
3878   case Op_CmpUL: {
3879     if (!Matcher::has_match_rule(Op_CmpUL)) {
3880       // No support for unsigned long comparisons
3881       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3882       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3883       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3884       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3885       Node* andl = new AndLNode(orl, remove_sign_mask);
3886       Node* cmp = new CmpLNode(andl, n->in(2));
3887       n->subsume_by(cmp, this);
3888     }
3889     break;
3890   }
3891   default:
3892     assert(!n->is_Call(), "");
3893     assert(!n->is_Mem(), "");
3894     assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3895     break;
3896   }
3897 }
3898 
3899 //------------------------------final_graph_reshaping_walk---------------------
3900 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3901 // requires that the walk visits a node's inputs before visiting the node.
3902 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3903   Unique_Node_List sfpt;
3904 
3905   frc._visited.set(root->_idx); // first, mark node as visited
3906   uint cnt = root->req();
3907   Node *n = root;
3908   uint  i = 0;
3909   while (true) {
3910     if (i < cnt) {
3911       // Place all non-visited non-null inputs onto stack
3912       Node* m = n->in(i);
3913       ++i;
3914       if (m != nullptr && !frc._visited.test_set(m->_idx)) {
3915         if (m->is_SafePoint() && m->as_SafePoint()->jvms() != nullptr) {
3916           // compute worst case interpreter size in case of a deoptimization
3917           update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3918 
3919           sfpt.push(m);
3920         }
3921         cnt = m->req();
3922         nstack.push(n, i); // put on stack parent and next input's index
3923         n = m;
3924         i = 0;
3925       }
3926     } else {
3927       // Now do post-visit work
3928       final_graph_reshaping_impl(n, frc, dead_nodes);
3929       if (nstack.is_empty())
3930         break;             // finished
3931       n = nstack.node();   // Get node from stack
3932       cnt = n->req();
3933       i = nstack.index();
3934       nstack.pop();        // Shift to the next node on stack
3935     }
3936   }
3937 
3938   // Skip next transformation if compressed oops are not used.
3939   if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3940       (!UseCompressedOops && !UseCompressedClassPointers))
3941     return;
3942 
3943   // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3944   // It could be done for an uncommon traps or any safepoints/calls
3945   // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3946   while (sfpt.size() > 0) {
3947     n = sfpt.pop();
3948     JVMState *jvms = n->as_SafePoint()->jvms();
3949     assert(jvms != nullptr, "sanity");
3950     int start = jvms->debug_start();
3951     int end   = n->req();
3952     bool is_uncommon = (n->is_CallStaticJava() &&
3953                         n->as_CallStaticJava()->uncommon_trap_request() != 0);
3954     for (int j = start; j < end; j++) {
3955       Node* in = n->in(j);
3956       if (in->is_DecodeNarrowPtr()) {
3957         bool safe_to_skip = true;
3958         if (!is_uncommon ) {
3959           // Is it safe to skip?
3960           for (uint i = 0; i < in->outcnt(); i++) {
3961             Node* u = in->raw_out(i);
3962             if (!u->is_SafePoint() ||
3963                 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) {
3964               safe_to_skip = false;
3965             }
3966           }
3967         }
3968         if (safe_to_skip) {
3969           n->set_req(j, in->in(1));
3970         }
3971         if (in->outcnt() == 0) {
3972           in->disconnect_inputs(this);
3973         }
3974       }
3975     }
3976   }
3977 }
3978 
3979 //------------------------------final_graph_reshaping--------------------------
3980 // Final Graph Reshaping.
3981 //
3982 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
3983 //     and not commoned up and forced early.  Must come after regular
3984 //     optimizations to avoid GVN undoing the cloning.  Clone constant
3985 //     inputs to Loop Phis; these will be split by the allocator anyways.
3986 //     Remove Opaque nodes.
3987 // (2) Move last-uses by commutative operations to the left input to encourage
3988 //     Intel update-in-place two-address operations and better register usage
3989 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
3990 //     calls canonicalizing them back.
3991 // (3) Count the number of double-precision FP ops, single-precision FP ops
3992 //     and call sites.  On Intel, we can get correct rounding either by
3993 //     forcing singles to memory (requires extra stores and loads after each
3994 //     FP bytecode) or we can set a rounding mode bit (requires setting and
3995 //     clearing the mode bit around call sites).  The mode bit is only used
3996 //     if the relative frequency of single FP ops to calls is low enough.
3997 //     This is a key transform for SPEC mpeg_audio.
3998 // (4) Detect infinite loops; blobs of code reachable from above but not
3999 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
4000 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
4001 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
4002 //     Detection is by looking for IfNodes where only 1 projection is
4003 //     reachable from below or CatchNodes missing some targets.
4004 // (5) Assert for insane oop offsets in debug mode.
4005 
4006 bool Compile::final_graph_reshaping() {
4007   // an infinite loop may have been eliminated by the optimizer,
4008   // in which case the graph will be empty.
4009   if (root()->req() == 1) {
4010     // Do not compile method that is only a trivial infinite loop,
4011     // since the content of the loop may have been eliminated.
4012     record_method_not_compilable("trivial infinite loop");
4013     return true;
4014   }
4015 
4016   // Expensive nodes have their control input set to prevent the GVN
4017   // from freely commoning them. There's no GVN beyond this point so
4018   // no need to keep the control input. We want the expensive nodes to
4019   // be freely moved to the least frequent code path by gcm.
4020   assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
4021   for (int i = 0; i < expensive_count(); i++) {
4022     _expensive_nodes.at(i)->set_req(0, nullptr);
4023   }
4024 
4025   Final_Reshape_Counts frc;
4026 
4027   // Visit everybody reachable!
4028   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
4029   Node_Stack nstack(live_nodes() >> 1);
4030   Unique_Node_List dead_nodes;
4031   final_graph_reshaping_walk(nstack, root(), frc, dead_nodes);
4032 
4033   // Check for unreachable (from below) code (i.e., infinite loops).
4034   for( uint i = 0; i < frc._tests.size(); i++ ) {
4035     MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
4036     // Get number of CFG targets.
4037     // Note that PCTables include exception targets after calls.
4038     uint required_outcnt = n->required_outcnt();
4039     if (n->outcnt() != required_outcnt) {
4040       // Check for a few special cases.  Rethrow Nodes never take the
4041       // 'fall-thru' path, so expected kids is 1 less.
4042       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
4043         if (n->in(0)->in(0)->is_Call()) {
4044           CallNode* call = n->in(0)->in(0)->as_Call();
4045           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
4046             required_outcnt--;      // Rethrow always has 1 less kid
4047           } else if (call->req() > TypeFunc::Parms &&
4048                      call->is_CallDynamicJava()) {
4049             // Check for null receiver. In such case, the optimizer has
4050             // detected that the virtual call will always result in a null
4051             // pointer exception. The fall-through projection of this CatchNode
4052             // will not be populated.
4053             Node* arg0 = call->in(TypeFunc::Parms);
4054             if (arg0->is_Type() &&
4055                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
4056               required_outcnt--;
4057             }
4058           } else if (call->entry_point() == OptoRuntime::new_array_Java() ||
4059                      call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
4060             // Check for illegal array length. In such case, the optimizer has
4061             // detected that the allocation attempt will always result in an
4062             // exception. There is no fall-through projection of this CatchNode .
4063             assert(call->is_CallStaticJava(), "static call expected");
4064             assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
4065             uint valid_length_test_input = call->req() - 1;
4066             Node* valid_length_test = call->in(valid_length_test_input);
4067             call->del_req(valid_length_test_input);
4068             if (valid_length_test->find_int_con(1) == 0) {
4069               required_outcnt--;
4070             }
4071             dead_nodes.push(valid_length_test);
4072             assert(n->outcnt() == required_outcnt, "malformed control flow");
4073             continue;
4074           }
4075         }
4076       }
4077 
4078       // Recheck with a better notion of 'required_outcnt'
4079       if (n->outcnt() != required_outcnt) {
4080         record_method_not_compilable("malformed control flow");
4081         return true;            // Not all targets reachable!
4082       }
4083     } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) {
4084       CallNode* call = n->in(0)->in(0)->as_Call();
4085       if (call->entry_point() == OptoRuntime::new_array_Java() ||
4086           call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
4087         assert(call->is_CallStaticJava(), "static call expected");
4088         assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
4089         uint valid_length_test_input = call->req() - 1;
4090         dead_nodes.push(call->in(valid_length_test_input));
4091         call->del_req(valid_length_test_input); // valid length test useless now
4092       }
4093     }
4094     // Check that I actually visited all kids.  Unreached kids
4095     // must be infinite loops.
4096     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
4097       if (!frc._visited.test(n->fast_out(j)->_idx)) {
4098         record_method_not_compilable("infinite loop");
4099         return true;            // Found unvisited kid; must be unreach
4100       }
4101 
4102     // Here so verification code in final_graph_reshaping_walk()
4103     // always see an OuterStripMinedLoopEnd
4104     if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) {
4105       IfNode* init_iff = n->as_If();
4106       Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
4107       n->subsume_by(iff, this);
4108     }
4109   }
4110 
4111   while (dead_nodes.size() > 0) {
4112     Node* m = dead_nodes.pop();
4113     if (m->outcnt() == 0 && m != top()) {
4114       for (uint j = 0; j < m->req(); j++) {
4115         Node* in = m->in(j);
4116         if (in != nullptr) {
4117           dead_nodes.push(in);
4118         }
4119       }
4120       m->disconnect_inputs(this);
4121     }
4122   }
4123 
4124 #ifdef IA32
4125   // If original bytecodes contained a mixture of floats and doubles
4126   // check if the optimizer has made it homogeneous, item (3).
4127   if (UseSSE == 0 &&
4128       frc.get_float_count() > 32 &&
4129       frc.get_double_count() == 0 &&
4130       (10 * frc.get_call_count() < frc.get_float_count()) ) {
4131     set_24_bit_selection_and_mode(false, true);
4132   }
4133 #endif // IA32
4134 
4135   set_java_calls(frc.get_java_call_count());
4136   set_inner_loops(frc.get_inner_loop_count());
4137 
4138   // No infinite loops, no reason to bail out.
4139   return false;
4140 }
4141 
4142 //-----------------------------too_many_traps----------------------------------
4143 // Report if there are too many traps at the current method and bci.
4144 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
4145 bool Compile::too_many_traps(ciMethod* method,
4146                              int bci,
4147                              Deoptimization::DeoptReason reason) {
4148   ciMethodData* md = method->method_data();
4149   if (md->is_empty()) {
4150     // Assume the trap has not occurred, or that it occurred only
4151     // because of a transient condition during start-up in the interpreter.
4152     return false;
4153   }
4154   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4155   if (md->has_trap_at(bci, m, reason) != 0) {
4156     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
4157     // Also, if there are multiple reasons, or if there is no per-BCI record,
4158     // assume the worst.
4159     if (log())
4160       log()->elem("observe trap='%s' count='%d'",
4161                   Deoptimization::trap_reason_name(reason),
4162                   md->trap_count(reason));
4163     return true;
4164   } else {
4165     // Ignore method/bci and see if there have been too many globally.
4166     return too_many_traps(reason, md);
4167   }
4168 }
4169 
4170 // Less-accurate variant which does not require a method and bci.
4171 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
4172                              ciMethodData* logmd) {
4173   if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
4174     // Too many traps globally.
4175     // Note that we use cumulative trap_count, not just md->trap_count.
4176     if (log()) {
4177       int mcount = (logmd == nullptr)? -1: (int)logmd->trap_count(reason);
4178       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
4179                   Deoptimization::trap_reason_name(reason),
4180                   mcount, trap_count(reason));
4181     }
4182     return true;
4183   } else {
4184     // The coast is clear.
4185     return false;
4186   }
4187 }
4188 
4189 //--------------------------too_many_recompiles--------------------------------
4190 // Report if there are too many recompiles at the current method and bci.
4191 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
4192 // Is not eager to return true, since this will cause the compiler to use
4193 // Action_none for a trap point, to avoid too many recompilations.
4194 bool Compile::too_many_recompiles(ciMethod* method,
4195                                   int bci,
4196                                   Deoptimization::DeoptReason reason) {
4197   ciMethodData* md = method->method_data();
4198   if (md->is_empty()) {
4199     // Assume the trap has not occurred, or that it occurred only
4200     // because of a transient condition during start-up in the interpreter.
4201     return false;
4202   }
4203   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
4204   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
4205   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
4206   Deoptimization::DeoptReason per_bc_reason
4207     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
4208   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4209   if ((per_bc_reason == Deoptimization::Reason_none
4210        || md->has_trap_at(bci, m, reason) != 0)
4211       // The trap frequency measure we care about is the recompile count:
4212       && md->trap_recompiled_at(bci, m)
4213       && md->overflow_recompile_count() >= bc_cutoff) {
4214     // Do not emit a trap here if it has already caused recompilations.
4215     // Also, if there are multiple reasons, or if there is no per-BCI record,
4216     // assume the worst.
4217     if (log())
4218       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
4219                   Deoptimization::trap_reason_name(reason),
4220                   md->trap_count(reason),
4221                   md->overflow_recompile_count());
4222     return true;
4223   } else if (trap_count(reason) != 0
4224              && decompile_count() >= m_cutoff) {
4225     // Too many recompiles globally, and we have seen this sort of trap.
4226     // Use cumulative decompile_count, not just md->decompile_count.
4227     if (log())
4228       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
4229                   Deoptimization::trap_reason_name(reason),
4230                   md->trap_count(reason), trap_count(reason),
4231                   md->decompile_count(), decompile_count());
4232     return true;
4233   } else {
4234     // The coast is clear.
4235     return false;
4236   }
4237 }
4238 
4239 // Compute when not to trap. Used by matching trap based nodes and
4240 // NullCheck optimization.
4241 void Compile::set_allowed_deopt_reasons() {
4242   _allowed_reasons = 0;
4243   if (is_method_compilation()) {
4244     for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
4245       assert(rs < BitsPerInt, "recode bit map");
4246       if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
4247         _allowed_reasons |= nth_bit(rs);
4248       }
4249     }
4250   }
4251 }
4252 
4253 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4254   return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4255 }
4256 
4257 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4258   return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4259 }
4260 
4261 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4262   if (holder->is_initialized()) {
4263     return false;
4264   }
4265   if (holder->is_being_initialized()) {
4266     if (accessing_method->holder() == holder) {
4267       // Access inside a class. The barrier can be elided when access happens in <clinit>,
4268       // <init>, or a static method. In all those cases, there was an initialization
4269       // barrier on the holder klass passed.
4270       if (accessing_method->is_static_initializer() ||
4271           accessing_method->is_object_initializer() ||
4272           accessing_method->is_static()) {
4273         return false;
4274       }
4275     } else if (accessing_method->holder()->is_subclass_of(holder)) {
4276       // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4277       // In case of <init> or a static method, the barrier is on the subclass is not enough:
4278       // child class can become fully initialized while its parent class is still being initialized.
4279       if (accessing_method->is_static_initializer()) {
4280         return false;
4281       }
4282     }
4283     ciMethod* root = method(); // the root method of compilation
4284     if (root != accessing_method) {
4285       return needs_clinit_barrier(holder, root); // check access in the context of compilation root
4286     }
4287   }
4288   return true;
4289 }
4290 
4291 #ifndef PRODUCT
4292 //------------------------------verify_bidirectional_edges---------------------
4293 // For each input edge to a node (ie - for each Use-Def edge), verify that
4294 // there is a corresponding Def-Use edge.
4295 void Compile::verify_bidirectional_edges(Unique_Node_List &visited) {
4296   // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
4297   uint stack_size = live_nodes() >> 4;
4298   Node_List nstack(MAX2(stack_size, (uint)OptoNodeListSize));
4299   nstack.push(_root);
4300 
4301   while (nstack.size() > 0) {
4302     Node* n = nstack.pop();
4303     if (visited.member(n)) {
4304       continue;
4305     }
4306     visited.push(n);
4307 
4308     // Walk over all input edges, checking for correspondence
4309     uint length = n->len();
4310     for (uint i = 0; i < length; i++) {
4311       Node* in = n->in(i);
4312       if (in != nullptr && !visited.member(in)) {
4313         nstack.push(in); // Put it on stack
4314       }
4315       if (in != nullptr && !in->is_top()) {
4316         // Count instances of `next`
4317         int cnt = 0;
4318         for (uint idx = 0; idx < in->_outcnt; idx++) {
4319           if (in->_out[idx] == n) {
4320             cnt++;
4321           }
4322         }
4323         assert(cnt > 0, "Failed to find Def-Use edge.");
4324         // Check for duplicate edges
4325         // walk the input array downcounting the input edges to n
4326         for (uint j = 0; j < length; j++) {
4327           if (n->in(j) == in) {
4328             cnt--;
4329           }
4330         }
4331         assert(cnt == 0, "Mismatched edge count.");
4332       } else if (in == nullptr) {
4333         assert(i == 0 || i >= n->req() ||
4334                n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
4335                (n->is_Unlock() && i == (n->req() - 1)) ||
4336                (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
4337               "only region, phi, arraycopy, unlock or membar nodes have null data edges");
4338       } else {
4339         assert(in->is_top(), "sanity");
4340         // Nothing to check.
4341       }
4342     }
4343   }
4344 }
4345 
4346 //------------------------------verify_graph_edges---------------------------
4347 // Walk the Graph and verify that there is a one-to-one correspondence
4348 // between Use-Def edges and Def-Use edges in the graph.
4349 void Compile::verify_graph_edges(bool no_dead_code) {
4350   if (VerifyGraphEdges) {
4351     Unique_Node_List visited;
4352 
4353     // Call graph walk to check edges
4354     verify_bidirectional_edges(visited);
4355     if (no_dead_code) {
4356       // Now make sure that no visited node is used by an unvisited node.
4357       bool dead_nodes = false;
4358       Unique_Node_List checked;
4359       while (visited.size() > 0) {
4360         Node* n = visited.pop();
4361         checked.push(n);
4362         for (uint i = 0; i < n->outcnt(); i++) {
4363           Node* use = n->raw_out(i);
4364           if (checked.member(use))  continue;  // already checked
4365           if (visited.member(use))  continue;  // already in the graph
4366           if (use->is_Con())        continue;  // a dead ConNode is OK
4367           // At this point, we have found a dead node which is DU-reachable.
4368           if (!dead_nodes) {
4369             tty->print_cr("*** Dead nodes reachable via DU edges:");
4370             dead_nodes = true;
4371           }
4372           use->dump(2);
4373           tty->print_cr("---");
4374           checked.push(use);  // No repeats; pretend it is now checked.
4375         }
4376       }
4377       assert(!dead_nodes, "using nodes must be reachable from root");
4378     }
4379   }
4380 }
4381 #endif
4382 
4383 // The Compile object keeps track of failure reasons separately from the ciEnv.
4384 // This is required because there is not quite a 1-1 relation between the
4385 // ciEnv and its compilation task and the Compile object.  Note that one
4386 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
4387 // to backtrack and retry without subsuming loads.  Other than this backtracking
4388 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
4389 // by the logic in C2Compiler.
4390 void Compile::record_failure(const char* reason) {
4391   if (log() != nullptr) {
4392     log()->elem("failure reason='%s' phase='compile'", reason);
4393   }
4394   if (_failure_reason == nullptr) {
4395     // Record the first failure reason.
4396     _failure_reason = reason;
4397     if (CaptureBailoutInformation) {
4398       _first_failure_details = new CompilationFailureInfo(reason);
4399     }
4400   }
4401 
4402   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
4403     C->print_method(PHASE_FAILURE, 1);
4404   }
4405   _root = nullptr;  // flush the graph, too
4406 }
4407 
4408 Compile::TracePhase::TracePhase(const char* name, elapsedTimer* accumulator)
4409   : TraceTime(name, accumulator, CITime, CITimeVerbose),
4410     _compile(Compile::current()),
4411     _log(nullptr),
4412     _phase_name(name),
4413     _dolog(CITimeVerbose)
4414 {
4415   assert(_compile != nullptr, "sanity check");
4416   if (_dolog) {
4417     _log = _compile->log();
4418   }
4419   if (_log != nullptr) {
4420     _log->begin_head("phase name='%s' nodes='%d' live='%d'", _phase_name, _compile->unique(), _compile->live_nodes());
4421     _log->stamp();
4422     _log->end_head();
4423   }
4424 }
4425 
4426 Compile::TracePhase::~TracePhase() {
4427   if (_compile->failing()) return;
4428 #ifdef ASSERT
4429   if (PrintIdealNodeCount) {
4430     tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
4431                   _phase_name, _compile->unique(), _compile->live_nodes(), _compile->count_live_nodes_by_graph_walk());
4432   }
4433 
4434   if (VerifyIdealNodeCount) {
4435     _compile->print_missing_nodes();
4436   }
4437 #endif
4438 
4439   if (_log != nullptr) {
4440     _log->done("phase name='%s' nodes='%d' live='%d'", _phase_name, _compile->unique(), _compile->live_nodes());
4441   }
4442 }
4443 
4444 //----------------------------static_subtype_check-----------------------------
4445 // Shortcut important common cases when superklass is exact:
4446 // (0) superklass is java.lang.Object (can occur in reflective code)
4447 // (1) subklass is already limited to a subtype of superklass => always ok
4448 // (2) subklass does not overlap with superklass => always fail
4449 // (3) superklass has NO subtypes and we can check with a simple compare.
4450 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
4451   if (skip) {
4452     return SSC_full_test;       // Let caller generate the general case.
4453   }
4454 
4455   if (subk->is_java_subtype_of(superk)) {
4456     return SSC_always_true; // (0) and (1)  this test cannot fail
4457   }
4458 
4459   if (!subk->maybe_java_subtype_of(superk)) {
4460     return SSC_always_false; // (2) true path dead; no dynamic test needed
4461   }
4462 
4463   const Type* superelem = superk;
4464   if (superk->isa_aryklassptr()) {
4465     int ignored;
4466     superelem = superk->is_aryklassptr()->base_element_type(ignored);
4467   }
4468 
4469   if (superelem->isa_instklassptr()) {
4470     ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
4471     if (!ik->has_subklass()) {
4472       if (!ik->is_final()) {
4473         // Add a dependency if there is a chance of a later subclass.
4474         dependencies()->assert_leaf_type(ik);
4475       }
4476       if (!superk->maybe_java_subtype_of(subk)) {
4477         return SSC_always_false;
4478       }
4479       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
4480     }
4481   } else {
4482     // A primitive array type has no subtypes.
4483     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
4484   }
4485 
4486   return SSC_full_test;
4487 }
4488 
4489 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
4490 #ifdef _LP64
4491   // The scaled index operand to AddP must be a clean 64-bit value.
4492   // Java allows a 32-bit int to be incremented to a negative
4493   // value, which appears in a 64-bit register as a large
4494   // positive number.  Using that large positive number as an
4495   // operand in pointer arithmetic has bad consequences.
4496   // On the other hand, 32-bit overflow is rare, and the possibility
4497   // can often be excluded, if we annotate the ConvI2L node with
4498   // a type assertion that its value is known to be a small positive
4499   // number.  (The prior range check has ensured this.)
4500   // This assertion is used by ConvI2LNode::Ideal.
4501   int index_max = max_jint - 1;  // array size is max_jint, index is one less
4502   if (sizetype != nullptr) index_max = sizetype->_hi - 1;
4503   const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
4504   idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
4505 #endif
4506   return idx;
4507 }
4508 
4509 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
4510 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency) {
4511   if (ctrl != nullptr) {
4512     // Express control dependency by a CastII node with a narrow type.
4513     // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4514     // node from floating above the range check during loop optimizations. Otherwise, the
4515     // ConvI2L node may be eliminated independently of the range check, causing the data path
4516     // to become TOP while the control path is still there (although it's unreachable).
4517     value = new CastIINode(ctrl, value, itype, carry_dependency ? ConstraintCastNode::StrongDependency : ConstraintCastNode::RegularDependency, true /* range check dependency */);
4518     value = phase->transform(value);
4519   }
4520   const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4521   return phase->transform(new ConvI2LNode(value, ltype));
4522 }
4523 
4524 // The message about the current inlining is accumulated in
4525 // _print_inlining_stream and transferred into the _print_inlining_list
4526 // once we know whether inlining succeeds or not. For regular
4527 // inlining, messages are appended to the buffer pointed by
4528 // _print_inlining_idx in the _print_inlining_list. For late inlining,
4529 // a new buffer is added after _print_inlining_idx in the list. This
4530 // way we can update the inlining message for late inlining call site
4531 // when the inlining is attempted again.
4532 void Compile::print_inlining_init() {
4533   if (print_inlining() || print_intrinsics()) {
4534     // print_inlining_init is actually called several times.
4535     print_inlining_reset();
4536     _print_inlining_list = new (comp_arena())GrowableArray<PrintInliningBuffer*>(comp_arena(), 1, 1, new PrintInliningBuffer());
4537   }
4538 }
4539 
4540 void Compile::print_inlining_reinit() {
4541   if (print_inlining() || print_intrinsics()) {
4542     print_inlining_reset();
4543   }
4544 }
4545 
4546 void Compile::print_inlining_reset() {
4547   _print_inlining_stream->reset();
4548 }
4549 
4550 void Compile::print_inlining_commit() {
4551   assert(print_inlining() || print_intrinsics(), "PrintInlining off?");
4552   // Transfer the message from _print_inlining_stream to the current
4553   // _print_inlining_list buffer and clear _print_inlining_stream.
4554   _print_inlining_list->at(_print_inlining_idx)->ss()->write(_print_inlining_stream->base(), _print_inlining_stream->size());
4555   print_inlining_reset();
4556 }
4557 
4558 void Compile::print_inlining_push() {
4559   // Add new buffer to the _print_inlining_list at current position
4560   _print_inlining_idx++;
4561   _print_inlining_list->insert_before(_print_inlining_idx, new PrintInliningBuffer());
4562 }
4563 
4564 Compile::PrintInliningBuffer* Compile::print_inlining_current() {
4565   return _print_inlining_list->at(_print_inlining_idx);
4566 }
4567 
4568 void Compile::print_inlining_update(CallGenerator* cg) {
4569   if (print_inlining() || print_intrinsics()) {
4570     if (cg->is_late_inline()) {
4571       if (print_inlining_current()->cg() != cg &&
4572           (print_inlining_current()->cg() != nullptr ||
4573            print_inlining_current()->ss()->size() != 0)) {
4574         print_inlining_push();
4575       }
4576       print_inlining_commit();
4577       print_inlining_current()->set_cg(cg);
4578     } else {
4579       if (print_inlining_current()->cg() != nullptr) {
4580         print_inlining_push();
4581       }
4582       print_inlining_commit();
4583     }
4584   }
4585 }
4586 
4587 void Compile::print_inlining_move_to(CallGenerator* cg) {
4588   // We resume inlining at a late inlining call site. Locate the
4589   // corresponding inlining buffer so that we can update it.
4590   if (print_inlining() || print_intrinsics()) {
4591     for (int i = 0; i < _print_inlining_list->length(); i++) {
4592       if (_print_inlining_list->at(i)->cg() == cg) {
4593         _print_inlining_idx = i;
4594         return;
4595       }
4596     }
4597     ShouldNotReachHere();
4598   }
4599 }
4600 
4601 void Compile::print_inlining_update_delayed(CallGenerator* cg) {
4602   if (print_inlining() || print_intrinsics()) {
4603     assert(_print_inlining_stream->size() > 0, "missing inlining msg");
4604     assert(print_inlining_current()->cg() == cg, "wrong entry");
4605     // replace message with new message
4606     _print_inlining_list->at_put(_print_inlining_idx, new PrintInliningBuffer());
4607     print_inlining_commit();
4608     print_inlining_current()->set_cg(cg);
4609   }
4610 }
4611 
4612 void Compile::print_inlining_assert_ready() {
4613   assert(!_print_inlining || _print_inlining_stream->size() == 0, "losing data");
4614 }
4615 
4616 void Compile::process_print_inlining() {
4617   assert(_late_inlines.length() == 0, "not drained yet");
4618   if (print_inlining() || print_intrinsics()) {
4619     ResourceMark rm;
4620     stringStream ss;
4621     assert(_print_inlining_list != nullptr, "process_print_inlining should be called only once.");
4622     for (int i = 0; i < _print_inlining_list->length(); i++) {
4623       PrintInliningBuffer* pib = _print_inlining_list->at(i);
4624       ss.print("%s", pib->ss()->freeze());
4625       delete pib;
4626       DEBUG_ONLY(_print_inlining_list->at_put(i, nullptr));
4627     }
4628     // Reset _print_inlining_list, it only contains destructed objects.
4629     // It is on the arena, so it will be freed when the arena is reset.
4630     _print_inlining_list = nullptr;
4631     // _print_inlining_stream won't be used anymore, either.
4632     print_inlining_reset();
4633     size_t end = ss.size();
4634     _print_inlining_output = NEW_ARENA_ARRAY(comp_arena(), char, end+1);
4635     strncpy(_print_inlining_output, ss.freeze(), end+1);
4636     _print_inlining_output[end] = 0;
4637   }
4638 }
4639 
4640 void Compile::dump_print_inlining() {
4641   if (_print_inlining_output != nullptr) {
4642     tty->print_raw(_print_inlining_output);
4643   }
4644 }
4645 
4646 void Compile::log_late_inline(CallGenerator* cg) {
4647   if (log() != nullptr) {
4648     log()->head("late_inline method='%d'  inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
4649                 cg->unique_id());
4650     JVMState* p = cg->call_node()->jvms();
4651     while (p != nullptr) {
4652       log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
4653       p = p->caller();
4654     }
4655     log()->tail("late_inline");
4656   }
4657 }
4658 
4659 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
4660   log_late_inline(cg);
4661   if (log() != nullptr) {
4662     log()->inline_fail(msg);
4663   }
4664 }
4665 
4666 void Compile::log_inline_id(CallGenerator* cg) {
4667   if (log() != nullptr) {
4668     // The LogCompilation tool needs a unique way to identify late
4669     // inline call sites. This id must be unique for this call site in
4670     // this compilation. Try to have it unique across compilations as
4671     // well because it can be convenient when grepping through the log
4672     // file.
4673     // Distinguish OSR compilations from others in case CICountOSR is
4674     // on.
4675     jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
4676     cg->set_unique_id(id);
4677     log()->elem("inline_id id='" JLONG_FORMAT "'", id);
4678   }
4679 }
4680 
4681 void Compile::log_inline_failure(const char* msg) {
4682   if (C->log() != nullptr) {
4683     C->log()->inline_fail(msg);
4684   }
4685 }
4686 
4687 
4688 // Dump inlining replay data to the stream.
4689 // Don't change thread state and acquire any locks.
4690 void Compile::dump_inline_data(outputStream* out) {
4691   InlineTree* inl_tree = ilt();
4692   if (inl_tree != nullptr) {
4693     out->print(" inline %d", inl_tree->count());
4694     inl_tree->dump_replay_data(out);
4695   }
4696 }
4697 
4698 void Compile::dump_inline_data_reduced(outputStream* out) {
4699   assert(ReplayReduce, "");
4700 
4701   InlineTree* inl_tree = ilt();
4702   if (inl_tree == nullptr) {
4703     return;
4704   }
4705   // Enable iterative replay file reduction
4706   // Output "compile" lines for depth 1 subtrees,
4707   // simulating that those trees were compiled
4708   // instead of inlined.
4709   for (int i = 0; i < inl_tree->subtrees().length(); ++i) {
4710     InlineTree* sub = inl_tree->subtrees().at(i);
4711     if (sub->inline_level() != 1) {
4712       continue;
4713     }
4714 
4715     ciMethod* method = sub->method();
4716     int entry_bci = -1;
4717     int comp_level = env()->task()->comp_level();
4718     out->print("compile ");
4719     method->dump_name_as_ascii(out);
4720     out->print(" %d %d", entry_bci, comp_level);
4721     out->print(" inline %d", sub->count());
4722     sub->dump_replay_data(out, -1);
4723     out->cr();
4724   }
4725 }
4726 
4727 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
4728   if (n1->Opcode() < n2->Opcode())      return -1;
4729   else if (n1->Opcode() > n2->Opcode()) return 1;
4730 
4731   assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
4732   for (uint i = 1; i < n1->req(); i++) {
4733     if (n1->in(i) < n2->in(i))      return -1;
4734     else if (n1->in(i) > n2->in(i)) return 1;
4735   }
4736 
4737   return 0;
4738 }
4739 
4740 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
4741   Node* n1 = *n1p;
4742   Node* n2 = *n2p;
4743 
4744   return cmp_expensive_nodes(n1, n2);
4745 }
4746 
4747 void Compile::sort_expensive_nodes() {
4748   if (!expensive_nodes_sorted()) {
4749     _expensive_nodes.sort(cmp_expensive_nodes);
4750   }
4751 }
4752 
4753 bool Compile::expensive_nodes_sorted() const {
4754   for (int i = 1; i < _expensive_nodes.length(); i++) {
4755     if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) {
4756       return false;
4757     }
4758   }
4759   return true;
4760 }
4761 
4762 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
4763   if (_expensive_nodes.length() == 0) {
4764     return false;
4765   }
4766 
4767   assert(OptimizeExpensiveOps, "optimization off?");
4768 
4769   // Take this opportunity to remove dead nodes from the list
4770   int j = 0;
4771   for (int i = 0; i < _expensive_nodes.length(); i++) {
4772     Node* n = _expensive_nodes.at(i);
4773     if (!n->is_unreachable(igvn)) {
4774       assert(n->is_expensive(), "should be expensive");
4775       _expensive_nodes.at_put(j, n);
4776       j++;
4777     }
4778   }
4779   _expensive_nodes.trunc_to(j);
4780 
4781   // Then sort the list so that similar nodes are next to each other
4782   // and check for at least two nodes of identical kind with same data
4783   // inputs.
4784   sort_expensive_nodes();
4785 
4786   for (int i = 0; i < _expensive_nodes.length()-1; i++) {
4787     if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) {
4788       return true;
4789     }
4790   }
4791 
4792   return false;
4793 }
4794 
4795 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4796   if (_expensive_nodes.length() == 0) {
4797     return;
4798   }
4799 
4800   assert(OptimizeExpensiveOps, "optimization off?");
4801 
4802   // Sort to bring similar nodes next to each other and clear the
4803   // control input of nodes for which there's only a single copy.
4804   sort_expensive_nodes();
4805 
4806   int j = 0;
4807   int identical = 0;
4808   int i = 0;
4809   bool modified = false;
4810   for (; i < _expensive_nodes.length()-1; i++) {
4811     assert(j <= i, "can't write beyond current index");
4812     if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) {
4813       identical++;
4814       _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4815       continue;
4816     }
4817     if (identical > 0) {
4818       _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4819       identical = 0;
4820     } else {
4821       Node* n = _expensive_nodes.at(i);
4822       igvn.replace_input_of(n, 0, nullptr);
4823       igvn.hash_insert(n);
4824       modified = true;
4825     }
4826   }
4827   if (identical > 0) {
4828     _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4829   } else if (_expensive_nodes.length() >= 1) {
4830     Node* n = _expensive_nodes.at(i);
4831     igvn.replace_input_of(n, 0, nullptr);
4832     igvn.hash_insert(n);
4833     modified = true;
4834   }
4835   _expensive_nodes.trunc_to(j);
4836   if (modified) {
4837     igvn.optimize();
4838   }
4839 }
4840 
4841 void Compile::add_expensive_node(Node * n) {
4842   assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list");
4843   assert(n->is_expensive(), "expensive nodes with non-null control here only");
4844   assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4845   if (OptimizeExpensiveOps) {
4846     _expensive_nodes.append(n);
4847   } else {
4848     // Clear control input and let IGVN optimize expensive nodes if
4849     // OptimizeExpensiveOps is off.
4850     n->set_req(0, nullptr);
4851   }
4852 }
4853 
4854 /**
4855  * Track coarsened Lock and Unlock nodes.
4856  */
4857 
4858 class Lock_List : public Node_List {
4859   uint _origin_cnt;
4860 public:
4861   Lock_List(Arena *a, uint cnt) : Node_List(a), _origin_cnt(cnt) {}
4862   uint origin_cnt() const { return _origin_cnt; }
4863 };
4864 
4865 void Compile::add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks) {
4866   int length = locks.length();
4867   if (length > 0) {
4868     // Have to keep this list until locks elimination during Macro nodes elimination.
4869     Lock_List* locks_list = new (comp_arena()) Lock_List(comp_arena(), length);
4870     for (int i = 0; i < length; i++) {
4871       AbstractLockNode* lock = locks.at(i);
4872       assert(lock->is_coarsened(), "expecting only coarsened AbstractLock nodes, but got '%s'[%d] node", lock->Name(), lock->_idx);
4873       locks_list->push(lock);
4874     }
4875     _coarsened_locks.append(locks_list);
4876   }
4877 }
4878 
4879 void Compile::remove_useless_coarsened_locks(Unique_Node_List& useful) {
4880   int count = coarsened_count();
4881   for (int i = 0; i < count; i++) {
4882     Node_List* locks_list = _coarsened_locks.at(i);
4883     for (uint j = 0; j < locks_list->size(); j++) {
4884       Node* lock = locks_list->at(j);
4885       assert(lock->is_AbstractLock(), "sanity");
4886       if (!useful.member(lock)) {
4887         locks_list->yank(lock);
4888       }
4889     }
4890   }
4891 }
4892 
4893 void Compile::remove_coarsened_lock(Node* n) {
4894   if (n->is_AbstractLock()) {
4895     int count = coarsened_count();
4896     for (int i = 0; i < count; i++) {
4897       Node_List* locks_list = _coarsened_locks.at(i);
4898       locks_list->yank(n);
4899     }
4900   }
4901 }
4902 
4903 bool Compile::coarsened_locks_consistent() {
4904   int count = coarsened_count();
4905   for (int i = 0; i < count; i++) {
4906     bool unbalanced = false;
4907     bool modified = false; // track locks kind modifications
4908     Lock_List* locks_list = (Lock_List*)_coarsened_locks.at(i);
4909     uint size = locks_list->size();
4910     if (size == 0) {
4911       unbalanced = false; // All locks were eliminated - good
4912     } else if (size != locks_list->origin_cnt()) {
4913       unbalanced = true; // Some locks were removed from list
4914     } else {
4915       for (uint j = 0; j < size; j++) {
4916         Node* lock = locks_list->at(j);
4917         // All nodes in group should have the same state (modified or not)
4918         if (!lock->as_AbstractLock()->is_coarsened()) {
4919           if (j == 0) {
4920             // first on list was modified, the rest should be too for consistency
4921             modified = true;
4922           } else if (!modified) {
4923             // this lock was modified but previous locks on the list were not
4924             unbalanced = true;
4925             break;
4926           }
4927         } else if (modified) {
4928           // previous locks on list were modified but not this lock
4929           unbalanced = true;
4930           break;
4931         }
4932       }
4933     }
4934     if (unbalanced) {
4935       // unbalanced monitor enter/exit - only some [un]lock nodes were removed or modified
4936 #ifdef ASSERT
4937       if (PrintEliminateLocks) {
4938         tty->print_cr("=== unbalanced coarsened locks ===");
4939         for (uint l = 0; l < size; l++) {
4940           locks_list->at(l)->dump();
4941         }
4942       }
4943 #endif
4944       record_failure(C2Compiler::retry_no_locks_coarsening());
4945       return false;
4946     }
4947   }
4948   return true;
4949 }
4950 
4951 /**
4952  * Remove the speculative part of types and clean up the graph
4953  */
4954 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4955   if (UseTypeSpeculation) {
4956     Unique_Node_List worklist;
4957     worklist.push(root());
4958     int modified = 0;
4959     // Go over all type nodes that carry a speculative type, drop the
4960     // speculative part of the type and enqueue the node for an igvn
4961     // which may optimize it out.
4962     for (uint next = 0; next < worklist.size(); ++next) {
4963       Node *n  = worklist.at(next);
4964       if (n->is_Type()) {
4965         TypeNode* tn = n->as_Type();
4966         const Type* t = tn->type();
4967         const Type* t_no_spec = t->remove_speculative();
4968         if (t_no_spec != t) {
4969           bool in_hash = igvn.hash_delete(n);
4970 #ifdef ASSERT
4971           if (!in_hash) {
4972             tty->print_cr("current graph:");
4973             n->dump_bfs(MaxNodeLimit, nullptr, "S$");
4974             tty->cr();
4975             tty->print_cr("erroneous node:");
4976             n->dump();
4977             assert(false, "node should be in igvn hash table");
4978           }
4979 #endif
4980           tn->set_type(t_no_spec);
4981           igvn.hash_insert(n);
4982           igvn._worklist.push(n); // give it a chance to go away
4983           modified++;
4984         }
4985       }
4986       // Iterate over outs - endless loops is unreachable from below
4987       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4988         Node *m = n->fast_out(i);
4989         if (not_a_node(m)) {
4990           continue;
4991         }
4992         worklist.push(m);
4993       }
4994     }
4995     // Drop the speculative part of all types in the igvn's type table
4996     igvn.remove_speculative_types();
4997     if (modified > 0) {
4998       igvn.optimize();
4999       if (failing())  return;
5000     }
5001 #ifdef ASSERT
5002     // Verify that after the IGVN is over no speculative type has resurfaced
5003     worklist.clear();
5004     worklist.push(root());
5005     for (uint next = 0; next < worklist.size(); ++next) {
5006       Node *n  = worklist.at(next);
5007       const Type* t = igvn.type_or_null(n);
5008       assert((t == nullptr) || (t == t->remove_speculative()), "no more speculative types");
5009       if (n->is_Type()) {
5010         t = n->as_Type()->type();
5011         assert(t == t->remove_speculative(), "no more speculative types");
5012       }
5013       // Iterate over outs - endless loops is unreachable from below
5014       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5015         Node *m = n->fast_out(i);
5016         if (not_a_node(m)) {
5017           continue;
5018         }
5019         worklist.push(m);
5020       }
5021     }
5022     igvn.check_no_speculative_types();
5023 #endif
5024   }
5025 }
5026 
5027 // Auxiliary methods to support randomized stressing/fuzzing.
5028 
5029 int Compile::random() {
5030   _stress_seed = os::next_random(_stress_seed);
5031   return static_cast<int>(_stress_seed);
5032 }
5033 
5034 // This method can be called the arbitrary number of times, with current count
5035 // as the argument. The logic allows selecting a single candidate from the
5036 // running list of candidates as follows:
5037 //    int count = 0;
5038 //    Cand* selected = null;
5039 //    while(cand = cand->next()) {
5040 //      if (randomized_select(++count)) {
5041 //        selected = cand;
5042 //      }
5043 //    }
5044 //
5045 // Including count equalizes the chances any candidate is "selected".
5046 // This is useful when we don't have the complete list of candidates to choose
5047 // from uniformly. In this case, we need to adjust the randomicity of the
5048 // selection, or else we will end up biasing the selection towards the latter
5049 // candidates.
5050 //
5051 // Quick back-envelope calculation shows that for the list of n candidates
5052 // the equal probability for the candidate to persist as "best" can be
5053 // achieved by replacing it with "next" k-th candidate with the probability
5054 // of 1/k. It can be easily shown that by the end of the run, the
5055 // probability for any candidate is converged to 1/n, thus giving the
5056 // uniform distribution among all the candidates.
5057 //
5058 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
5059 #define RANDOMIZED_DOMAIN_POW 29
5060 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
5061 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
5062 bool Compile::randomized_select(int count) {
5063   assert(count > 0, "only positive");
5064   return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
5065 }
5066 
5067 CloneMap&     Compile::clone_map()                 { return _clone_map; }
5068 void          Compile::set_clone_map(Dict* d)      { _clone_map._dict = d; }
5069 
5070 void NodeCloneInfo::dump_on(outputStream* st) const {
5071   st->print(" {%d:%d} ", idx(), gen());
5072 }
5073 
5074 void CloneMap::clone(Node* old, Node* nnn, int gen) {
5075   uint64_t val = value(old->_idx);
5076   NodeCloneInfo cio(val);
5077   assert(val != 0, "old node should be in the map");
5078   NodeCloneInfo cin(cio.idx(), gen + cio.gen());
5079   insert(nnn->_idx, cin.get());
5080 #ifndef PRODUCT
5081   if (is_debug()) {
5082     tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
5083   }
5084 #endif
5085 }
5086 
5087 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
5088   NodeCloneInfo cio(value(old->_idx));
5089   if (cio.get() == 0) {
5090     cio.set(old->_idx, 0);
5091     insert(old->_idx, cio.get());
5092 #ifndef PRODUCT
5093     if (is_debug()) {
5094       tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
5095     }
5096 #endif
5097   }
5098   clone(old, nnn, gen);
5099 }
5100 
5101 int CloneMap::max_gen() const {
5102   int g = 0;
5103   DictI di(_dict);
5104   for(; di.test(); ++di) {
5105     int t = gen(di._key);
5106     if (g < t) {
5107       g = t;
5108 #ifndef PRODUCT
5109       if (is_debug()) {
5110         tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
5111       }
5112 #endif
5113     }
5114   }
5115   return g;
5116 }
5117 
5118 void CloneMap::dump(node_idx_t key, outputStream* st) const {
5119   uint64_t val = value(key);
5120   if (val != 0) {
5121     NodeCloneInfo ni(val);
5122     ni.dump_on(st);
5123   }
5124 }
5125 
5126 void Compile::shuffle_macro_nodes() {
5127   if (_macro_nodes.length() < 2) {
5128     return;
5129   }
5130   for (uint i = _macro_nodes.length() - 1; i >= 1; i--) {
5131     uint j = C->random() % (i + 1);
5132     swap(_macro_nodes.at(i), _macro_nodes.at(j));
5133   }
5134 }
5135 
5136 // Move Allocate nodes to the start of the list
5137 void Compile::sort_macro_nodes() {
5138   int count = macro_count();
5139   int allocates = 0;
5140   for (int i = 0; i < count; i++) {
5141     Node* n = macro_node(i);
5142     if (n->is_Allocate()) {
5143       if (i != allocates) {
5144         Node* tmp = macro_node(allocates);
5145         _macro_nodes.at_put(allocates, n);
5146         _macro_nodes.at_put(i, tmp);
5147       }
5148       allocates++;
5149     }
5150   }
5151 }
5152 
5153 void Compile::print_method(CompilerPhaseType cpt, int level, Node* n) {
5154   if (failing()) { return; }
5155   EventCompilerPhase event(UNTIMED);
5156   if (event.should_commit()) {
5157     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level);
5158   }
5159 #ifndef PRODUCT
5160   ResourceMark rm;
5161   stringStream ss;
5162   ss.print_raw(CompilerPhaseTypeHelper::to_description(cpt));
5163   int iter = ++_igv_phase_iter[cpt];
5164   if (iter > 1) {
5165     ss.print(" %d", iter);
5166   }
5167   if (n != nullptr) {
5168     ss.print(": %d %s ", n->_idx, NodeClassNames[n->Opcode()]);
5169   }
5170 
5171   const char* name = ss.as_string();
5172   if (should_print_igv(level)) {
5173     _igv_printer->print_method(name, level);
5174   }
5175   if (should_print_phase(cpt)) {
5176     print_ideal_ir(CompilerPhaseTypeHelper::to_name(cpt));
5177   }
5178 #endif
5179   C->_latest_stage_start_counter.stamp();
5180 }
5181 
5182 // Only used from CompileWrapper
5183 void Compile::begin_method() {
5184 #ifndef PRODUCT
5185   if (_method != nullptr && should_print_igv(1)) {
5186     _igv_printer->begin_method();
5187   }
5188 #endif
5189   C->_latest_stage_start_counter.stamp();
5190 }
5191 
5192 // Only used from CompileWrapper
5193 void Compile::end_method() {
5194   EventCompilerPhase event(UNTIMED);
5195   if (event.should_commit()) {
5196     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, 1);
5197   }
5198 
5199 #ifndef PRODUCT
5200   if (_method != nullptr && should_print_igv(1)) {
5201     _igv_printer->end_method();
5202   }
5203 #endif
5204 }
5205 
5206 bool Compile::should_print_phase(CompilerPhaseType cpt) {
5207 #ifndef PRODUCT
5208   if (_directive->should_print_phase(cpt)) {
5209     return true;
5210   }
5211 #endif
5212   return false;
5213 }
5214 
5215 bool Compile::should_print_igv(const int level) {
5216 #ifndef PRODUCT
5217   if (PrintIdealGraphLevel < 0) { // disabled by the user
5218     return false;
5219   }
5220 
5221   bool need = directive()->IGVPrintLevelOption >= level;
5222   if (need && !_igv_printer) {
5223     _igv_printer = IdealGraphPrinter::printer();
5224     _igv_printer->set_compile(this);
5225   }
5226   return need;
5227 #else
5228   return false;
5229 #endif
5230 }
5231 
5232 #ifndef PRODUCT
5233 IdealGraphPrinter* Compile::_debug_file_printer = nullptr;
5234 IdealGraphPrinter* Compile::_debug_network_printer = nullptr;
5235 
5236 // Called from debugger. Prints method to the default file with the default phase name.
5237 // This works regardless of any Ideal Graph Visualizer flags set or not.
5238 void igv_print() {
5239   Compile::current()->igv_print_method_to_file();
5240 }
5241 
5242 // Same as igv_print() above but with a specified phase name.
5243 void igv_print(const char* phase_name) {
5244   Compile::current()->igv_print_method_to_file(phase_name);
5245 }
5246 
5247 // Called from debugger. Prints method with the default phase name to the default network or the one specified with
5248 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument.
5249 // This works regardless of any Ideal Graph Visualizer flags set or not.
5250 void igv_print(bool network) {
5251   if (network) {
5252     Compile::current()->igv_print_method_to_network();
5253   } else {
5254     Compile::current()->igv_print_method_to_file();
5255   }
5256 }
5257 
5258 // Same as igv_print(bool network) above but with a specified phase name.
5259 void igv_print(bool network, const char* phase_name) {
5260   if (network) {
5261     Compile::current()->igv_print_method_to_network(phase_name);
5262   } else {
5263     Compile::current()->igv_print_method_to_file(phase_name);
5264   }
5265 }
5266 
5267 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set.
5268 void igv_print_default() {
5269   Compile::current()->print_method(PHASE_DEBUG, 0);
5270 }
5271 
5272 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay.
5273 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow
5274 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not.
5275 void igv_append() {
5276   Compile::current()->igv_print_method_to_file("Debug", true);
5277 }
5278 
5279 // Same as igv_append() above but with a specified phase name.
5280 void igv_append(const char* phase_name) {
5281   Compile::current()->igv_print_method_to_file(phase_name, true);
5282 }
5283 
5284 void Compile::igv_print_method_to_file(const char* phase_name, bool append) {
5285   const char* file_name = "custom_debug.xml";
5286   if (_debug_file_printer == nullptr) {
5287     _debug_file_printer = new IdealGraphPrinter(C, file_name, append);
5288   } else {
5289     _debug_file_printer->update_compiled_method(C->method());
5290   }
5291   tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name);
5292   _debug_file_printer->print(phase_name, (Node*)C->root());
5293 }
5294 
5295 void Compile::igv_print_method_to_network(const char* phase_name) {
5296   if (_debug_network_printer == nullptr) {
5297     _debug_network_printer = new IdealGraphPrinter(C);
5298   } else {
5299     _debug_network_printer->update_compiled_method(C->method());
5300   }
5301   tty->print_cr("Method printed over network stream to IGV");
5302   _debug_network_printer->print(phase_name, (Node*)C->root());
5303 }
5304 #endif
5305 
5306 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
5307   if (type != nullptr && phase->type(value)->higher_equal(type)) {
5308     return value;
5309   }
5310   Node* result = nullptr;
5311   if (bt == T_BYTE) {
5312     result = phase->transform(new LShiftINode(value, phase->intcon(24)));
5313     result = new RShiftINode(result, phase->intcon(24));
5314   } else if (bt == T_BOOLEAN) {
5315     result = new AndINode(value, phase->intcon(0xFF));
5316   } else if (bt == T_CHAR) {
5317     result = new AndINode(value,phase->intcon(0xFFFF));
5318   } else {
5319     assert(bt == T_SHORT, "unexpected narrow type");
5320     result = phase->transform(new LShiftINode(value, phase->intcon(16)));
5321     result = new RShiftINode(result, phase->intcon(16));
5322   }
5323   if (transform_res) {
5324     result = phase->transform(result);
5325   }
5326   return result;
5327 }
5328 
5329 void Compile::record_method_not_compilable_oom() {
5330   record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
5331 }