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