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