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::modifier_flags_offset()))
1703         alias_type(idx)->set_rewritable(false);
1704       if (flat->offset() == in_bytes(Klass::access_flags_offset()))
1705         alias_type(idx)->set_rewritable(false);
1706       if (flat->offset() == in_bytes(Klass::misc_flags_offset()))
1707         alias_type(idx)->set_rewritable(false);
1708       if (flat->offset() == in_bytes(Klass::java_mirror_offset()))
1709         alias_type(idx)->set_rewritable(false);
1710       if (flat->offset() == in_bytes(Klass::secondary_super_cache_offset()))
1711         alias_type(idx)->set_rewritable(false);
1712     }
1713     // %%% (We would like to finalize JavaThread::threadObj_offset(),
1714     // but the base pointer type is not distinctive enough to identify
1715     // references into JavaThread.)
1716 
1717     // Check for final fields.
1718     const TypeInstPtr* tinst = flat->isa_instptr();
1719     if (tinst && tinst->offset() >= instanceOopDesc::base_offset_in_bytes()) {
1720       ciField* field;
1721       if (tinst->const_oop() != nullptr &&
1722           tinst->instance_klass() == ciEnv::current()->Class_klass() &&
1723           tinst->offset() >= (tinst->instance_klass()->layout_helper_size_in_bytes())) {
1724         // static field
1725         ciInstanceKlass* k = tinst->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
1726         field = k->get_field_by_offset(tinst->offset(), true);
1727       } else {
1728         ciInstanceKlass *k = tinst->instance_klass();
1729         field = k->get_field_by_offset(tinst->offset(), false);
1730       }
1731       assert(field == nullptr ||
1732              original_field == nullptr ||
1733              (field->holder() == original_field->holder() &&
1734               field->offset_in_bytes() == original_field->offset_in_bytes() &&
1735               field->is_static() == original_field->is_static()), "wrong field?");
1736       // Set field() and is_rewritable() attributes.
1737       if (field != nullptr)  alias_type(idx)->set_field(field);
1738     }
1739   }
1740 
1741   // Fill the cache for next time.
1742   ace->_adr_type = adr_type;
1743   ace->_index    = idx;
1744   assert(alias_type(adr_type) == alias_type(idx),  "type must be installed");
1745 
1746   // Might as well try to fill the cache for the flattened version, too.
1747   AliasCacheEntry* face = probe_alias_cache(flat);
1748   if (face->_adr_type == nullptr) {
1749     face->_adr_type = flat;
1750     face->_index    = idx;
1751     assert(alias_type(flat) == alias_type(idx), "flat type must work too");
1752   }
1753 
1754   return alias_type(idx);
1755 }
1756 
1757 
1758 Compile::AliasType* Compile::alias_type(ciField* field) {
1759   const TypeOopPtr* t;
1760   if (field->is_static())
1761     t = TypeInstPtr::make(field->holder()->java_mirror());
1762   else
1763     t = TypeOopPtr::make_from_klass_raw(field->holder());
1764   AliasType* atp = alias_type(t->add_offset(field->offset_in_bytes()), field);
1765   assert((field->is_final() || field->is_stable()) == !atp->is_rewritable(), "must get the rewritable bits correct");
1766   return atp;
1767 }
1768 
1769 
1770 //------------------------------have_alias_type--------------------------------
1771 bool Compile::have_alias_type(const TypePtr* adr_type) {
1772   AliasCacheEntry* ace = probe_alias_cache(adr_type);
1773   if (ace->_adr_type == adr_type) {
1774     return true;
1775   }
1776 
1777   // Handle special cases.
1778   if (adr_type == nullptr)             return true;
1779   if (adr_type == TypePtr::BOTTOM)  return true;
1780 
1781   return find_alias_type(adr_type, true, nullptr) != nullptr;
1782 }
1783 
1784 //-----------------------------must_alias--------------------------------------
1785 // True if all values of the given address type are in the given alias category.
1786 bool Compile::must_alias(const TypePtr* adr_type, int alias_idx) {
1787   if (alias_idx == AliasIdxBot)         return true;  // the universal category
1788   if (adr_type == nullptr)              return true;  // null serves as TypePtr::TOP
1789   if (alias_idx == AliasIdxTop)         return false; // the empty category
1790   if (adr_type->base() == Type::AnyPtr) return false; // TypePtr::BOTTOM or its twins
1791 
1792   // the only remaining possible overlap is identity
1793   int adr_idx = get_alias_index(adr_type);
1794   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1795   assert(adr_idx == alias_idx ||
1796          (alias_type(alias_idx)->adr_type() != TypeOopPtr::BOTTOM
1797           && adr_type                       != TypeOopPtr::BOTTOM),
1798          "should not be testing for overlap with an unsafe pointer");
1799   return adr_idx == alias_idx;
1800 }
1801 
1802 //------------------------------can_alias--------------------------------------
1803 // True if any values of the given address type are in the given alias category.
1804 bool Compile::can_alias(const TypePtr* adr_type, int alias_idx) {
1805   if (alias_idx == AliasIdxTop)         return false; // the empty category
1806   if (adr_type == nullptr)              return false; // null serves as TypePtr::TOP
1807   // Known instance doesn't alias with bottom memory
1808   if (alias_idx == AliasIdxBot)         return !adr_type->is_known_instance();                   // the universal category
1809   if (adr_type->base() == Type::AnyPtr) return !C->get_adr_type(alias_idx)->is_known_instance(); // TypePtr::BOTTOM or its twins
1810 
1811   // the only remaining possible overlap is identity
1812   int adr_idx = get_alias_index(adr_type);
1813   assert(adr_idx != AliasIdxBot && adr_idx != AliasIdxTop, "");
1814   return adr_idx == alias_idx;
1815 }
1816 
1817 // Mark all ParsePredicateNodes as useless. They will later be removed from the graph in IGVN together with their
1818 // uncommon traps if no Runtime Predicates were created from the Parse Predicates.
1819 void Compile::mark_parse_predicate_nodes_useless(PhaseIterGVN& igvn) {
1820   if (parse_predicate_count() == 0) {
1821     return;
1822   }
1823   for (int i = 0; i < parse_predicate_count(); i++) {
1824     ParsePredicateNode* parse_predicate = _parse_predicates.at(i);
1825     parse_predicate->mark_useless();
1826     igvn._worklist.push(parse_predicate);
1827   }
1828   _parse_predicates.clear();
1829 }
1830 
1831 void Compile::record_for_post_loop_opts_igvn(Node* n) {
1832   if (!n->for_post_loop_opts_igvn()) {
1833     assert(!_for_post_loop_igvn.contains(n), "duplicate");
1834     n->add_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1835     _for_post_loop_igvn.append(n);
1836   }
1837 }
1838 
1839 void Compile::remove_from_post_loop_opts_igvn(Node* n) {
1840   n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1841   _for_post_loop_igvn.remove(n);
1842 }
1843 
1844 void Compile::process_for_post_loop_opts_igvn(PhaseIterGVN& igvn) {
1845   // Verify that all previous optimizations produced a valid graph
1846   // at least to this point, even if no loop optimizations were done.
1847   PhaseIdealLoop::verify(igvn);
1848 
1849   C->set_post_loop_opts_phase(); // no more loop opts allowed
1850 
1851   assert(!C->major_progress(), "not cleared");
1852 
1853   if (_for_post_loop_igvn.length() > 0) {
1854     while (_for_post_loop_igvn.length() > 0) {
1855       Node* n = _for_post_loop_igvn.pop();
1856       n->remove_flag(Node::NodeFlags::Flag_for_post_loop_opts_igvn);
1857       igvn._worklist.push(n);
1858     }
1859     igvn.optimize();
1860     if (failing()) return;
1861     assert(_for_post_loop_igvn.length() == 0, "no more delayed nodes allowed");
1862     assert(C->parse_predicate_count() == 0, "all parse predicates should have been removed now");
1863 
1864     // Sometimes IGVN sets major progress (e.g., when processing loop nodes).
1865     if (C->major_progress()) {
1866       C->clear_major_progress(); // ensure that major progress is now clear
1867     }
1868   }
1869 }
1870 
1871 void Compile::record_unstable_if_trap(UnstableIfTrap* trap) {
1872   if (OptimizeUnstableIf) {
1873     _unstable_if_traps.append(trap);
1874   }
1875 }
1876 
1877 void Compile::remove_useless_unstable_if_traps(Unique_Node_List& useful) {
1878   for (int i = _unstable_if_traps.length() - 1; i >= 0; i--) {
1879     UnstableIfTrap* trap = _unstable_if_traps.at(i);
1880     Node* n = trap->uncommon_trap();
1881     if (!useful.member(n)) {
1882       _unstable_if_traps.delete_at(i); // replaces i-th with last element which is known to be useful (already processed)
1883     }
1884   }
1885 }
1886 
1887 // Remove the unstable if trap associated with 'unc' from candidates. It is either dead
1888 // or fold-compares case. Return true if succeed or not found.
1889 //
1890 // In rare cases, the found trap has been processed. It is too late to delete it. Return
1891 // false and ask fold-compares to yield.
1892 //
1893 // 'fold-compares' may use the uncommon_trap of the dominating IfNode to cover the fused
1894 // IfNode. This breaks the unstable_if trap invariant: control takes the unstable path
1895 // when deoptimization does happen.
1896 bool Compile::remove_unstable_if_trap(CallStaticJavaNode* unc, bool yield) {
1897   for (int i = 0; i < _unstable_if_traps.length(); ++i) {
1898     UnstableIfTrap* trap = _unstable_if_traps.at(i);
1899     if (trap->uncommon_trap() == unc) {
1900       if (yield && trap->modified()) {
1901         return false;
1902       }
1903       _unstable_if_traps.delete_at(i);
1904       break;
1905     }
1906   }
1907   return true;
1908 }
1909 
1910 // Re-calculate unstable_if traps with the liveness of next_bci, which points to the unlikely path.
1911 // It needs to be done after igvn because fold-compares may fuse uncommon_traps and before renumbering.
1912 void Compile::process_for_unstable_if_traps(PhaseIterGVN& igvn) {
1913   for (int i = _unstable_if_traps.length() - 1; i >= 0; --i) {
1914     UnstableIfTrap* trap = _unstable_if_traps.at(i);
1915     CallStaticJavaNode* unc = trap->uncommon_trap();
1916     int next_bci = trap->next_bci();
1917     bool modified = trap->modified();
1918 
1919     if (next_bci != -1 && !modified) {
1920       assert(!_dead_node_list.test(unc->_idx), "changing a dead node!");
1921       JVMState* jvms = unc->jvms();
1922       ciMethod* method = jvms->method();
1923       ciBytecodeStream iter(method);
1924 
1925       iter.force_bci(jvms->bci());
1926       assert(next_bci == iter.next_bci() || next_bci == iter.get_dest(), "wrong next_bci at unstable_if");
1927       Bytecodes::Code c = iter.cur_bc();
1928       Node* lhs = nullptr;
1929       Node* rhs = nullptr;
1930       if (c == Bytecodes::_if_acmpeq || c == Bytecodes::_if_acmpne) {
1931         lhs = unc->peek_operand(0);
1932         rhs = unc->peek_operand(1);
1933       } else if (c == Bytecodes::_ifnull || c == Bytecodes::_ifnonnull) {
1934         lhs = unc->peek_operand(0);
1935       }
1936 
1937       ResourceMark rm;
1938       const MethodLivenessResult& live_locals = method->liveness_at_bci(next_bci);
1939       assert(live_locals.is_valid(), "broken liveness info");
1940       int len = (int)live_locals.size();
1941 
1942       for (int i = 0; i < len; i++) {
1943         Node* local = unc->local(jvms, i);
1944         // kill local using the liveness of next_bci.
1945         // give up when the local looks like an operand to secure reexecution.
1946         if (!live_locals.at(i) && !local->is_top() && local != lhs && local!= rhs) {
1947           uint idx = jvms->locoff() + i;
1948 #ifdef ASSERT
1949           if (PrintOpto && Verbose) {
1950             tty->print("[unstable_if] kill local#%d: ", idx);
1951             local->dump();
1952             tty->cr();
1953           }
1954 #endif
1955           igvn.replace_input_of(unc, idx, top());
1956           modified = true;
1957         }
1958       }
1959     }
1960 
1961     // keep the mondified trap for late query
1962     if (modified) {
1963       trap->set_modified();
1964     } else {
1965       _unstable_if_traps.delete_at(i);
1966     }
1967   }
1968   igvn.optimize();
1969 }
1970 
1971 // StringOpts and late inlining of string methods
1972 void Compile::inline_string_calls(bool parse_time) {
1973   {
1974     // remove useless nodes to make the usage analysis simpler
1975     ResourceMark rm;
1976     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
1977   }
1978 
1979   {
1980     ResourceMark rm;
1981     print_method(PHASE_BEFORE_STRINGOPTS, 3);
1982     PhaseStringOpts pso(initial_gvn());
1983     print_method(PHASE_AFTER_STRINGOPTS, 3);
1984   }
1985 
1986   // now inline anything that we skipped the first time around
1987   if (!parse_time) {
1988     _late_inlines_pos = _late_inlines.length();
1989   }
1990 
1991   while (_string_late_inlines.length() > 0) {
1992     CallGenerator* cg = _string_late_inlines.pop();
1993     cg->do_late_inline();
1994     if (failing())  return;
1995   }
1996   _string_late_inlines.trunc_to(0);
1997 }
1998 
1999 // Late inlining of boxing methods
2000 void Compile::inline_boxing_calls(PhaseIterGVN& igvn) {
2001   if (_boxing_late_inlines.length() > 0) {
2002     assert(has_boxed_value(), "inconsistent");
2003 
2004     set_inlining_incrementally(true);
2005 
2006     igvn_worklist()->ensure_empty(); // should be done with igvn
2007 
2008     _late_inlines_pos = _late_inlines.length();
2009 
2010     while (_boxing_late_inlines.length() > 0) {
2011       CallGenerator* cg = _boxing_late_inlines.pop();
2012       cg->do_late_inline();
2013       if (failing())  return;
2014     }
2015     _boxing_late_inlines.trunc_to(0);
2016 
2017     inline_incrementally_cleanup(igvn);
2018 
2019     set_inlining_incrementally(false);
2020   }
2021 }
2022 
2023 bool Compile::inline_incrementally_one() {
2024   assert(IncrementalInline, "incremental inlining should be on");
2025 
2026   TracePhase tp(_t_incrInline_inline);
2027 
2028   set_inlining_progress(false);
2029   set_do_cleanup(false);
2030 
2031   for (int i = 0; i < _late_inlines.length(); i++) {
2032     _late_inlines_pos = i+1;
2033     CallGenerator* cg = _late_inlines.at(i);
2034     bool does_dispatch = cg->is_virtual_late_inline() || cg->is_mh_late_inline();
2035     if (inlining_incrementally() || does_dispatch) { // a call can be either inlined or strength-reduced to a direct call
2036       cg->do_late_inline();
2037       assert(_late_inlines.at(i) == cg, "no insertions before current position allowed");
2038       if (failing()) {
2039         return false;
2040       } else if (inlining_progress()) {
2041         _late_inlines_pos = i+1; // restore the position in case new elements were inserted
2042         print_method(PHASE_INCREMENTAL_INLINE_STEP, 3, cg->call_node());
2043         break; // process one call site at a time
2044       }
2045     } else {
2046       // Ignore late inline direct calls when inlining is not allowed.
2047       // They are left in the late inline list when node budget is exhausted until the list is fully drained.
2048     }
2049   }
2050   // Remove processed elements.
2051   _late_inlines.remove_till(_late_inlines_pos);
2052   _late_inlines_pos = 0;
2053 
2054   assert(inlining_progress() || _late_inlines.length() == 0, "no progress");
2055 
2056   bool needs_cleanup = do_cleanup() || over_inlining_cutoff();
2057 
2058   set_inlining_progress(false);
2059   set_do_cleanup(false);
2060 
2061   bool force_cleanup = directive()->IncrementalInlineForceCleanupOption;
2062   return (_late_inlines.length() > 0) && !needs_cleanup && !force_cleanup;
2063 }
2064 
2065 void Compile::inline_incrementally_cleanup(PhaseIterGVN& igvn) {
2066   {
2067     TracePhase tp(_t_incrInline_pru);
2068     ResourceMark rm;
2069     PhaseRemoveUseless pru(initial_gvn(), *igvn_worklist());
2070   }
2071   {
2072     TracePhase tp(_t_incrInline_igvn);
2073     igvn.reset_from_gvn(initial_gvn());
2074     igvn.optimize();
2075     if (failing()) return;
2076   }
2077   print_method(PHASE_INCREMENTAL_INLINE_CLEANUP, 3);
2078 }
2079 
2080 // Perform incremental inlining until bound on number of live nodes is reached
2081 void Compile::inline_incrementally(PhaseIterGVN& igvn) {
2082   TracePhase tp(_t_incrInline);
2083 
2084   set_inlining_incrementally(true);
2085   uint low_live_nodes = 0;
2086 
2087   while (_late_inlines.length() > 0) {
2088     if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2089       if (low_live_nodes < (uint)LiveNodeCountInliningCutoff * 8 / 10) {
2090         TracePhase tp(_t_incrInline_ideal);
2091         // PhaseIdealLoop is expensive so we only try it once we are
2092         // out of live nodes and we only try it again if the previous
2093         // helped got the number of nodes down significantly
2094         PhaseIdealLoop::optimize(igvn, LoopOptsNone);
2095         if (failing())  return;
2096         low_live_nodes = live_nodes();
2097         _major_progress = true;
2098       }
2099 
2100       if (live_nodes() > (uint)LiveNodeCountInliningCutoff) {
2101         bool do_print_inlining = print_inlining() || print_intrinsics();
2102         if (do_print_inlining || log() != nullptr) {
2103           // Print inlining message for candidates that we couldn't inline for lack of space.
2104           for (int i = 0; i < _late_inlines.length(); i++) {
2105             CallGenerator* cg = _late_inlines.at(i);
2106             const char* msg = "live nodes > LiveNodeCountInliningCutoff";
2107             if (do_print_inlining) {
2108               inline_printer()->record(cg->method(), cg->call_node()->jvms(), InliningResult::FAILURE, msg);
2109             }
2110             log_late_inline_failure(cg, msg);
2111           }
2112         }
2113         break; // finish
2114       }
2115     }
2116 
2117     igvn_worklist()->ensure_empty(); // should be done with igvn
2118 
2119     while (inline_incrementally_one()) {
2120       assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2121     }
2122     if (failing())  return;
2123 
2124     inline_incrementally_cleanup(igvn);
2125 
2126     print_method(PHASE_INCREMENTAL_INLINE_STEP, 3);
2127 
2128     if (failing())  return;
2129 
2130     if (_late_inlines.length() == 0) {
2131       break; // no more progress
2132     }
2133   }
2134 
2135   igvn_worklist()->ensure_empty(); // should be done with igvn
2136 
2137   if (_string_late_inlines.length() > 0) {
2138     assert(has_stringbuilder(), "inconsistent");
2139 
2140     inline_string_calls(false);
2141 
2142     if (failing())  return;
2143 
2144     inline_incrementally_cleanup(igvn);
2145   }
2146 
2147   set_inlining_incrementally(false);
2148 }
2149 
2150 void Compile::process_late_inline_calls_no_inline(PhaseIterGVN& igvn) {
2151   // "inlining_incrementally() == false" is used to signal that no inlining is allowed
2152   // (see LateInlineVirtualCallGenerator::do_late_inline_check() for details).
2153   // Tracking and verification of modified nodes is disabled by setting "_modified_nodes == nullptr"
2154   // as if "inlining_incrementally() == true" were set.
2155   assert(inlining_incrementally() == false, "not allowed");
2156   assert(_modified_nodes == nullptr, "not allowed");
2157   assert(_late_inlines.length() > 0, "sanity");
2158 
2159   while (_late_inlines.length() > 0) {
2160     igvn_worklist()->ensure_empty(); // should be done with igvn
2161 
2162     while (inline_incrementally_one()) {
2163       assert(!failing_internal() || failure_is_artificial(), "inconsistent");
2164     }
2165     if (failing())  return;
2166 
2167     inline_incrementally_cleanup(igvn);
2168   }
2169 }
2170 
2171 bool Compile::optimize_loops(PhaseIterGVN& igvn, LoopOptsMode mode) {
2172   if (_loop_opts_cnt > 0) {
2173     while (major_progress() && (_loop_opts_cnt > 0)) {
2174       TracePhase tp(_t_idealLoop);
2175       PhaseIdealLoop::optimize(igvn, mode);
2176       _loop_opts_cnt--;
2177       if (failing())  return false;
2178       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP_ITERATIONS, 2);
2179     }
2180   }
2181   return true;
2182 }
2183 
2184 // Remove edges from "root" to each SafePoint at a backward branch.
2185 // They were inserted during parsing (see add_safepoint()) to make
2186 // infinite loops without calls or exceptions visible to root, i.e.,
2187 // useful.
2188 void Compile::remove_root_to_sfpts_edges(PhaseIterGVN& igvn) {
2189   Node *r = root();
2190   if (r != nullptr) {
2191     for (uint i = r->req(); i < r->len(); ++i) {
2192       Node *n = r->in(i);
2193       if (n != nullptr && n->is_SafePoint()) {
2194         r->rm_prec(i);
2195         if (n->outcnt() == 0) {
2196           igvn.remove_dead_node(n);
2197         }
2198         --i;
2199       }
2200     }
2201     // Parsing may have added top inputs to the root node (Path
2202     // leading to the Halt node proven dead). Make sure we get a
2203     // chance to clean them up.
2204     igvn._worklist.push(r);
2205     igvn.optimize();
2206   }
2207 }
2208 
2209 //------------------------------Optimize---------------------------------------
2210 // Given a graph, optimize it.
2211 void Compile::Optimize() {
2212   TracePhase tp(_t_optimizer);
2213 
2214 #ifndef PRODUCT
2215   if (env()->break_at_compile()) {
2216     BREAKPOINT;
2217   }
2218 
2219 #endif
2220 
2221   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2222 #ifdef ASSERT
2223   bs->verify_gc_barriers(this, BarrierSetC2::BeforeOptimize);
2224 #endif
2225 
2226   ResourceMark rm;
2227 
2228   NOT_PRODUCT( verify_graph_edges(); )
2229 
2230   print_method(PHASE_AFTER_PARSING, 1);
2231 
2232  {
2233   // Iterative Global Value Numbering, including ideal transforms
2234   // Initialize IterGVN with types and values from parse-time GVN
2235   PhaseIterGVN igvn(initial_gvn());
2236 #ifdef ASSERT
2237   _modified_nodes = new (comp_arena()) Unique_Node_List(comp_arena());
2238 #endif
2239   {
2240     TracePhase tp(_t_iterGVN);
2241     igvn.optimize();
2242   }
2243 
2244   if (failing())  return;
2245 
2246   print_method(PHASE_ITER_GVN1, 2);
2247 
2248   process_for_unstable_if_traps(igvn);
2249 
2250   if (failing())  return;
2251 
2252   inline_incrementally(igvn);
2253 
2254   print_method(PHASE_INCREMENTAL_INLINE, 2);
2255 
2256   if (failing())  return;
2257 
2258   if (eliminate_boxing()) {
2259     // Inline valueOf() methods now.
2260     inline_boxing_calls(igvn);
2261 
2262     if (failing())  return;
2263 
2264     if (AlwaysIncrementalInline || StressIncrementalInlining) {
2265       inline_incrementally(igvn);
2266     }
2267 
2268     print_method(PHASE_INCREMENTAL_BOXING_INLINE, 2);
2269 
2270     if (failing())  return;
2271   }
2272 
2273   // Remove the speculative part of types and clean up the graph from
2274   // the extra CastPP nodes whose only purpose is to carry them. Do
2275   // that early so that optimizations are not disrupted by the extra
2276   // CastPP nodes.
2277   remove_speculative_types(igvn);
2278 
2279   if (failing())  return;
2280 
2281   // No more new expensive nodes will be added to the list from here
2282   // so keep only the actual candidates for optimizations.
2283   cleanup_expensive_nodes(igvn);
2284 
2285   if (failing())  return;
2286 
2287   assert(EnableVectorSupport || !has_vbox_nodes(), "sanity");
2288   if (EnableVectorSupport && has_vbox_nodes()) {
2289     TracePhase tp(_t_vector);
2290     PhaseVector pv(igvn);
2291     pv.optimize_vector_boxes();
2292     if (failing())  return;
2293     print_method(PHASE_ITER_GVN_AFTER_VECTOR, 2);
2294   }
2295   assert(!has_vbox_nodes(), "sanity");
2296 
2297   if (!failing() && RenumberLiveNodes && live_nodes() + NodeLimitFudgeFactor < unique()) {
2298     Compile::TracePhase tp(_t_renumberLive);
2299     igvn_worklist()->ensure_empty(); // should be done with igvn
2300     {
2301       ResourceMark rm;
2302       PhaseRenumberLive prl(initial_gvn(), *igvn_worklist());
2303     }
2304     igvn.reset_from_gvn(initial_gvn());
2305     igvn.optimize();
2306     if (failing()) return;
2307   }
2308 
2309   // Now that all inlining is over and no PhaseRemoveUseless will run, cut edge from root to loop
2310   // safepoints
2311   remove_root_to_sfpts_edges(igvn);
2312 
2313   if (failing())  return;
2314 
2315   // Perform escape analysis
2316   if (do_escape_analysis() && ConnectionGraph::has_candidates(this)) {
2317     if (has_loops()) {
2318       // Cleanup graph (remove dead nodes).
2319       TracePhase tp(_t_idealLoop);
2320       PhaseIdealLoop::optimize(igvn, LoopOptsMaxUnroll);
2321       if (failing())  return;
2322     }
2323     bool progress;
2324     print_method(PHASE_PHASEIDEAL_BEFORE_EA, 2);
2325     do {
2326       ConnectionGraph::do_analysis(this, &igvn);
2327 
2328       if (failing())  return;
2329 
2330       int mcount = macro_count(); // Record number of allocations and locks before IGVN
2331 
2332       // Optimize out fields loads from scalar replaceable allocations.
2333       igvn.optimize();
2334       print_method(PHASE_ITER_GVN_AFTER_EA, 2);
2335 
2336       if (failing()) return;
2337 
2338       if (congraph() != nullptr && macro_count() > 0) {
2339         TracePhase tp(_t_macroEliminate);
2340         PhaseMacroExpand mexp(igvn);
2341         mexp.eliminate_macro_nodes();
2342         if (failing()) return;
2343 
2344         igvn.set_delay_transform(false);
2345         igvn.optimize();
2346         if (failing()) return;
2347 
2348         print_method(PHASE_ITER_GVN_AFTER_ELIMINATION, 2);
2349       }
2350 
2351       ConnectionGraph::verify_ram_nodes(this, root());
2352       if (failing())  return;
2353 
2354       progress = do_iterative_escape_analysis() &&
2355                  (macro_count() < mcount) &&
2356                  ConnectionGraph::has_candidates(this);
2357       // Try again if candidates exist and made progress
2358       // by removing some allocations and/or locks.
2359     } while (progress);
2360   }
2361 
2362   // Loop transforms on the ideal graph.  Range Check Elimination,
2363   // peeling, unrolling, etc.
2364 
2365   // Set loop opts counter
2366   if((_loop_opts_cnt > 0) && (has_loops() || has_split_ifs())) {
2367     {
2368       TracePhase tp(_t_idealLoop);
2369       PhaseIdealLoop::optimize(igvn, LoopOptsDefault);
2370       _loop_opts_cnt--;
2371       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP1, 2);
2372       if (failing())  return;
2373     }
2374     // Loop opts pass if partial peeling occurred in previous pass
2375     if(PartialPeelLoop && major_progress() && (_loop_opts_cnt > 0)) {
2376       TracePhase tp(_t_idealLoop);
2377       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2378       _loop_opts_cnt--;
2379       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP2, 2);
2380       if (failing())  return;
2381     }
2382     // Loop opts pass for loop-unrolling before CCP
2383     if(major_progress() && (_loop_opts_cnt > 0)) {
2384       TracePhase tp(_t_idealLoop);
2385       PhaseIdealLoop::optimize(igvn, LoopOptsSkipSplitIf);
2386       _loop_opts_cnt--;
2387       if (major_progress()) print_method(PHASE_PHASEIDEALLOOP3, 2);
2388     }
2389     if (!failing()) {
2390       // Verify that last round of loop opts produced a valid graph
2391       PhaseIdealLoop::verify(igvn);
2392     }
2393   }
2394   if (failing())  return;
2395 
2396   // Conditional Constant Propagation;
2397   print_method(PHASE_BEFORE_CCP1, 2);
2398   PhaseCCP ccp( &igvn );
2399   assert( true, "Break here to ccp.dump_nodes_and_types(_root,999,1)");
2400   {
2401     TracePhase tp(_t_ccp);
2402     ccp.do_transform();
2403   }
2404   print_method(PHASE_CCP1, 2);
2405 
2406   assert( true, "Break here to ccp.dump_old2new_map()");
2407 
2408   // Iterative Global Value Numbering, including ideal transforms
2409   {
2410     TracePhase tp(_t_iterGVN2);
2411     igvn.reset_from_igvn(&ccp);
2412     igvn.optimize();
2413   }
2414   print_method(PHASE_ITER_GVN2, 2);
2415 
2416   if (failing())  return;
2417 
2418   // Loop transforms on the ideal graph.  Range Check Elimination,
2419   // peeling, unrolling, etc.
2420   if (!optimize_loops(igvn, LoopOptsDefault)) {
2421     return;
2422   }
2423 
2424   if (failing())  return;
2425 
2426   C->clear_major_progress(); // ensure that major progress is now clear
2427 
2428   process_for_post_loop_opts_igvn(igvn);
2429 
2430   if (failing())  return;
2431 
2432 #ifdef ASSERT
2433   bs->verify_gc_barriers(this, BarrierSetC2::BeforeMacroExpand);
2434 #endif
2435 
2436   {
2437     TracePhase tp(_t_macroExpand);
2438     print_method(PHASE_BEFORE_MACRO_EXPANSION, 3);
2439     PhaseMacroExpand  mex(igvn);
2440     if (mex.expand_macro_nodes()) {
2441       assert(failing(), "must bail out w/ explicit message");
2442       return;
2443     }
2444     print_method(PHASE_AFTER_MACRO_EXPANSION, 2);
2445   }
2446 
2447   {
2448     TracePhase tp(_t_barrierExpand);
2449     if (bs->expand_barriers(this, igvn)) {
2450       assert(failing(), "must bail out w/ explicit message");
2451       return;
2452     }
2453     print_method(PHASE_BARRIER_EXPANSION, 2);
2454   }
2455 
2456   if (C->max_vector_size() > 0) {
2457     C->optimize_logic_cones(igvn);
2458     igvn.optimize();
2459     if (failing()) return;
2460   }
2461 
2462   DEBUG_ONLY( _modified_nodes = nullptr; )
2463 
2464   assert(igvn._worklist.size() == 0, "not empty");
2465 
2466   assert(_late_inlines.length() == 0 || IncrementalInlineMH || IncrementalInlineVirtual, "not empty");
2467 
2468   if (_late_inlines.length() > 0) {
2469     // More opportunities to optimize virtual and MH calls.
2470     // Though it's maybe too late to perform inlining, strength-reducing them to direct calls is still an option.
2471     process_late_inline_calls_no_inline(igvn);
2472     if (failing())  return;
2473   }
2474  } // (End scope of igvn; run destructor if necessary for asserts.)
2475 
2476  check_no_dead_use();
2477 
2478  // We will never use the NodeHash table any more. Clear it so that final_graph_reshaping does not have
2479  // to remove hashes to unlock nodes for modifications.
2480  C->node_hash()->clear();
2481 
2482  // A method with only infinite loops has no edges entering loops from root
2483  {
2484    TracePhase tp(_t_graphReshaping);
2485    if (final_graph_reshaping()) {
2486      assert(failing(), "must bail out w/ explicit message");
2487      return;
2488    }
2489  }
2490 
2491  print_method(PHASE_OPTIMIZE_FINISHED, 2);
2492  DEBUG_ONLY(set_phase_optimize_finished();)
2493 }
2494 
2495 #ifdef ASSERT
2496 void Compile::check_no_dead_use() const {
2497   ResourceMark rm;
2498   Unique_Node_List wq;
2499   wq.push(root());
2500   for (uint i = 0; i < wq.size(); ++i) {
2501     Node* n = wq.at(i);
2502     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
2503       Node* u = n->fast_out(j);
2504       if (u->outcnt() == 0 && !u->is_Con()) {
2505         u->dump();
2506         fatal("no reachable node should have no use");
2507       }
2508       wq.push(u);
2509     }
2510   }
2511 }
2512 #endif
2513 
2514 void Compile::inline_vector_reboxing_calls() {
2515   if (C->_vector_reboxing_late_inlines.length() > 0) {
2516     _late_inlines_pos = C->_late_inlines.length();
2517     while (_vector_reboxing_late_inlines.length() > 0) {
2518       CallGenerator* cg = _vector_reboxing_late_inlines.pop();
2519       cg->do_late_inline();
2520       if (failing())  return;
2521       print_method(PHASE_INLINE_VECTOR_REBOX, 3, cg->call_node());
2522     }
2523     _vector_reboxing_late_inlines.trunc_to(0);
2524   }
2525 }
2526 
2527 bool Compile::has_vbox_nodes() {
2528   if (C->_vector_reboxing_late_inlines.length() > 0) {
2529     return true;
2530   }
2531   for (int macro_idx = C->macro_count() - 1; macro_idx >= 0; macro_idx--) {
2532     Node * n = C->macro_node(macro_idx);
2533     assert(n->is_macro(), "only macro nodes expected here");
2534     if (n->Opcode() == Op_VectorUnbox || n->Opcode() == Op_VectorBox || n->Opcode() == Op_VectorBoxAllocate) {
2535       return true;
2536     }
2537   }
2538   return false;
2539 }
2540 
2541 //---------------------------- Bitwise operation packing optimization ---------------------------
2542 
2543 static bool is_vector_unary_bitwise_op(Node* n) {
2544   return n->Opcode() == Op_XorV &&
2545          VectorNode::is_vector_bitwise_not_pattern(n);
2546 }
2547 
2548 static bool is_vector_binary_bitwise_op(Node* n) {
2549   switch (n->Opcode()) {
2550     case Op_AndV:
2551     case Op_OrV:
2552       return true;
2553 
2554     case Op_XorV:
2555       return !is_vector_unary_bitwise_op(n);
2556 
2557     default:
2558       return false;
2559   }
2560 }
2561 
2562 static bool is_vector_ternary_bitwise_op(Node* n) {
2563   return n->Opcode() == Op_MacroLogicV;
2564 }
2565 
2566 static bool is_vector_bitwise_op(Node* n) {
2567   return is_vector_unary_bitwise_op(n)  ||
2568          is_vector_binary_bitwise_op(n) ||
2569          is_vector_ternary_bitwise_op(n);
2570 }
2571 
2572 static bool is_vector_bitwise_cone_root(Node* n) {
2573   if (n->bottom_type()->isa_vectmask() || !is_vector_bitwise_op(n)) {
2574     return false;
2575   }
2576   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2577     if (is_vector_bitwise_op(n->fast_out(i))) {
2578       return false;
2579     }
2580   }
2581   return true;
2582 }
2583 
2584 static uint collect_unique_inputs(Node* n, Unique_Node_List& inputs) {
2585   uint cnt = 0;
2586   if (is_vector_bitwise_op(n)) {
2587     uint inp_cnt = n->is_predicated_vector() ? n->req()-1 : n->req();
2588     if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2589       for (uint i = 1; i < inp_cnt; i++) {
2590         Node* in = n->in(i);
2591         bool skip = VectorNode::is_all_ones_vector(in);
2592         if (!skip && !inputs.member(in)) {
2593           inputs.push(in);
2594           cnt++;
2595         }
2596       }
2597       assert(cnt <= 1, "not unary");
2598     } else {
2599       uint last_req = inp_cnt;
2600       if (is_vector_ternary_bitwise_op(n)) {
2601         last_req = inp_cnt - 1; // skip last input
2602       }
2603       for (uint i = 1; i < last_req; i++) {
2604         Node* def = n->in(i);
2605         if (!inputs.member(def)) {
2606           inputs.push(def);
2607           cnt++;
2608         }
2609       }
2610     }
2611   } else { // not a bitwise operations
2612     if (!inputs.member(n)) {
2613       inputs.push(n);
2614       cnt++;
2615     }
2616   }
2617   return cnt;
2618 }
2619 
2620 void Compile::collect_logic_cone_roots(Unique_Node_List& list) {
2621   Unique_Node_List useful_nodes;
2622   C->identify_useful_nodes(useful_nodes);
2623 
2624   for (uint i = 0; i < useful_nodes.size(); i++) {
2625     Node* n = useful_nodes.at(i);
2626     if (is_vector_bitwise_cone_root(n)) {
2627       list.push(n);
2628     }
2629   }
2630 }
2631 
2632 Node* Compile::xform_to_MacroLogicV(PhaseIterGVN& igvn,
2633                                     const TypeVect* vt,
2634                                     Unique_Node_List& partition,
2635                                     Unique_Node_List& inputs) {
2636   assert(partition.size() == 2 || partition.size() == 3, "not supported");
2637   assert(inputs.size()    == 2 || inputs.size()    == 3, "not supported");
2638   assert(Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type()), "not supported");
2639 
2640   Node* in1 = inputs.at(0);
2641   Node* in2 = inputs.at(1);
2642   Node* in3 = (inputs.size() == 3 ? inputs.at(2) : in2);
2643 
2644   uint func = compute_truth_table(partition, inputs);
2645 
2646   Node* pn = partition.at(partition.size() - 1);
2647   Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr;
2648   return igvn.transform(MacroLogicVNode::make(igvn, in1, in2, in3, mask, func, vt));
2649 }
2650 
2651 static uint extract_bit(uint func, uint pos) {
2652   return (func & (1 << pos)) >> pos;
2653 }
2654 
2655 //
2656 //  A macro logic node represents a truth table. It has 4 inputs,
2657 //  First three inputs corresponds to 3 columns of a truth table
2658 //  and fourth input captures the logic function.
2659 //
2660 //  eg.  fn = (in1 AND in2) OR in3;
2661 //
2662 //      MacroNode(in1,in2,in3,fn)
2663 //
2664 //  -----------------
2665 //  in1 in2 in3  fn
2666 //  -----------------
2667 //  0    0   0    0
2668 //  0    0   1    1
2669 //  0    1   0    0
2670 //  0    1   1    1
2671 //  1    0   0    0
2672 //  1    0   1    1
2673 //  1    1   0    1
2674 //  1    1   1    1
2675 //
2676 
2677 uint Compile::eval_macro_logic_op(uint func, uint in1 , uint in2, uint in3) {
2678   int res = 0;
2679   for (int i = 0; i < 8; i++) {
2680     int bit1 = extract_bit(in1, i);
2681     int bit2 = extract_bit(in2, i);
2682     int bit3 = extract_bit(in3, i);
2683 
2684     int func_bit_pos = (bit1 << 2 | bit2 << 1 | bit3);
2685     int func_bit = extract_bit(func, func_bit_pos);
2686 
2687     res |= func_bit << i;
2688   }
2689   return res;
2690 }
2691 
2692 static uint eval_operand(Node* n, ResourceHashtable<Node*,uint>& eval_map) {
2693   assert(n != nullptr, "");
2694   assert(eval_map.contains(n), "absent");
2695   return *(eval_map.get(n));
2696 }
2697 
2698 static void eval_operands(Node* n,
2699                           uint& func1, uint& func2, uint& func3,
2700                           ResourceHashtable<Node*,uint>& eval_map) {
2701   assert(is_vector_bitwise_op(n), "");
2702 
2703   if (is_vector_unary_bitwise_op(n)) {
2704     Node* opnd = n->in(1);
2705     if (VectorNode::is_vector_bitwise_not_pattern(n) && VectorNode::is_all_ones_vector(opnd)) {
2706       opnd = n->in(2);
2707     }
2708     func1 = eval_operand(opnd, eval_map);
2709   } else if (is_vector_binary_bitwise_op(n)) {
2710     func1 = eval_operand(n->in(1), eval_map);
2711     func2 = eval_operand(n->in(2), eval_map);
2712   } else {
2713     assert(is_vector_ternary_bitwise_op(n), "unknown operation");
2714     func1 = eval_operand(n->in(1), eval_map);
2715     func2 = eval_operand(n->in(2), eval_map);
2716     func3 = eval_operand(n->in(3), eval_map);
2717   }
2718 }
2719 
2720 uint Compile::compute_truth_table(Unique_Node_List& partition, Unique_Node_List& inputs) {
2721   assert(inputs.size() <= 3, "sanity");
2722   ResourceMark rm;
2723   uint res = 0;
2724   ResourceHashtable<Node*,uint> eval_map;
2725 
2726   // Populate precomputed functions for inputs.
2727   // Each input corresponds to one column of 3 input truth-table.
2728   uint input_funcs[] = { 0xAA,   // (_, _, c) -> c
2729                          0xCC,   // (_, b, _) -> b
2730                          0xF0 }; // (a, _, _) -> a
2731   for (uint i = 0; i < inputs.size(); i++) {
2732     eval_map.put(inputs.at(i), input_funcs[2-i]);
2733   }
2734 
2735   for (uint i = 0; i < partition.size(); i++) {
2736     Node* n = partition.at(i);
2737 
2738     uint func1 = 0, func2 = 0, func3 = 0;
2739     eval_operands(n, func1, func2, func3, eval_map);
2740 
2741     switch (n->Opcode()) {
2742       case Op_OrV:
2743         assert(func3 == 0, "not binary");
2744         res = func1 | func2;
2745         break;
2746       case Op_AndV:
2747         assert(func3 == 0, "not binary");
2748         res = func1 & func2;
2749         break;
2750       case Op_XorV:
2751         if (VectorNode::is_vector_bitwise_not_pattern(n)) {
2752           assert(func2 == 0 && func3 == 0, "not unary");
2753           res = (~func1) & 0xFF;
2754         } else {
2755           assert(func3 == 0, "not binary");
2756           res = func1 ^ func2;
2757         }
2758         break;
2759       case Op_MacroLogicV:
2760         // Ordering of inputs may change during evaluation of sub-tree
2761         // containing MacroLogic node as a child node, thus a re-evaluation
2762         // makes sure that function is evaluated in context of current
2763         // inputs.
2764         res = eval_macro_logic_op(n->in(4)->get_int(), func1, func2, func3);
2765         break;
2766 
2767       default: assert(false, "not supported: %s", n->Name());
2768     }
2769     assert(res <= 0xFF, "invalid");
2770     eval_map.put(n, res);
2771   }
2772   return res;
2773 }
2774 
2775 // Criteria under which nodes gets packed into a macro logic node:-
2776 //  1) Parent and both child nodes are all unmasked or masked with
2777 //     same predicates.
2778 //  2) Masked parent can be packed with left child if it is predicated
2779 //     and both have same predicates.
2780 //  3) Masked parent can be packed with right child if its un-predicated
2781 //     or has matching predication condition.
2782 //  4) An unmasked parent can be packed with an unmasked child.
2783 bool Compile::compute_logic_cone(Node* n, Unique_Node_List& partition, Unique_Node_List& inputs) {
2784   assert(partition.size() == 0, "not empty");
2785   assert(inputs.size() == 0, "not empty");
2786   if (is_vector_ternary_bitwise_op(n)) {
2787     return false;
2788   }
2789 
2790   bool is_unary_op = is_vector_unary_bitwise_op(n);
2791   if (is_unary_op) {
2792     assert(collect_unique_inputs(n, inputs) == 1, "not unary");
2793     return false; // too few inputs
2794   }
2795 
2796   bool pack_left_child = true;
2797   bool pack_right_child = true;
2798 
2799   bool left_child_LOP = is_vector_bitwise_op(n->in(1));
2800   bool right_child_LOP = is_vector_bitwise_op(n->in(2));
2801 
2802   int left_child_input_cnt = 0;
2803   int right_child_input_cnt = 0;
2804 
2805   bool parent_is_predicated = n->is_predicated_vector();
2806   bool left_child_predicated = n->in(1)->is_predicated_vector();
2807   bool right_child_predicated = n->in(2)->is_predicated_vector();
2808 
2809   Node* parent_pred = parent_is_predicated ? n->in(n->req()-1) : nullptr;
2810   Node* left_child_pred = left_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr;
2811   Node* right_child_pred = right_child_predicated ? n->in(1)->in(n->in(1)->req()-1) : nullptr;
2812 
2813   do {
2814     if (pack_left_child && left_child_LOP &&
2815         ((!parent_is_predicated && !left_child_predicated) ||
2816         ((parent_is_predicated && left_child_predicated &&
2817           parent_pred == left_child_pred)))) {
2818        partition.push(n->in(1));
2819        left_child_input_cnt = collect_unique_inputs(n->in(1), inputs);
2820     } else {
2821        inputs.push(n->in(1));
2822        left_child_input_cnt = 1;
2823     }
2824 
2825     if (pack_right_child && right_child_LOP &&
2826         (!right_child_predicated ||
2827          (right_child_predicated && parent_is_predicated &&
2828           parent_pred == right_child_pred))) {
2829        partition.push(n->in(2));
2830        right_child_input_cnt = collect_unique_inputs(n->in(2), inputs);
2831     } else {
2832        inputs.push(n->in(2));
2833        right_child_input_cnt = 1;
2834     }
2835 
2836     if (inputs.size() > 3) {
2837       assert(partition.size() > 0, "");
2838       inputs.clear();
2839       partition.clear();
2840       if (left_child_input_cnt > right_child_input_cnt) {
2841         pack_left_child = false;
2842       } else {
2843         pack_right_child = false;
2844       }
2845     } else {
2846       break;
2847     }
2848   } while(true);
2849 
2850   if(partition.size()) {
2851     partition.push(n);
2852   }
2853 
2854   return (partition.size() == 2 || partition.size() == 3) &&
2855          (inputs.size()    == 2 || inputs.size()    == 3);
2856 }
2857 
2858 void Compile::process_logic_cone_root(PhaseIterGVN &igvn, Node *n, VectorSet &visited) {
2859   assert(is_vector_bitwise_op(n), "not a root");
2860 
2861   visited.set(n->_idx);
2862 
2863   // 1) Do a DFS walk over the logic cone.
2864   for (uint i = 1; i < n->req(); i++) {
2865     Node* in = n->in(i);
2866     if (!visited.test(in->_idx) && is_vector_bitwise_op(in)) {
2867       process_logic_cone_root(igvn, in, visited);
2868     }
2869   }
2870 
2871   // 2) Bottom up traversal: Merge node[s] with
2872   // the parent to form macro logic node.
2873   Unique_Node_List partition;
2874   Unique_Node_List inputs;
2875   if (compute_logic_cone(n, partition, inputs)) {
2876     const TypeVect* vt = n->bottom_type()->is_vect();
2877     Node* pn = partition.at(partition.size() - 1);
2878     Node* mask = pn->is_predicated_vector() ? pn->in(pn->req()-1) : nullptr;
2879     if (mask == nullptr ||
2880         Matcher::match_rule_supported_vector_masked(Op_MacroLogicV, vt->length(), vt->element_basic_type())) {
2881       Node* macro_logic = xform_to_MacroLogicV(igvn, vt, partition, inputs);
2882       VectorNode::trace_new_vector(macro_logic, "MacroLogic");
2883       igvn.replace_node(n, macro_logic);
2884     }
2885   }
2886 }
2887 
2888 void Compile::optimize_logic_cones(PhaseIterGVN &igvn) {
2889   ResourceMark rm;
2890   if (Matcher::match_rule_supported(Op_MacroLogicV)) {
2891     Unique_Node_List list;
2892     collect_logic_cone_roots(list);
2893 
2894     while (list.size() > 0) {
2895       Node* n = list.pop();
2896       const TypeVect* vt = n->bottom_type()->is_vect();
2897       bool supported = Matcher::match_rule_supported_vector(Op_MacroLogicV, vt->length(), vt->element_basic_type());
2898       if (supported) {
2899         VectorSet visited(comp_arena());
2900         process_logic_cone_root(igvn, n, visited);
2901       }
2902     }
2903   }
2904 }
2905 
2906 //------------------------------Code_Gen---------------------------------------
2907 // Given a graph, generate code for it
2908 void Compile::Code_Gen() {
2909   if (failing()) {
2910     return;
2911   }
2912 
2913   // Perform instruction selection.  You might think we could reclaim Matcher
2914   // memory PDQ, but actually the Matcher is used in generating spill code.
2915   // Internals of the Matcher (including some VectorSets) must remain live
2916   // for awhile - thus I cannot reclaim Matcher memory lest a VectorSet usage
2917   // set a bit in reclaimed memory.
2918 
2919   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2920   // nodes.  Mapping is only valid at the root of each matched subtree.
2921   NOT_PRODUCT( verify_graph_edges(); )
2922 
2923   Matcher matcher;
2924   _matcher = &matcher;
2925   {
2926     TracePhase tp(_t_matcher);
2927     matcher.match();
2928     if (failing()) {
2929       return;
2930     }
2931   }
2932   // In debug mode can dump m._nodes.dump() for mapping of ideal to machine
2933   // nodes.  Mapping is only valid at the root of each matched subtree.
2934   NOT_PRODUCT( verify_graph_edges(); )
2935 
2936   // If you have too many nodes, or if matching has failed, bail out
2937   check_node_count(0, "out of nodes matching instructions");
2938   if (failing()) {
2939     return;
2940   }
2941 
2942   print_method(PHASE_MATCHING, 2);
2943 
2944   // Build a proper-looking CFG
2945   PhaseCFG cfg(node_arena(), root(), matcher);
2946   if (failing()) {
2947     return;
2948   }
2949   _cfg = &cfg;
2950   {
2951     TracePhase tp(_t_scheduler);
2952     bool success = cfg.do_global_code_motion();
2953     if (!success) {
2954       return;
2955     }
2956 
2957     print_method(PHASE_GLOBAL_CODE_MOTION, 2);
2958     NOT_PRODUCT( verify_graph_edges(); )
2959     cfg.verify();
2960     if (failing()) {
2961       return;
2962     }
2963   }
2964 
2965   PhaseChaitin regalloc(unique(), cfg, matcher, false);
2966   _regalloc = &regalloc;
2967   {
2968     TracePhase tp(_t_registerAllocation);
2969     // Perform register allocation.  After Chaitin, use-def chains are
2970     // no longer accurate (at spill code) and so must be ignored.
2971     // Node->LRG->reg mappings are still accurate.
2972     _regalloc->Register_Allocate();
2973 
2974     // Bail out if the allocator builds too many nodes
2975     if (failing()) {
2976       return;
2977     }
2978 
2979     print_method(PHASE_REGISTER_ALLOCATION, 2);
2980   }
2981 
2982   // Prior to register allocation we kept empty basic blocks in case the
2983   // the allocator needed a place to spill.  After register allocation we
2984   // are not adding any new instructions.  If any basic block is empty, we
2985   // can now safely remove it.
2986   {
2987     TracePhase tp(_t_blockOrdering);
2988     cfg.remove_empty_blocks();
2989     if (do_freq_based_layout()) {
2990       PhaseBlockLayout layout(cfg);
2991     } else {
2992       cfg.set_loop_alignment();
2993     }
2994     cfg.fixup_flow();
2995     cfg.remove_unreachable_blocks();
2996     cfg.verify_dominator_tree();
2997     print_method(PHASE_BLOCK_ORDERING, 3);
2998   }
2999 
3000   // Apply peephole optimizations
3001   if( OptoPeephole ) {
3002     TracePhase tp(_t_peephole);
3003     PhasePeephole peep( _regalloc, cfg);
3004     peep.do_transform();
3005     print_method(PHASE_PEEPHOLE, 3);
3006   }
3007 
3008   // Do late expand if CPU requires this.
3009   if (Matcher::require_postalloc_expand) {
3010     TracePhase tp(_t_postalloc_expand);
3011     cfg.postalloc_expand(_regalloc);
3012     print_method(PHASE_POSTALLOC_EXPAND, 3);
3013   }
3014 
3015   // Convert Nodes to instruction bits in a buffer
3016   {
3017     TracePhase tp(_t_output);
3018     PhaseOutput output;
3019     output.Output();
3020     if (failing())  return;
3021     output.install();
3022     print_method(PHASE_FINAL_CODE, 1); // Compile::_output is not null here
3023   }
3024 
3025   // He's dead, Jim.
3026   _cfg     = (PhaseCFG*)((intptr_t)0xdeadbeef);
3027   _regalloc = (PhaseChaitin*)((intptr_t)0xdeadbeef);
3028 }
3029 
3030 //------------------------------Final_Reshape_Counts---------------------------
3031 // This class defines counters to help identify when a method
3032 // may/must be executed using hardware with only 24-bit precision.
3033 struct Final_Reshape_Counts : public StackObj {
3034   int  _call_count;             // count non-inlined 'common' calls
3035   int  _float_count;            // count float ops requiring 24-bit precision
3036   int  _double_count;           // count double ops requiring more precision
3037   int  _java_call_count;        // count non-inlined 'java' calls
3038   int  _inner_loop_count;       // count loops which need alignment
3039   VectorSet _visited;           // Visitation flags
3040   Node_List _tests;             // Set of IfNodes & PCTableNodes
3041 
3042   Final_Reshape_Counts() :
3043     _call_count(0), _float_count(0), _double_count(0),
3044     _java_call_count(0), _inner_loop_count(0) { }
3045 
3046   void inc_call_count  () { _call_count  ++; }
3047   void inc_float_count () { _float_count ++; }
3048   void inc_double_count() { _double_count++; }
3049   void inc_java_call_count() { _java_call_count++; }
3050   void inc_inner_loop_count() { _inner_loop_count++; }
3051 
3052   int  get_call_count  () const { return _call_count  ; }
3053   int  get_float_count () const { return _float_count ; }
3054   int  get_double_count() const { return _double_count; }
3055   int  get_java_call_count() const { return _java_call_count; }
3056   int  get_inner_loop_count() const { return _inner_loop_count; }
3057 };
3058 
3059 //------------------------------final_graph_reshaping_impl----------------------
3060 // Implement items 1-5 from final_graph_reshaping below.
3061 void Compile::final_graph_reshaping_impl(Node *n, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3062 
3063   if ( n->outcnt() == 0 ) return; // dead node
3064   uint nop = n->Opcode();
3065 
3066   // Check for 2-input instruction with "last use" on right input.
3067   // Swap to left input.  Implements item (2).
3068   if( n->req() == 3 &&          // two-input instruction
3069       n->in(1)->outcnt() > 1 && // left use is NOT a last use
3070       (!n->in(1)->is_Phi() || n->in(1)->in(2) != n) && // it is not data loop
3071       n->in(2)->outcnt() == 1 &&// right use IS a last use
3072       !n->in(2)->is_Con() ) {   // right use is not a constant
3073     // Check for commutative opcode
3074     switch( nop ) {
3075     case Op_AddI:  case Op_AddF:  case Op_AddD:  case Op_AddL:
3076     case Op_MaxI:  case Op_MaxL:  case Op_MaxF:  case Op_MaxD:
3077     case Op_MinI:  case Op_MinL:  case Op_MinF:  case Op_MinD:
3078     case Op_MulI:  case Op_MulF:  case Op_MulD:  case Op_MulL:
3079     case Op_AndL:  case Op_XorL:  case Op_OrL:
3080     case Op_AndI:  case Op_XorI:  case Op_OrI: {
3081       // Move "last use" input to left by swapping inputs
3082       n->swap_edges(1, 2);
3083       break;
3084     }
3085     default:
3086       break;
3087     }
3088   }
3089 
3090 #ifdef ASSERT
3091   if( n->is_Mem() ) {
3092     int alias_idx = get_alias_index(n->as_Mem()->adr_type());
3093     assert( n->in(0) != nullptr || alias_idx != Compile::AliasIdxRaw ||
3094             // oop will be recorded in oop map if load crosses safepoint
3095             (n->is_Load() && (n->as_Load()->bottom_type()->isa_oopptr() ||
3096                               LoadNode::is_immutable_value(n->in(MemNode::Address)))),
3097             "raw memory operations should have control edge");
3098   }
3099   if (n->is_MemBar()) {
3100     MemBarNode* mb = n->as_MemBar();
3101     if (mb->trailing_store() || mb->trailing_load_store()) {
3102       assert(mb->leading_membar()->trailing_membar() == mb, "bad membar pair");
3103       Node* mem = BarrierSet::barrier_set()->barrier_set_c2()->step_over_gc_barrier(mb->in(MemBarNode::Precedent));
3104       assert((mb->trailing_store() && mem->is_Store() && mem->as_Store()->is_release()) ||
3105              (mb->trailing_load_store() && mem->is_LoadStore()), "missing mem op");
3106     } else if (mb->leading()) {
3107       assert(mb->trailing_membar()->leading_membar() == mb, "bad membar pair");
3108     }
3109   }
3110 #endif
3111   // Count FPU ops and common calls, implements item (3)
3112   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->final_graph_reshaping(this, n, nop, dead_nodes);
3113   if (!gc_handled) {
3114     final_graph_reshaping_main_switch(n, frc, nop, dead_nodes);
3115   }
3116 
3117   // Collect CFG split points
3118   if (n->is_MultiBranch() && !n->is_RangeCheck()) {
3119     frc._tests.push(n);
3120   }
3121 }
3122 
3123 void Compile::handle_div_mod_op(Node* n, BasicType bt, bool is_unsigned) {
3124   if (!UseDivMod) {
3125     return;
3126   }
3127 
3128   // Check if "a % b" and "a / b" both exist
3129   Node* d = n->find_similar(Op_DivIL(bt, is_unsigned));
3130   if (d == nullptr) {
3131     return;
3132   }
3133 
3134   // Replace them with a fused divmod if supported
3135   if (Matcher::has_match_rule(Op_DivModIL(bt, is_unsigned))) {
3136     DivModNode* divmod = DivModNode::make(n, bt, is_unsigned);
3137     // If the divisor input for a Div (or Mod etc.) is not zero, then the control input of the Div is set to zero.
3138     // It could be that the divisor input is found not zero because its type is narrowed down by a CastII in the
3139     // subgraph for that input. Range check CastIIs are removed during final graph reshape. To preserve the dependency
3140     // carried by a CastII, precedence edges are added to the Div node. We need to transfer the precedence edges to the
3141     // DivMod node so the dependency is not lost.
3142     divmod->add_prec_from(n);
3143     divmod->add_prec_from(d);
3144     d->subsume_by(divmod->div_proj(), this);
3145     n->subsume_by(divmod->mod_proj(), this);
3146   } else {
3147     // Replace "a % b" with "a - ((a / b) * b)"
3148     Node* mult = MulNode::make(d, d->in(2), bt);
3149     Node* sub = SubNode::make(d->in(1), mult, bt);
3150     n->subsume_by(sub, this);
3151   }
3152 }
3153 
3154 void Compile::final_graph_reshaping_main_switch(Node* n, Final_Reshape_Counts& frc, uint nop, Unique_Node_List& dead_nodes) {
3155   switch( nop ) {
3156   // Count all float operations that may use FPU
3157   case Op_AddF:
3158   case Op_SubF:
3159   case Op_MulF:
3160   case Op_DivF:
3161   case Op_NegF:
3162   case Op_ModF:
3163   case Op_ConvI2F:
3164   case Op_ConF:
3165   case Op_CmpF:
3166   case Op_CmpF3:
3167   case Op_StoreF:
3168   case Op_LoadF:
3169   // case Op_ConvL2F: // longs are split into 32-bit halves
3170     frc.inc_float_count();
3171     break;
3172 
3173   case Op_ConvF2D:
3174   case Op_ConvD2F:
3175     frc.inc_float_count();
3176     frc.inc_double_count();
3177     break;
3178 
3179   // Count all double operations that may use FPU
3180   case Op_AddD:
3181   case Op_SubD:
3182   case Op_MulD:
3183   case Op_DivD:
3184   case Op_NegD:
3185   case Op_ModD:
3186   case Op_ConvI2D:
3187   case Op_ConvD2I:
3188   // case Op_ConvL2D: // handled by leaf call
3189   // case Op_ConvD2L: // handled by leaf call
3190   case Op_ConD:
3191   case Op_CmpD:
3192   case Op_CmpD3:
3193   case Op_StoreD:
3194   case Op_LoadD:
3195   case Op_LoadD_unaligned:
3196     frc.inc_double_count();
3197     break;
3198   case Op_Opaque1:              // Remove Opaque Nodes before matching
3199     n->subsume_by(n->in(1), this);
3200     break;
3201   case Op_CallStaticJava:
3202   case Op_CallJava:
3203   case Op_CallDynamicJava:
3204     frc.inc_java_call_count(); // Count java call site;
3205   case Op_CallRuntime:
3206   case Op_CallLeaf:
3207   case Op_CallLeafVector:
3208   case Op_CallLeafNoFP: {
3209     assert (n->is_Call(), "");
3210     CallNode *call = n->as_Call();
3211     // Count call sites where the FP mode bit would have to be flipped.
3212     // Do not count uncommon runtime calls:
3213     // uncommon_trap, _complete_monitor_locking, _complete_monitor_unlocking,
3214     // _new_Java, _new_typeArray, _new_objArray, _rethrow_Java, ...
3215     if (!call->is_CallStaticJava() || !call->as_CallStaticJava()->_name) {
3216       frc.inc_call_count();   // Count the call site
3217     } else {                  // See if uncommon argument is shared
3218       Node *n = call->in(TypeFunc::Parms);
3219       int nop = n->Opcode();
3220       // Clone shared simple arguments to uncommon calls, item (1).
3221       if (n->outcnt() > 1 &&
3222           !n->is_Proj() &&
3223           nop != Op_CreateEx &&
3224           nop != Op_CheckCastPP &&
3225           nop != Op_DecodeN &&
3226           nop != Op_DecodeNKlass &&
3227           !n->is_Mem() &&
3228           !n->is_Phi()) {
3229         Node *x = n->clone();
3230         call->set_req(TypeFunc::Parms, x);
3231       }
3232     }
3233     break;
3234   }
3235   case Op_StoreB:
3236   case Op_StoreC:
3237   case Op_StoreI:
3238   case Op_StoreL:
3239   case Op_CompareAndSwapB:
3240   case Op_CompareAndSwapS:
3241   case Op_CompareAndSwapI:
3242   case Op_CompareAndSwapL:
3243   case Op_CompareAndSwapP:
3244   case Op_CompareAndSwapN:
3245   case Op_WeakCompareAndSwapB:
3246   case Op_WeakCompareAndSwapS:
3247   case Op_WeakCompareAndSwapI:
3248   case Op_WeakCompareAndSwapL:
3249   case Op_WeakCompareAndSwapP:
3250   case Op_WeakCompareAndSwapN:
3251   case Op_CompareAndExchangeB:
3252   case Op_CompareAndExchangeS:
3253   case Op_CompareAndExchangeI:
3254   case Op_CompareAndExchangeL:
3255   case Op_CompareAndExchangeP:
3256   case Op_CompareAndExchangeN:
3257   case Op_GetAndAddS:
3258   case Op_GetAndAddB:
3259   case Op_GetAndAddI:
3260   case Op_GetAndAddL:
3261   case Op_GetAndSetS:
3262   case Op_GetAndSetB:
3263   case Op_GetAndSetI:
3264   case Op_GetAndSetL:
3265   case Op_GetAndSetP:
3266   case Op_GetAndSetN:
3267   case Op_StoreP:
3268   case Op_StoreN:
3269   case Op_StoreNKlass:
3270   case Op_LoadB:
3271   case Op_LoadUB:
3272   case Op_LoadUS:
3273   case Op_LoadI:
3274   case Op_LoadKlass:
3275   case Op_LoadNKlass:
3276   case Op_LoadL:
3277   case Op_LoadL_unaligned:
3278   case Op_LoadP:
3279   case Op_LoadN:
3280   case Op_LoadRange:
3281   case Op_LoadS:
3282     break;
3283 
3284   case Op_AddP: {               // Assert sane base pointers
3285     Node *addp = n->in(AddPNode::Address);
3286     assert( !addp->is_AddP() ||
3287             addp->in(AddPNode::Base)->is_top() || // Top OK for allocation
3288             addp->in(AddPNode::Base) == n->in(AddPNode::Base),
3289             "Base pointers must match (addp %u)", addp->_idx );
3290 #ifdef _LP64
3291     if ((UseCompressedOops || UseCompressedClassPointers) &&
3292         addp->Opcode() == Op_ConP &&
3293         addp == n->in(AddPNode::Base) &&
3294         n->in(AddPNode::Offset)->is_Con()) {
3295       // If the transformation of ConP to ConN+DecodeN is beneficial depends
3296       // on the platform and on the compressed oops mode.
3297       // Use addressing with narrow klass to load with offset on x86.
3298       // Some platforms can use the constant pool to load ConP.
3299       // Do this transformation here since IGVN will convert ConN back to ConP.
3300       const Type* t = addp->bottom_type();
3301       bool is_oop   = t->isa_oopptr() != nullptr;
3302       bool is_klass = t->isa_klassptr() != nullptr;
3303 
3304       if ((is_oop   && UseCompressedOops          && Matcher::const_oop_prefer_decode()  ) ||
3305           (is_klass && UseCompressedClassPointers && Matcher::const_klass_prefer_decode() &&
3306            t->isa_klassptr()->exact_klass()->is_in_encoding_range())) {
3307         Node* nn = nullptr;
3308 
3309         int op = is_oop ? Op_ConN : Op_ConNKlass;
3310 
3311         // Look for existing ConN node of the same exact type.
3312         Node* r  = root();
3313         uint cnt = r->outcnt();
3314         for (uint i = 0; i < cnt; i++) {
3315           Node* m = r->raw_out(i);
3316           if (m!= nullptr && m->Opcode() == op &&
3317               m->bottom_type()->make_ptr() == t) {
3318             nn = m;
3319             break;
3320           }
3321         }
3322         if (nn != nullptr) {
3323           // Decode a narrow oop to match address
3324           // [R12 + narrow_oop_reg<<3 + offset]
3325           if (is_oop) {
3326             nn = new DecodeNNode(nn, t);
3327           } else {
3328             nn = new DecodeNKlassNode(nn, t);
3329           }
3330           // Check for succeeding AddP which uses the same Base.
3331           // Otherwise we will run into the assertion above when visiting that guy.
3332           for (uint i = 0; i < n->outcnt(); ++i) {
3333             Node *out_i = n->raw_out(i);
3334             if (out_i && out_i->is_AddP() && out_i->in(AddPNode::Base) == addp) {
3335               out_i->set_req(AddPNode::Base, nn);
3336 #ifdef ASSERT
3337               for (uint j = 0; j < out_i->outcnt(); ++j) {
3338                 Node *out_j = out_i->raw_out(j);
3339                 assert(out_j == nullptr || !out_j->is_AddP() || out_j->in(AddPNode::Base) != addp,
3340                        "more than 2 AddP nodes in a chain (out_j %u)", out_j->_idx);
3341               }
3342 #endif
3343             }
3344           }
3345           n->set_req(AddPNode::Base, nn);
3346           n->set_req(AddPNode::Address, nn);
3347           if (addp->outcnt() == 0) {
3348             addp->disconnect_inputs(this);
3349           }
3350         }
3351       }
3352     }
3353 #endif
3354     break;
3355   }
3356 
3357   case Op_CastPP: {
3358     // Remove CastPP nodes to gain more freedom during scheduling but
3359     // keep the dependency they encode as control or precedence edges
3360     // (if control is set already) on memory operations. Some CastPP
3361     // nodes don't have a control (don't carry a dependency): skip
3362     // those.
3363     if (n->in(0) != nullptr) {
3364       ResourceMark rm;
3365       Unique_Node_List wq;
3366       wq.push(n);
3367       for (uint next = 0; next < wq.size(); ++next) {
3368         Node *m = wq.at(next);
3369         for (DUIterator_Fast imax, i = m->fast_outs(imax); i < imax; i++) {
3370           Node* use = m->fast_out(i);
3371           if (use->is_Mem() || use->is_EncodeNarrowPtr()) {
3372             use->ensure_control_or_add_prec(n->in(0));
3373           } else {
3374             switch(use->Opcode()) {
3375             case Op_AddP:
3376             case Op_DecodeN:
3377             case Op_DecodeNKlass:
3378             case Op_CheckCastPP:
3379             case Op_CastPP:
3380               wq.push(use);
3381               break;
3382             }
3383           }
3384         }
3385       }
3386     }
3387     const bool is_LP64 = LP64_ONLY(true) NOT_LP64(false);
3388     if (is_LP64 && n->in(1)->is_DecodeN() && Matcher::gen_narrow_oop_implicit_null_checks()) {
3389       Node* in1 = n->in(1);
3390       const Type* t = n->bottom_type();
3391       Node* new_in1 = in1->clone();
3392       new_in1->as_DecodeN()->set_type(t);
3393 
3394       if (!Matcher::narrow_oop_use_complex_address()) {
3395         //
3396         // x86, ARM and friends can handle 2 adds in addressing mode
3397         // and Matcher can fold a DecodeN node into address by using
3398         // a narrow oop directly and do implicit null check in address:
3399         //
3400         // [R12 + narrow_oop_reg<<3 + offset]
3401         // NullCheck narrow_oop_reg
3402         //
3403         // On other platforms (Sparc) we have to keep new DecodeN node and
3404         // use it to do implicit null check in address:
3405         //
3406         // decode_not_null narrow_oop_reg, base_reg
3407         // [base_reg + offset]
3408         // NullCheck base_reg
3409         //
3410         // Pin the new DecodeN node to non-null path on these platform (Sparc)
3411         // to keep the information to which null check the new DecodeN node
3412         // corresponds to use it as value in implicit_null_check().
3413         //
3414         new_in1->set_req(0, n->in(0));
3415       }
3416 
3417       n->subsume_by(new_in1, this);
3418       if (in1->outcnt() == 0) {
3419         in1->disconnect_inputs(this);
3420       }
3421     } else {
3422       n->subsume_by(n->in(1), this);
3423       if (n->outcnt() == 0) {
3424         n->disconnect_inputs(this);
3425       }
3426     }
3427     break;
3428   }
3429   case Op_CastII: {
3430     n->as_CastII()->remove_range_check_cast(this);
3431     break;
3432   }
3433 #ifdef _LP64
3434   case Op_CmpP:
3435     // Do this transformation here to preserve CmpPNode::sub() and
3436     // other TypePtr related Ideal optimizations (for example, ptr nullness).
3437     if (n->in(1)->is_DecodeNarrowPtr() || n->in(2)->is_DecodeNarrowPtr()) {
3438       Node* in1 = n->in(1);
3439       Node* in2 = n->in(2);
3440       if (!in1->is_DecodeNarrowPtr()) {
3441         in2 = in1;
3442         in1 = n->in(2);
3443       }
3444       assert(in1->is_DecodeNarrowPtr(), "sanity");
3445 
3446       Node* new_in2 = nullptr;
3447       if (in2->is_DecodeNarrowPtr()) {
3448         assert(in2->Opcode() == in1->Opcode(), "must be same node type");
3449         new_in2 = in2->in(1);
3450       } else if (in2->Opcode() == Op_ConP) {
3451         const Type* t = in2->bottom_type();
3452         if (t == TypePtr::NULL_PTR) {
3453           assert(in1->is_DecodeN(), "compare klass to null?");
3454           // Don't convert CmpP null check into CmpN if compressed
3455           // oops implicit null check is not generated.
3456           // This will allow to generate normal oop implicit null check.
3457           if (Matcher::gen_narrow_oop_implicit_null_checks())
3458             new_in2 = ConNode::make(TypeNarrowOop::NULL_PTR);
3459           //
3460           // This transformation together with CastPP transformation above
3461           // will generated code for implicit null checks for compressed oops.
3462           //
3463           // The original code after Optimize()
3464           //
3465           //    LoadN memory, narrow_oop_reg
3466           //    decode narrow_oop_reg, base_reg
3467           //    CmpP base_reg, nullptr
3468           //    CastPP base_reg // NotNull
3469           //    Load [base_reg + offset], val_reg
3470           //
3471           // after these transformations will be
3472           //
3473           //    LoadN memory, narrow_oop_reg
3474           //    CmpN narrow_oop_reg, nullptr
3475           //    decode_not_null narrow_oop_reg, base_reg
3476           //    Load [base_reg + offset], val_reg
3477           //
3478           // and the uncommon path (== nullptr) will use narrow_oop_reg directly
3479           // since narrow oops can be used in debug info now (see the code in
3480           // final_graph_reshaping_walk()).
3481           //
3482           // At the end the code will be matched to
3483           // on x86:
3484           //
3485           //    Load_narrow_oop memory, narrow_oop_reg
3486           //    Load [R12 + narrow_oop_reg<<3 + offset], val_reg
3487           //    NullCheck narrow_oop_reg
3488           //
3489           // and on sparc:
3490           //
3491           //    Load_narrow_oop memory, narrow_oop_reg
3492           //    decode_not_null narrow_oop_reg, base_reg
3493           //    Load [base_reg + offset], val_reg
3494           //    NullCheck base_reg
3495           //
3496         } else if (t->isa_oopptr()) {
3497           new_in2 = ConNode::make(t->make_narrowoop());
3498         } else if (t->isa_klassptr()) {
3499           new_in2 = ConNode::make(t->make_narrowklass());
3500         }
3501       }
3502       if (new_in2 != nullptr) {
3503         Node* cmpN = new CmpNNode(in1->in(1), new_in2);
3504         n->subsume_by(cmpN, this);
3505         if (in1->outcnt() == 0) {
3506           in1->disconnect_inputs(this);
3507         }
3508         if (in2->outcnt() == 0) {
3509           in2->disconnect_inputs(this);
3510         }
3511       }
3512     }
3513     break;
3514 
3515   case Op_DecodeN:
3516   case Op_DecodeNKlass:
3517     assert(!n->in(1)->is_EncodeNarrowPtr(), "should be optimized out");
3518     // DecodeN could be pinned when it can't be fold into
3519     // an address expression, see the code for Op_CastPP above.
3520     assert(n->in(0) == nullptr || (UseCompressedOops && !Matcher::narrow_oop_use_complex_address()), "no control");
3521     break;
3522 
3523   case Op_EncodeP:
3524   case Op_EncodePKlass: {
3525     Node* in1 = n->in(1);
3526     if (in1->is_DecodeNarrowPtr()) {
3527       n->subsume_by(in1->in(1), this);
3528     } else if (in1->Opcode() == Op_ConP) {
3529       const Type* t = in1->bottom_type();
3530       if (t == TypePtr::NULL_PTR) {
3531         assert(t->isa_oopptr(), "null klass?");
3532         n->subsume_by(ConNode::make(TypeNarrowOop::NULL_PTR), this);
3533       } else if (t->isa_oopptr()) {
3534         n->subsume_by(ConNode::make(t->make_narrowoop()), this);
3535       } else if (t->isa_klassptr()) {
3536         n->subsume_by(ConNode::make(t->make_narrowklass()), this);
3537       }
3538     }
3539     if (in1->outcnt() == 0) {
3540       in1->disconnect_inputs(this);
3541     }
3542     break;
3543   }
3544 
3545   case Op_Proj: {
3546     if (OptimizeStringConcat || IncrementalInline) {
3547       ProjNode* proj = n->as_Proj();
3548       if (proj->_is_io_use) {
3549         assert(proj->_con == TypeFunc::I_O || proj->_con == TypeFunc::Memory, "");
3550         // Separate projections were used for the exception path which
3551         // are normally removed by a late inline.  If it wasn't inlined
3552         // then they will hang around and should just be replaced with
3553         // the original one. Merge them.
3554         Node* non_io_proj = proj->in(0)->as_Multi()->proj_out_or_null(proj->_con, false /*is_io_use*/);
3555         if (non_io_proj  != nullptr) {
3556           proj->subsume_by(non_io_proj , this);
3557         }
3558       }
3559     }
3560     break;
3561   }
3562 
3563   case Op_Phi:
3564     if (n->as_Phi()->bottom_type()->isa_narrowoop() || n->as_Phi()->bottom_type()->isa_narrowklass()) {
3565       // The EncodeP optimization may create Phi with the same edges
3566       // for all paths. It is not handled well by Register Allocator.
3567       Node* unique_in = n->in(1);
3568       assert(unique_in != nullptr, "");
3569       uint cnt = n->req();
3570       for (uint i = 2; i < cnt; i++) {
3571         Node* m = n->in(i);
3572         assert(m != nullptr, "");
3573         if (unique_in != m)
3574           unique_in = nullptr;
3575       }
3576       if (unique_in != nullptr) {
3577         n->subsume_by(unique_in, this);
3578       }
3579     }
3580     break;
3581 
3582 #endif
3583 
3584   case Op_ModI:
3585     handle_div_mod_op(n, T_INT, false);
3586     break;
3587 
3588   case Op_ModL:
3589     handle_div_mod_op(n, T_LONG, false);
3590     break;
3591 
3592   case Op_UModI:
3593     handle_div_mod_op(n, T_INT, true);
3594     break;
3595 
3596   case Op_UModL:
3597     handle_div_mod_op(n, T_LONG, true);
3598     break;
3599 
3600   case Op_LoadVector:
3601   case Op_StoreVector:
3602 #ifdef ASSERT
3603     // Add VerifyVectorAlignment node between adr and load / store.
3604     if (VerifyAlignVector && Matcher::has_match_rule(Op_VerifyVectorAlignment)) {
3605       bool must_verify_alignment = n->is_LoadVector() ? n->as_LoadVector()->must_verify_alignment() :
3606                                                         n->as_StoreVector()->must_verify_alignment();
3607       if (must_verify_alignment) {
3608         jlong vector_width = n->is_LoadVector() ? n->as_LoadVector()->memory_size() :
3609                                                   n->as_StoreVector()->memory_size();
3610         // The memory access should be aligned to the vector width in bytes.
3611         // However, the underlying array is possibly less well aligned, but at least
3612         // to ObjectAlignmentInBytes. Hence, even if multiple arrays are accessed in
3613         // a loop we can expect at least the following alignment:
3614         jlong guaranteed_alignment = MIN2(vector_width, (jlong)ObjectAlignmentInBytes);
3615         assert(2 <= guaranteed_alignment && guaranteed_alignment <= 64, "alignment must be in range");
3616         assert(is_power_of_2(guaranteed_alignment), "alignment must be power of 2");
3617         // Create mask from alignment. e.g. 0b1000 -> 0b0111
3618         jlong mask = guaranteed_alignment - 1;
3619         Node* mask_con = ConLNode::make(mask);
3620         VerifyVectorAlignmentNode* va = new VerifyVectorAlignmentNode(n->in(MemNode::Address), mask_con);
3621         n->set_req(MemNode::Address, va);
3622       }
3623     }
3624 #endif
3625     break;
3626 
3627   case Op_LoadVectorGather:
3628   case Op_StoreVectorScatter:
3629   case Op_LoadVectorGatherMasked:
3630   case Op_StoreVectorScatterMasked:
3631   case Op_VectorCmpMasked:
3632   case Op_VectorMaskGen:
3633   case Op_LoadVectorMasked:
3634   case Op_StoreVectorMasked:
3635     break;
3636 
3637   case Op_AddReductionVI:
3638   case Op_AddReductionVL:
3639   case Op_AddReductionVF:
3640   case Op_AddReductionVD:
3641   case Op_MulReductionVI:
3642   case Op_MulReductionVL:
3643   case Op_MulReductionVF:
3644   case Op_MulReductionVD:
3645   case Op_MinReductionV:
3646   case Op_MaxReductionV:
3647   case Op_AndReductionV:
3648   case Op_OrReductionV:
3649   case Op_XorReductionV:
3650     break;
3651 
3652   case Op_PackB:
3653   case Op_PackS:
3654   case Op_PackI:
3655   case Op_PackF:
3656   case Op_PackL:
3657   case Op_PackD:
3658     if (n->req()-1 > 2) {
3659       // Replace many operand PackNodes with a binary tree for matching
3660       PackNode* p = (PackNode*) n;
3661       Node* btp = p->binary_tree_pack(1, n->req());
3662       n->subsume_by(btp, this);
3663     }
3664     break;
3665   case Op_Loop:
3666     assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0, "should have been turned into a counted loop");
3667   case Op_CountedLoop:
3668   case Op_LongCountedLoop:
3669   case Op_OuterStripMinedLoop:
3670     if (n->as_Loop()->is_inner_loop()) {
3671       frc.inc_inner_loop_count();
3672     }
3673     n->as_Loop()->verify_strip_mined(0);
3674     break;
3675   case Op_LShiftI:
3676   case Op_RShiftI:
3677   case Op_URShiftI:
3678   case Op_LShiftL:
3679   case Op_RShiftL:
3680   case Op_URShiftL:
3681     if (Matcher::need_masked_shift_count) {
3682       // The cpu's shift instructions don't restrict the count to the
3683       // lower 5/6 bits. We need to do the masking ourselves.
3684       Node* in2 = n->in(2);
3685       juint mask = (n->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
3686       const TypeInt* t = in2->find_int_type();
3687       if (t != nullptr && t->is_con()) {
3688         juint shift = t->get_con();
3689         if (shift > mask) { // Unsigned cmp
3690           n->set_req(2, ConNode::make(TypeInt::make(shift & mask)));
3691         }
3692       } else {
3693         if (t == nullptr || t->_lo < 0 || t->_hi > (int)mask) {
3694           Node* shift = new AndINode(in2, ConNode::make(TypeInt::make(mask)));
3695           n->set_req(2, shift);
3696         }
3697       }
3698       if (in2->outcnt() == 0) { // Remove dead node
3699         in2->disconnect_inputs(this);
3700       }
3701     }
3702     break;
3703   case Op_MemBarStoreStore:
3704   case Op_MemBarRelease:
3705     // Break the link with AllocateNode: it is no longer useful and
3706     // confuses register allocation.
3707     if (n->req() > MemBarNode::Precedent) {
3708       n->set_req(MemBarNode::Precedent, top());
3709     }
3710     break;
3711   case Op_MemBarAcquire: {
3712     if (n->as_MemBar()->trailing_load() && n->req() > MemBarNode::Precedent) {
3713       // At parse time, the trailing MemBarAcquire for a volatile load
3714       // is created with an edge to the load. After optimizations,
3715       // that input may be a chain of Phis. If those phis have no
3716       // other use, then the MemBarAcquire keeps them alive and
3717       // register allocation can be confused.
3718       dead_nodes.push(n->in(MemBarNode::Precedent));
3719       n->set_req(MemBarNode::Precedent, top());
3720     }
3721     break;
3722   }
3723   case Op_Blackhole:
3724     break;
3725   case Op_RangeCheck: {
3726     RangeCheckNode* rc = n->as_RangeCheck();
3727     Node* iff = new IfNode(rc->in(0), rc->in(1), rc->_prob, rc->_fcnt);
3728     n->subsume_by(iff, this);
3729     frc._tests.push(iff);
3730     break;
3731   }
3732   case Op_ConvI2L: {
3733     if (!Matcher::convi2l_type_required) {
3734       // Code generation on some platforms doesn't need accurate
3735       // ConvI2L types. Widening the type can help remove redundant
3736       // address computations.
3737       n->as_Type()->set_type(TypeLong::INT);
3738       ResourceMark rm;
3739       Unique_Node_List wq;
3740       wq.push(n);
3741       for (uint next = 0; next < wq.size(); next++) {
3742         Node *m = wq.at(next);
3743 
3744         for(;;) {
3745           // Loop over all nodes with identical inputs edges as m
3746           Node* k = m->find_similar(m->Opcode());
3747           if (k == nullptr) {
3748             break;
3749           }
3750           // Push their uses so we get a chance to remove node made
3751           // redundant
3752           for (DUIterator_Fast imax, i = k->fast_outs(imax); i < imax; i++) {
3753             Node* u = k->fast_out(i);
3754             if (u->Opcode() == Op_LShiftL ||
3755                 u->Opcode() == Op_AddL ||
3756                 u->Opcode() == Op_SubL ||
3757                 u->Opcode() == Op_AddP) {
3758               wq.push(u);
3759             }
3760           }
3761           // Replace all nodes with identical edges as m with m
3762           k->subsume_by(m, this);
3763         }
3764       }
3765     }
3766     break;
3767   }
3768   case Op_CmpUL: {
3769     if (!Matcher::has_match_rule(Op_CmpUL)) {
3770       // No support for unsigned long comparisons
3771       ConINode* sign_pos = new ConINode(TypeInt::make(BitsPerLong - 1));
3772       Node* sign_bit_mask = new RShiftLNode(n->in(1), sign_pos);
3773       Node* orl = new OrLNode(n->in(1), sign_bit_mask);
3774       ConLNode* remove_sign_mask = new ConLNode(TypeLong::make(max_jlong));
3775       Node* andl = new AndLNode(orl, remove_sign_mask);
3776       Node* cmp = new CmpLNode(andl, n->in(2));
3777       n->subsume_by(cmp, this);
3778     }
3779     break;
3780   }
3781 #ifdef ASSERT
3782   case Op_ConNKlass: {
3783     const TypePtr* tp = n->as_Type()->type()->make_ptr();
3784     ciKlass* klass = tp->is_klassptr()->exact_klass();
3785     assert(klass->is_in_encoding_range(), "klass cannot be compressed");
3786     break;
3787   }
3788 #endif
3789   default:
3790     assert(!n->is_Call(), "");
3791     assert(!n->is_Mem(), "");
3792     assert(nop != Op_ProfileBoolean, "should be eliminated during IGVN");
3793     break;
3794   }
3795 }
3796 
3797 //------------------------------final_graph_reshaping_walk---------------------
3798 // Replacing Opaque nodes with their input in final_graph_reshaping_impl(),
3799 // requires that the walk visits a node's inputs before visiting the node.
3800 void Compile::final_graph_reshaping_walk(Node_Stack& nstack, Node* root, Final_Reshape_Counts& frc, Unique_Node_List& dead_nodes) {
3801   Unique_Node_List sfpt;
3802 
3803   frc._visited.set(root->_idx); // first, mark node as visited
3804   uint cnt = root->req();
3805   Node *n = root;
3806   uint  i = 0;
3807   while (true) {
3808     if (i < cnt) {
3809       // Place all non-visited non-null inputs onto stack
3810       Node* m = n->in(i);
3811       ++i;
3812       if (m != nullptr && !frc._visited.test_set(m->_idx)) {
3813         if (m->is_SafePoint() && m->as_SafePoint()->jvms() != nullptr) {
3814           // compute worst case interpreter size in case of a deoptimization
3815           update_interpreter_frame_size(m->as_SafePoint()->jvms()->interpreter_frame_size());
3816 
3817           sfpt.push(m);
3818         }
3819         cnt = m->req();
3820         nstack.push(n, i); // put on stack parent and next input's index
3821         n = m;
3822         i = 0;
3823       }
3824     } else {
3825       // Now do post-visit work
3826       final_graph_reshaping_impl(n, frc, dead_nodes);
3827       if (nstack.is_empty())
3828         break;             // finished
3829       n = nstack.node();   // Get node from stack
3830       cnt = n->req();
3831       i = nstack.index();
3832       nstack.pop();        // Shift to the next node on stack
3833     }
3834   }
3835 
3836   // Skip next transformation if compressed oops are not used.
3837   if ((UseCompressedOops && !Matcher::gen_narrow_oop_implicit_null_checks()) ||
3838       (!UseCompressedOops && !UseCompressedClassPointers))
3839     return;
3840 
3841   // Go over safepoints nodes to skip DecodeN/DecodeNKlass nodes for debug edges.
3842   // It could be done for an uncommon traps or any safepoints/calls
3843   // if the DecodeN/DecodeNKlass node is referenced only in a debug info.
3844   while (sfpt.size() > 0) {
3845     n = sfpt.pop();
3846     JVMState *jvms = n->as_SafePoint()->jvms();
3847     assert(jvms != nullptr, "sanity");
3848     int start = jvms->debug_start();
3849     int end   = n->req();
3850     bool is_uncommon = (n->is_CallStaticJava() &&
3851                         n->as_CallStaticJava()->uncommon_trap_request() != 0);
3852     for (int j = start; j < end; j++) {
3853       Node* in = n->in(j);
3854       if (in->is_DecodeNarrowPtr()) {
3855         bool safe_to_skip = true;
3856         if (!is_uncommon ) {
3857           // Is it safe to skip?
3858           for (uint i = 0; i < in->outcnt(); i++) {
3859             Node* u = in->raw_out(i);
3860             if (!u->is_SafePoint() ||
3861                 (u->is_Call() && u->as_Call()->has_non_debug_use(n))) {
3862               safe_to_skip = false;
3863             }
3864           }
3865         }
3866         if (safe_to_skip) {
3867           n->set_req(j, in->in(1));
3868         }
3869         if (in->outcnt() == 0) {
3870           in->disconnect_inputs(this);
3871         }
3872       }
3873     }
3874   }
3875 }
3876 
3877 //------------------------------final_graph_reshaping--------------------------
3878 // Final Graph Reshaping.
3879 //
3880 // (1) Clone simple inputs to uncommon calls, so they can be scheduled late
3881 //     and not commoned up and forced early.  Must come after regular
3882 //     optimizations to avoid GVN undoing the cloning.  Clone constant
3883 //     inputs to Loop Phis; these will be split by the allocator anyways.
3884 //     Remove Opaque nodes.
3885 // (2) Move last-uses by commutative operations to the left input to encourage
3886 //     Intel update-in-place two-address operations and better register usage
3887 //     on RISCs.  Must come after regular optimizations to avoid GVN Ideal
3888 //     calls canonicalizing them back.
3889 // (3) Count the number of double-precision FP ops, single-precision FP ops
3890 //     and call sites.  On Intel, we can get correct rounding either by
3891 //     forcing singles to memory (requires extra stores and loads after each
3892 //     FP bytecode) or we can set a rounding mode bit (requires setting and
3893 //     clearing the mode bit around call sites).  The mode bit is only used
3894 //     if the relative frequency of single FP ops to calls is low enough.
3895 //     This is a key transform for SPEC mpeg_audio.
3896 // (4) Detect infinite loops; blobs of code reachable from above but not
3897 //     below.  Several of the Code_Gen algorithms fail on such code shapes,
3898 //     so we simply bail out.  Happens a lot in ZKM.jar, but also happens
3899 //     from time to time in other codes (such as -Xcomp finalizer loops, etc).
3900 //     Detection is by looking for IfNodes where only 1 projection is
3901 //     reachable from below or CatchNodes missing some targets.
3902 // (5) Assert for insane oop offsets in debug mode.
3903 
3904 bool Compile::final_graph_reshaping() {
3905   // an infinite loop may have been eliminated by the optimizer,
3906   // in which case the graph will be empty.
3907   if (root()->req() == 1) {
3908     // Do not compile method that is only a trivial infinite loop,
3909     // since the content of the loop may have been eliminated.
3910     record_method_not_compilable("trivial infinite loop");
3911     return true;
3912   }
3913 
3914   // Expensive nodes have their control input set to prevent the GVN
3915   // from freely commoning them. There's no GVN beyond this point so
3916   // no need to keep the control input. We want the expensive nodes to
3917   // be freely moved to the least frequent code path by gcm.
3918   assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
3919   for (int i = 0; i < expensive_count(); i++) {
3920     _expensive_nodes.at(i)->set_req(0, nullptr);
3921   }
3922 
3923   Final_Reshape_Counts frc;
3924 
3925   // Visit everybody reachable!
3926   // Allocate stack of size C->live_nodes()/2 to avoid frequent realloc
3927   Node_Stack nstack(live_nodes() >> 1);
3928   Unique_Node_List dead_nodes;
3929   final_graph_reshaping_walk(nstack, root(), frc, dead_nodes);
3930 
3931   // Check for unreachable (from below) code (i.e., infinite loops).
3932   for( uint i = 0; i < frc._tests.size(); i++ ) {
3933     MultiBranchNode *n = frc._tests[i]->as_MultiBranch();
3934     // Get number of CFG targets.
3935     // Note that PCTables include exception targets after calls.
3936     uint required_outcnt = n->required_outcnt();
3937     if (n->outcnt() != required_outcnt) {
3938       // Check for a few special cases.  Rethrow Nodes never take the
3939       // 'fall-thru' path, so expected kids is 1 less.
3940       if (n->is_PCTable() && n->in(0) && n->in(0)->in(0)) {
3941         if (n->in(0)->in(0)->is_Call()) {
3942           CallNode* call = n->in(0)->in(0)->as_Call();
3943           if (call->entry_point() == OptoRuntime::rethrow_stub()) {
3944             required_outcnt--;      // Rethrow always has 1 less kid
3945           } else if (call->req() > TypeFunc::Parms &&
3946                      call->is_CallDynamicJava()) {
3947             // Check for null receiver. In such case, the optimizer has
3948             // detected that the virtual call will always result in a null
3949             // pointer exception. The fall-through projection of this CatchNode
3950             // will not be populated.
3951             Node* arg0 = call->in(TypeFunc::Parms);
3952             if (arg0->is_Type() &&
3953                 arg0->as_Type()->type()->higher_equal(TypePtr::NULL_PTR)) {
3954               required_outcnt--;
3955             }
3956           } else if (call->entry_point() == OptoRuntime::new_array_Java() ||
3957                      call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
3958             // Check for illegal array length. In such case, the optimizer has
3959             // detected that the allocation attempt will always result in an
3960             // exception. There is no fall-through projection of this CatchNode .
3961             assert(call->is_CallStaticJava(), "static call expected");
3962             assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
3963             uint valid_length_test_input = call->req() - 1;
3964             Node* valid_length_test = call->in(valid_length_test_input);
3965             call->del_req(valid_length_test_input);
3966             if (valid_length_test->find_int_con(1) == 0) {
3967               required_outcnt--;
3968             }
3969             dead_nodes.push(valid_length_test);
3970             assert(n->outcnt() == required_outcnt, "malformed control flow");
3971             continue;
3972           }
3973         }
3974       }
3975 
3976       // Recheck with a better notion of 'required_outcnt'
3977       if (n->outcnt() != required_outcnt) {
3978         record_method_not_compilable("malformed control flow");
3979         return true;            // Not all targets reachable!
3980       }
3981     } else if (n->is_PCTable() && n->in(0) && n->in(0)->in(0) && n->in(0)->in(0)->is_Call()) {
3982       CallNode* call = n->in(0)->in(0)->as_Call();
3983       if (call->entry_point() == OptoRuntime::new_array_Java() ||
3984           call->entry_point() == OptoRuntime::new_array_nozero_Java()) {
3985         assert(call->is_CallStaticJava(), "static call expected");
3986         assert(call->req() == call->jvms()->endoff() + 1, "missing extra input");
3987         uint valid_length_test_input = call->req() - 1;
3988         dead_nodes.push(call->in(valid_length_test_input));
3989         call->del_req(valid_length_test_input); // valid length test useless now
3990       }
3991     }
3992     // Check that I actually visited all kids.  Unreached kids
3993     // must be infinite loops.
3994     for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++)
3995       if (!frc._visited.test(n->fast_out(j)->_idx)) {
3996         record_method_not_compilable("infinite loop");
3997         return true;            // Found unvisited kid; must be unreach
3998       }
3999 
4000     // Here so verification code in final_graph_reshaping_walk()
4001     // always see an OuterStripMinedLoopEnd
4002     if (n->is_OuterStripMinedLoopEnd() || n->is_LongCountedLoopEnd()) {
4003       IfNode* init_iff = n->as_If();
4004       Node* iff = new IfNode(init_iff->in(0), init_iff->in(1), init_iff->_prob, init_iff->_fcnt);
4005       n->subsume_by(iff, this);
4006     }
4007   }
4008 
4009   while (dead_nodes.size() > 0) {
4010     Node* m = dead_nodes.pop();
4011     if (m->outcnt() == 0 && m != top()) {
4012       for (uint j = 0; j < m->req(); j++) {
4013         Node* in = m->in(j);
4014         if (in != nullptr) {
4015           dead_nodes.push(in);
4016         }
4017       }
4018       m->disconnect_inputs(this);
4019     }
4020   }
4021 
4022 #ifdef IA32
4023   // If original bytecodes contained a mixture of floats and doubles
4024   // check if the optimizer has made it homogeneous, item (3).
4025   if (UseSSE == 0 &&
4026       frc.get_float_count() > 32 &&
4027       frc.get_double_count() == 0 &&
4028       (10 * frc.get_call_count() < frc.get_float_count()) ) {
4029     set_24_bit_selection_and_mode(false, true);
4030   }
4031 #endif // IA32
4032 
4033   set_java_calls(frc.get_java_call_count());
4034   set_inner_loops(frc.get_inner_loop_count());
4035 
4036   // No infinite loops, no reason to bail out.
4037   return false;
4038 }
4039 
4040 //-----------------------------too_many_traps----------------------------------
4041 // Report if there are too many traps at the current method and bci.
4042 // Return true if there was a trap, and/or PerMethodTrapLimit is exceeded.
4043 bool Compile::too_many_traps(ciMethod* method,
4044                              int bci,
4045                              Deoptimization::DeoptReason reason) {
4046   ciMethodData* md = method->method_data();
4047   if (md->is_empty()) {
4048     // Assume the trap has not occurred, or that it occurred only
4049     // because of a transient condition during start-up in the interpreter.
4050     return false;
4051   }
4052   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4053   if (md->has_trap_at(bci, m, reason) != 0) {
4054     // Assume PerBytecodeTrapLimit==0, for a more conservative heuristic.
4055     // Also, if there are multiple reasons, or if there is no per-BCI record,
4056     // assume the worst.
4057     if (log())
4058       log()->elem("observe trap='%s' count='%d'",
4059                   Deoptimization::trap_reason_name(reason),
4060                   md->trap_count(reason));
4061     return true;
4062   } else {
4063     // Ignore method/bci and see if there have been too many globally.
4064     return too_many_traps(reason, md);
4065   }
4066 }
4067 
4068 // Less-accurate variant which does not require a method and bci.
4069 bool Compile::too_many_traps(Deoptimization::DeoptReason reason,
4070                              ciMethodData* logmd) {
4071   if (trap_count(reason) >= Deoptimization::per_method_trap_limit(reason)) {
4072     // Too many traps globally.
4073     // Note that we use cumulative trap_count, not just md->trap_count.
4074     if (log()) {
4075       int mcount = (logmd == nullptr)? -1: (int)logmd->trap_count(reason);
4076       log()->elem("observe trap='%s' count='0' mcount='%d' ccount='%d'",
4077                   Deoptimization::trap_reason_name(reason),
4078                   mcount, trap_count(reason));
4079     }
4080     return true;
4081   } else {
4082     // The coast is clear.
4083     return false;
4084   }
4085 }
4086 
4087 //--------------------------too_many_recompiles--------------------------------
4088 // Report if there are too many recompiles at the current method and bci.
4089 // Consults PerBytecodeRecompilationCutoff and PerMethodRecompilationCutoff.
4090 // Is not eager to return true, since this will cause the compiler to use
4091 // Action_none for a trap point, to avoid too many recompilations.
4092 bool Compile::too_many_recompiles(ciMethod* method,
4093                                   int bci,
4094                                   Deoptimization::DeoptReason reason) {
4095   ciMethodData* md = method->method_data();
4096   if (md->is_empty()) {
4097     // Assume the trap has not occurred, or that it occurred only
4098     // because of a transient condition during start-up in the interpreter.
4099     return false;
4100   }
4101   // Pick a cutoff point well within PerBytecodeRecompilationCutoff.
4102   uint bc_cutoff = (uint) PerBytecodeRecompilationCutoff / 8;
4103   uint m_cutoff  = (uint) PerMethodRecompilationCutoff / 2 + 1;  // not zero
4104   Deoptimization::DeoptReason per_bc_reason
4105     = Deoptimization::reason_recorded_per_bytecode_if_any(reason);
4106   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? this->method() : nullptr;
4107   if ((per_bc_reason == Deoptimization::Reason_none
4108        || md->has_trap_at(bci, m, reason) != 0)
4109       // The trap frequency measure we care about is the recompile count:
4110       && md->trap_recompiled_at(bci, m)
4111       && md->overflow_recompile_count() >= bc_cutoff) {
4112     // Do not emit a trap here if it has already caused recompilations.
4113     // Also, if there are multiple reasons, or if there is no per-BCI record,
4114     // assume the worst.
4115     if (log())
4116       log()->elem("observe trap='%s recompiled' count='%d' recompiles2='%d'",
4117                   Deoptimization::trap_reason_name(reason),
4118                   md->trap_count(reason),
4119                   md->overflow_recompile_count());
4120     return true;
4121   } else if (trap_count(reason) != 0
4122              && decompile_count() >= m_cutoff) {
4123     // Too many recompiles globally, and we have seen this sort of trap.
4124     // Use cumulative decompile_count, not just md->decompile_count.
4125     if (log())
4126       log()->elem("observe trap='%s' count='%d' mcount='%d' decompiles='%d' mdecompiles='%d'",
4127                   Deoptimization::trap_reason_name(reason),
4128                   md->trap_count(reason), trap_count(reason),
4129                   md->decompile_count(), decompile_count());
4130     return true;
4131   } else {
4132     // The coast is clear.
4133     return false;
4134   }
4135 }
4136 
4137 // Compute when not to trap. Used by matching trap based nodes and
4138 // NullCheck optimization.
4139 void Compile::set_allowed_deopt_reasons() {
4140   _allowed_reasons = 0;
4141   if (is_method_compilation()) {
4142     for (int rs = (int)Deoptimization::Reason_none+1; rs < Compile::trapHistLength; rs++) {
4143       assert(rs < BitsPerInt, "recode bit map");
4144       if (!too_many_traps((Deoptimization::DeoptReason) rs)) {
4145         _allowed_reasons |= nth_bit(rs);
4146       }
4147     }
4148   }
4149 }
4150 
4151 bool Compile::needs_clinit_barrier(ciMethod* method, ciMethod* accessing_method) {
4152   return method->is_static() && needs_clinit_barrier(method->holder(), accessing_method);
4153 }
4154 
4155 bool Compile::needs_clinit_barrier(ciField* field, ciMethod* accessing_method) {
4156   return field->is_static() && needs_clinit_barrier(field->holder(), accessing_method);
4157 }
4158 
4159 bool Compile::needs_clinit_barrier(ciInstanceKlass* holder, ciMethod* accessing_method) {
4160   if (holder->is_initialized()) {
4161     return false;
4162   }
4163   if (holder->is_being_initialized()) {
4164     if (accessing_method->holder() == holder) {
4165       // Access inside a class. The barrier can be elided when access happens in <clinit>,
4166       // <init>, or a static method. In all those cases, there was an initialization
4167       // barrier on the holder klass passed.
4168       if (accessing_method->is_static_initializer() ||
4169           accessing_method->is_object_initializer() ||
4170           accessing_method->is_static()) {
4171         return false;
4172       }
4173     } else if (accessing_method->holder()->is_subclass_of(holder)) {
4174       // Access from a subclass. The barrier can be elided only when access happens in <clinit>.
4175       // In case of <init> or a static method, the barrier is on the subclass is not enough:
4176       // child class can become fully initialized while its parent class is still being initialized.
4177       if (accessing_method->is_static_initializer()) {
4178         return false;
4179       }
4180     }
4181     ciMethod* root = method(); // the root method of compilation
4182     if (root != accessing_method) {
4183       return needs_clinit_barrier(holder, root); // check access in the context of compilation root
4184     }
4185   }
4186   return true;
4187 }
4188 
4189 #ifndef PRODUCT
4190 //------------------------------verify_bidirectional_edges---------------------
4191 // For each input edge to a node (ie - for each Use-Def edge), verify that
4192 // there is a corresponding Def-Use edge.
4193 void Compile::verify_bidirectional_edges(Unique_Node_List &visited) {
4194   // Allocate stack of size C->live_nodes()/16 to avoid frequent realloc
4195   uint stack_size = live_nodes() >> 4;
4196   Node_List nstack(MAX2(stack_size, (uint)OptoNodeListSize));
4197   nstack.push(_root);
4198 
4199   while (nstack.size() > 0) {
4200     Node* n = nstack.pop();
4201     if (visited.member(n)) {
4202       continue;
4203     }
4204     visited.push(n);
4205 
4206     // Walk over all input edges, checking for correspondence
4207     uint length = n->len();
4208     for (uint i = 0; i < length; i++) {
4209       Node* in = n->in(i);
4210       if (in != nullptr && !visited.member(in)) {
4211         nstack.push(in); // Put it on stack
4212       }
4213       if (in != nullptr && !in->is_top()) {
4214         // Count instances of `next`
4215         int cnt = 0;
4216         for (uint idx = 0; idx < in->_outcnt; idx++) {
4217           if (in->_out[idx] == n) {
4218             cnt++;
4219           }
4220         }
4221         assert(cnt > 0, "Failed to find Def-Use edge.");
4222         // Check for duplicate edges
4223         // walk the input array downcounting the input edges to n
4224         for (uint j = 0; j < length; j++) {
4225           if (n->in(j) == in) {
4226             cnt--;
4227           }
4228         }
4229         assert(cnt == 0, "Mismatched edge count.");
4230       } else if (in == nullptr) {
4231         assert(i == 0 || i >= n->req() ||
4232                n->is_Region() || n->is_Phi() || n->is_ArrayCopy() ||
4233                (n->is_Unlock() && i == (n->req() - 1)) ||
4234                (n->is_MemBar() && i == 5), // the precedence edge to a membar can be removed during macro node expansion
4235               "only region, phi, arraycopy, unlock or membar nodes have null data edges");
4236       } else {
4237         assert(in->is_top(), "sanity");
4238         // Nothing to check.
4239       }
4240     }
4241   }
4242 }
4243 
4244 //------------------------------verify_graph_edges---------------------------
4245 // Walk the Graph and verify that there is a one-to-one correspondence
4246 // between Use-Def edges and Def-Use edges in the graph.
4247 void Compile::verify_graph_edges(bool no_dead_code) {
4248   if (VerifyGraphEdges) {
4249     Unique_Node_List visited;
4250 
4251     // Call graph walk to check edges
4252     verify_bidirectional_edges(visited);
4253     if (no_dead_code) {
4254       // Now make sure that no visited node is used by an unvisited node.
4255       bool dead_nodes = false;
4256       Unique_Node_List checked;
4257       while (visited.size() > 0) {
4258         Node* n = visited.pop();
4259         checked.push(n);
4260         for (uint i = 0; i < n->outcnt(); i++) {
4261           Node* use = n->raw_out(i);
4262           if (checked.member(use))  continue;  // already checked
4263           if (visited.member(use))  continue;  // already in the graph
4264           if (use->is_Con())        continue;  // a dead ConNode is OK
4265           // At this point, we have found a dead node which is DU-reachable.
4266           if (!dead_nodes) {
4267             tty->print_cr("*** Dead nodes reachable via DU edges:");
4268             dead_nodes = true;
4269           }
4270           use->dump(2);
4271           tty->print_cr("---");
4272           checked.push(use);  // No repeats; pretend it is now checked.
4273         }
4274       }
4275       assert(!dead_nodes, "using nodes must be reachable from root");
4276     }
4277   }
4278 }
4279 #endif
4280 
4281 // The Compile object keeps track of failure reasons separately from the ciEnv.
4282 // This is required because there is not quite a 1-1 relation between the
4283 // ciEnv and its compilation task and the Compile object.  Note that one
4284 // ciEnv might use two Compile objects, if C2Compiler::compile_method decides
4285 // to backtrack and retry without subsuming loads.  Other than this backtracking
4286 // behavior, the Compile's failure reason is quietly copied up to the ciEnv
4287 // by the logic in C2Compiler.
4288 void Compile::record_failure(const char* reason DEBUG_ONLY(COMMA bool allow_multiple_failures)) {
4289   if (log() != nullptr) {
4290     log()->elem("failure reason='%s' phase='compile'", reason);
4291   }
4292   if (_failure_reason.get() == nullptr) {
4293     // Record the first failure reason.
4294     _failure_reason.set(reason);
4295     if (CaptureBailoutInformation) {
4296       _first_failure_details = new CompilationFailureInfo(reason);
4297     }
4298   } else {
4299     assert(!StressBailout || allow_multiple_failures, "should have handled previous failure.");
4300   }
4301 
4302   if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
4303     C->print_method(PHASE_FAILURE, 1);
4304   }
4305   _root = nullptr;  // flush the graph, too
4306 }
4307 
4308 Compile::TracePhase::TracePhase(const char* name, PhaseTraceId id)
4309   : TraceTime(name, &Phase::timers[id], CITime, CITimeVerbose),
4310     _compile(Compile::current()),
4311     _log(nullptr),
4312     _dolog(CITimeVerbose)
4313 {
4314   assert(_compile != nullptr, "sanity check");
4315   if (_dolog) {
4316     _log = _compile->log();
4317   }
4318   if (_log != nullptr) {
4319     _log->begin_head("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes());
4320     _log->stamp();
4321     _log->end_head();
4322   }
4323 }
4324 
4325 Compile::TracePhase::TracePhase(PhaseTraceId id)
4326   : TracePhase(Phase::get_phase_trace_id_text(id), id) {}
4327 
4328 Compile::TracePhase::~TracePhase() {
4329   if (_compile->failing_internal()) {
4330     if (_log != nullptr) {
4331       _log->done("phase");
4332     }
4333     return; // timing code, not stressing bailouts.
4334   }
4335 #ifdef ASSERT
4336   if (PrintIdealNodeCount) {
4337     tty->print_cr("phase name='%s' nodes='%d' live='%d' live_graph_walk='%d'",
4338                   phase_name(), _compile->unique(), _compile->live_nodes(), _compile->count_live_nodes_by_graph_walk());
4339   }
4340 
4341   if (VerifyIdealNodeCount) {
4342     _compile->print_missing_nodes();
4343   }
4344 #endif
4345 
4346   if (_log != nullptr) {
4347     _log->done("phase name='%s' nodes='%d' live='%d'", phase_name(), _compile->unique(), _compile->live_nodes());
4348   }
4349 }
4350 
4351 //----------------------------static_subtype_check-----------------------------
4352 // Shortcut important common cases when superklass is exact:
4353 // (0) superklass is java.lang.Object (can occur in reflective code)
4354 // (1) subklass is already limited to a subtype of superklass => always ok
4355 // (2) subklass does not overlap with superklass => always fail
4356 // (3) superklass has NO subtypes and we can check with a simple compare.
4357 Compile::SubTypeCheckResult Compile::static_subtype_check(const TypeKlassPtr* superk, const TypeKlassPtr* subk, bool skip) {
4358   if (skip) {
4359     return SSC_full_test;       // Let caller generate the general case.
4360   }
4361 
4362   if (subk->is_java_subtype_of(superk)) {
4363     return SSC_always_true; // (0) and (1)  this test cannot fail
4364   }
4365 
4366   if (!subk->maybe_java_subtype_of(superk)) {
4367     return SSC_always_false; // (2) true path dead; no dynamic test needed
4368   }
4369 
4370   const Type* superelem = superk;
4371   if (superk->isa_aryklassptr()) {
4372     int ignored;
4373     superelem = superk->is_aryklassptr()->base_element_type(ignored);
4374   }
4375 
4376   if (superelem->isa_instklassptr()) {
4377     ciInstanceKlass* ik = superelem->is_instklassptr()->instance_klass();
4378     if (!ik->has_subklass()) {
4379       if (!ik->is_final()) {
4380         // Add a dependency if there is a chance of a later subclass.
4381         dependencies()->assert_leaf_type(ik);
4382       }
4383       if (!superk->maybe_java_subtype_of(subk)) {
4384         return SSC_always_false;
4385       }
4386       return SSC_easy_test;     // (3) caller can do a simple ptr comparison
4387     }
4388   } else {
4389     // A primitive array type has no subtypes.
4390     return SSC_easy_test;       // (3) caller can do a simple ptr comparison
4391   }
4392 
4393   return SSC_full_test;
4394 }
4395 
4396 Node* Compile::conv_I2X_index(PhaseGVN* phase, Node* idx, const TypeInt* sizetype, Node* ctrl) {
4397 #ifdef _LP64
4398   // The scaled index operand to AddP must be a clean 64-bit value.
4399   // Java allows a 32-bit int to be incremented to a negative
4400   // value, which appears in a 64-bit register as a large
4401   // positive number.  Using that large positive number as an
4402   // operand in pointer arithmetic has bad consequences.
4403   // On the other hand, 32-bit overflow is rare, and the possibility
4404   // can often be excluded, if we annotate the ConvI2L node with
4405   // a type assertion that its value is known to be a small positive
4406   // number.  (The prior range check has ensured this.)
4407   // This assertion is used by ConvI2LNode::Ideal.
4408   int index_max = max_jint - 1;  // array size is max_jint, index is one less
4409   if (sizetype != nullptr) index_max = sizetype->_hi - 1;
4410   const TypeInt* iidxtype = TypeInt::make(0, index_max, Type::WidenMax);
4411   idx = constrained_convI2L(phase, idx, iidxtype, ctrl);
4412 #endif
4413   return idx;
4414 }
4415 
4416 // Convert integer value to a narrowed long type dependent on ctrl (for example, a range check)
4417 Node* Compile::constrained_convI2L(PhaseGVN* phase, Node* value, const TypeInt* itype, Node* ctrl, bool carry_dependency) {
4418   if (ctrl != nullptr) {
4419     // Express control dependency by a CastII node with a narrow type.
4420     // Make the CastII node dependent on the control input to prevent the narrowed ConvI2L
4421     // node from floating above the range check during loop optimizations. Otherwise, the
4422     // ConvI2L node may be eliminated independently of the range check, causing the data path
4423     // to become TOP while the control path is still there (although it's unreachable).
4424     value = new CastIINode(ctrl, value, itype, carry_dependency ? ConstraintCastNode::StrongDependency : ConstraintCastNode::RegularDependency, true /* range check dependency */);
4425     value = phase->transform(value);
4426   }
4427   const TypeLong* ltype = TypeLong::make(itype->_lo, itype->_hi, itype->_widen);
4428   return phase->transform(new ConvI2LNode(value, ltype));
4429 }
4430 
4431 void Compile::dump_print_inlining() {
4432   inline_printer()->print_on(tty);
4433 }
4434 
4435 void Compile::log_late_inline(CallGenerator* cg) {
4436   if (log() != nullptr) {
4437     log()->head("late_inline method='%d'  inline_id='" JLONG_FORMAT "'", log()->identify(cg->method()),
4438                 cg->unique_id());
4439     JVMState* p = cg->call_node()->jvms();
4440     while (p != nullptr) {
4441       log()->elem("jvms bci='%d' method='%d'", p->bci(), log()->identify(p->method()));
4442       p = p->caller();
4443     }
4444     log()->tail("late_inline");
4445   }
4446 }
4447 
4448 void Compile::log_late_inline_failure(CallGenerator* cg, const char* msg) {
4449   log_late_inline(cg);
4450   if (log() != nullptr) {
4451     log()->inline_fail(msg);
4452   }
4453 }
4454 
4455 void Compile::log_inline_id(CallGenerator* cg) {
4456   if (log() != nullptr) {
4457     // The LogCompilation tool needs a unique way to identify late
4458     // inline call sites. This id must be unique for this call site in
4459     // this compilation. Try to have it unique across compilations as
4460     // well because it can be convenient when grepping through the log
4461     // file.
4462     // Distinguish OSR compilations from others in case CICountOSR is
4463     // on.
4464     jlong id = ((jlong)unique()) + (((jlong)compile_id()) << 33) + (CICountOSR && is_osr_compilation() ? ((jlong)1) << 32 : 0);
4465     cg->set_unique_id(id);
4466     log()->elem("inline_id id='" JLONG_FORMAT "'", id);
4467   }
4468 }
4469 
4470 void Compile::log_inline_failure(const char* msg) {
4471   if (C->log() != nullptr) {
4472     C->log()->inline_fail(msg);
4473   }
4474 }
4475 
4476 
4477 // Dump inlining replay data to the stream.
4478 // Don't change thread state and acquire any locks.
4479 void Compile::dump_inline_data(outputStream* out) {
4480   InlineTree* inl_tree = ilt();
4481   if (inl_tree != nullptr) {
4482     out->print(" inline %d", inl_tree->count());
4483     inl_tree->dump_replay_data(out);
4484   }
4485 }
4486 
4487 void Compile::dump_inline_data_reduced(outputStream* out) {
4488   assert(ReplayReduce, "");
4489 
4490   InlineTree* inl_tree = ilt();
4491   if (inl_tree == nullptr) {
4492     return;
4493   }
4494   // Enable iterative replay file reduction
4495   // Output "compile" lines for depth 1 subtrees,
4496   // simulating that those trees were compiled
4497   // instead of inlined.
4498   for (int i = 0; i < inl_tree->subtrees().length(); ++i) {
4499     InlineTree* sub = inl_tree->subtrees().at(i);
4500     if (sub->inline_level() != 1) {
4501       continue;
4502     }
4503 
4504     ciMethod* method = sub->method();
4505     int entry_bci = -1;
4506     int comp_level = env()->task()->comp_level();
4507     out->print("compile ");
4508     method->dump_name_as_ascii(out);
4509     out->print(" %d %d", entry_bci, comp_level);
4510     out->print(" inline %d", sub->count());
4511     sub->dump_replay_data(out, -1);
4512     out->cr();
4513   }
4514 }
4515 
4516 int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
4517   if (n1->Opcode() < n2->Opcode())      return -1;
4518   else if (n1->Opcode() > n2->Opcode()) return 1;
4519 
4520   assert(n1->req() == n2->req(), "can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req());
4521   for (uint i = 1; i < n1->req(); i++) {
4522     if (n1->in(i) < n2->in(i))      return -1;
4523     else if (n1->in(i) > n2->in(i)) return 1;
4524   }
4525 
4526   return 0;
4527 }
4528 
4529 int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
4530   Node* n1 = *n1p;
4531   Node* n2 = *n2p;
4532 
4533   return cmp_expensive_nodes(n1, n2);
4534 }
4535 
4536 void Compile::sort_expensive_nodes() {
4537   if (!expensive_nodes_sorted()) {
4538     _expensive_nodes.sort(cmp_expensive_nodes);
4539   }
4540 }
4541 
4542 bool Compile::expensive_nodes_sorted() const {
4543   for (int i = 1; i < _expensive_nodes.length(); i++) {
4544     if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i-1)) < 0) {
4545       return false;
4546     }
4547   }
4548   return true;
4549 }
4550 
4551 bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
4552   if (_expensive_nodes.length() == 0) {
4553     return false;
4554   }
4555 
4556   assert(OptimizeExpensiveOps, "optimization off?");
4557 
4558   // Take this opportunity to remove dead nodes from the list
4559   int j = 0;
4560   for (int i = 0; i < _expensive_nodes.length(); i++) {
4561     Node* n = _expensive_nodes.at(i);
4562     if (!n->is_unreachable(igvn)) {
4563       assert(n->is_expensive(), "should be expensive");
4564       _expensive_nodes.at_put(j, n);
4565       j++;
4566     }
4567   }
4568   _expensive_nodes.trunc_to(j);
4569 
4570   // Then sort the list so that similar nodes are next to each other
4571   // and check for at least two nodes of identical kind with same data
4572   // inputs.
4573   sort_expensive_nodes();
4574 
4575   for (int i = 0; i < _expensive_nodes.length()-1; i++) {
4576     if (cmp_expensive_nodes(_expensive_nodes.adr_at(i), _expensive_nodes.adr_at(i+1)) == 0) {
4577       return true;
4578     }
4579   }
4580 
4581   return false;
4582 }
4583 
4584 void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
4585   if (_expensive_nodes.length() == 0) {
4586     return;
4587   }
4588 
4589   assert(OptimizeExpensiveOps, "optimization off?");
4590 
4591   // Sort to bring similar nodes next to each other and clear the
4592   // control input of nodes for which there's only a single copy.
4593   sort_expensive_nodes();
4594 
4595   int j = 0;
4596   int identical = 0;
4597   int i = 0;
4598   bool modified = false;
4599   for (; i < _expensive_nodes.length()-1; i++) {
4600     assert(j <= i, "can't write beyond current index");
4601     if (_expensive_nodes.at(i)->Opcode() == _expensive_nodes.at(i+1)->Opcode()) {
4602       identical++;
4603       _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4604       continue;
4605     }
4606     if (identical > 0) {
4607       _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4608       identical = 0;
4609     } else {
4610       Node* n = _expensive_nodes.at(i);
4611       igvn.replace_input_of(n, 0, nullptr);
4612       igvn.hash_insert(n);
4613       modified = true;
4614     }
4615   }
4616   if (identical > 0) {
4617     _expensive_nodes.at_put(j++, _expensive_nodes.at(i));
4618   } else if (_expensive_nodes.length() >= 1) {
4619     Node* n = _expensive_nodes.at(i);
4620     igvn.replace_input_of(n, 0, nullptr);
4621     igvn.hash_insert(n);
4622     modified = true;
4623   }
4624   _expensive_nodes.trunc_to(j);
4625   if (modified) {
4626     igvn.optimize();
4627   }
4628 }
4629 
4630 void Compile::add_expensive_node(Node * n) {
4631   assert(!_expensive_nodes.contains(n), "duplicate entry in expensive list");
4632   assert(n->is_expensive(), "expensive nodes with non-null control here only");
4633   assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
4634   if (OptimizeExpensiveOps) {
4635     _expensive_nodes.append(n);
4636   } else {
4637     // Clear control input and let IGVN optimize expensive nodes if
4638     // OptimizeExpensiveOps is off.
4639     n->set_req(0, nullptr);
4640   }
4641 }
4642 
4643 /**
4644  * Track coarsened Lock and Unlock nodes.
4645  */
4646 
4647 class Lock_List : public Node_List {
4648   uint _origin_cnt;
4649 public:
4650   Lock_List(Arena *a, uint cnt) : Node_List(a), _origin_cnt(cnt) {}
4651   uint origin_cnt() const { return _origin_cnt; }
4652 };
4653 
4654 void Compile::add_coarsened_locks(GrowableArray<AbstractLockNode*>& locks) {
4655   int length = locks.length();
4656   if (length > 0) {
4657     // Have to keep this list until locks elimination during Macro nodes elimination.
4658     Lock_List* locks_list = new (comp_arena()) Lock_List(comp_arena(), length);
4659     AbstractLockNode* alock = locks.at(0);
4660     BoxLockNode* box = alock->box_node()->as_BoxLock();
4661     for (int i = 0; i < length; i++) {
4662       AbstractLockNode* lock = locks.at(i);
4663       assert(lock->is_coarsened(), "expecting only coarsened AbstractLock nodes, but got '%s'[%d] node", lock->Name(), lock->_idx);
4664       locks_list->push(lock);
4665       BoxLockNode* this_box = lock->box_node()->as_BoxLock();
4666       if (this_box != box) {
4667         // Locking regions (BoxLock) could be Unbalanced here:
4668         //  - its coarsened locks were eliminated in earlier
4669         //    macro nodes elimination followed by loop unroll
4670         //  - it is OSR locking region (no Lock node)
4671         // Preserve Unbalanced status in such cases.
4672         if (!this_box->is_unbalanced()) {
4673           this_box->set_coarsened();
4674         }
4675         if (!box->is_unbalanced()) {
4676           box->set_coarsened();
4677         }
4678       }
4679     }
4680     _coarsened_locks.append(locks_list);
4681   }
4682 }
4683 
4684 void Compile::remove_useless_coarsened_locks(Unique_Node_List& useful) {
4685   int count = coarsened_count();
4686   for (int i = 0; i < count; i++) {
4687     Node_List* locks_list = _coarsened_locks.at(i);
4688     for (uint j = 0; j < locks_list->size(); j++) {
4689       Node* lock = locks_list->at(j);
4690       assert(lock->is_AbstractLock(), "sanity");
4691       if (!useful.member(lock)) {
4692         locks_list->yank(lock);
4693       }
4694     }
4695   }
4696 }
4697 
4698 void Compile::remove_coarsened_lock(Node* n) {
4699   if (n->is_AbstractLock()) {
4700     int count = coarsened_count();
4701     for (int i = 0; i < count; i++) {
4702       Node_List* locks_list = _coarsened_locks.at(i);
4703       locks_list->yank(n);
4704     }
4705   }
4706 }
4707 
4708 bool Compile::coarsened_locks_consistent() {
4709   int count = coarsened_count();
4710   for (int i = 0; i < count; i++) {
4711     bool unbalanced = false;
4712     bool modified = false; // track locks kind modifications
4713     Lock_List* locks_list = (Lock_List*)_coarsened_locks.at(i);
4714     uint size = locks_list->size();
4715     if (size == 0) {
4716       unbalanced = false; // All locks were eliminated - good
4717     } else if (size != locks_list->origin_cnt()) {
4718       unbalanced = true; // Some locks were removed from list
4719     } else {
4720       for (uint j = 0; j < size; j++) {
4721         Node* lock = locks_list->at(j);
4722         // All nodes in group should have the same state (modified or not)
4723         if (!lock->as_AbstractLock()->is_coarsened()) {
4724           if (j == 0) {
4725             // first on list was modified, the rest should be too for consistency
4726             modified = true;
4727           } else if (!modified) {
4728             // this lock was modified but previous locks on the list were not
4729             unbalanced = true;
4730             break;
4731           }
4732         } else if (modified) {
4733           // previous locks on list were modified but not this lock
4734           unbalanced = true;
4735           break;
4736         }
4737       }
4738     }
4739     if (unbalanced) {
4740       // unbalanced monitor enter/exit - only some [un]lock nodes were removed or modified
4741 #ifdef ASSERT
4742       if (PrintEliminateLocks) {
4743         tty->print_cr("=== unbalanced coarsened locks ===");
4744         for (uint l = 0; l < size; l++) {
4745           locks_list->at(l)->dump();
4746         }
4747       }
4748 #endif
4749       record_failure(C2Compiler::retry_no_locks_coarsening());
4750       return false;
4751     }
4752   }
4753   return true;
4754 }
4755 
4756 // Mark locking regions (identified by BoxLockNode) as unbalanced if
4757 // locks coarsening optimization removed Lock/Unlock nodes from them.
4758 // Such regions become unbalanced because coarsening only removes part
4759 // of Lock/Unlock nodes in region. As result we can't execute other
4760 // locks elimination optimizations which assume all code paths have
4761 // corresponding pair of Lock/Unlock nodes - they are balanced.
4762 void Compile::mark_unbalanced_boxes() const {
4763   int count = coarsened_count();
4764   for (int i = 0; i < count; i++) {
4765     Node_List* locks_list = _coarsened_locks.at(i);
4766     uint size = locks_list->size();
4767     if (size > 0) {
4768       AbstractLockNode* alock = locks_list->at(0)->as_AbstractLock();
4769       BoxLockNode* box = alock->box_node()->as_BoxLock();
4770       if (alock->is_coarsened()) {
4771         // coarsened_locks_consistent(), which is called before this method, verifies
4772         // that the rest of Lock/Unlock nodes on locks_list are also coarsened.
4773         assert(!box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated");
4774         for (uint j = 1; j < size; j++) {
4775           assert(locks_list->at(j)->as_AbstractLock()->is_coarsened(), "only coarsened locks are expected here");
4776           BoxLockNode* this_box = locks_list->at(j)->as_AbstractLock()->box_node()->as_BoxLock();
4777           if (box != this_box) {
4778             assert(!this_box->is_eliminated(), "regions with coarsened locks should not be marked as eliminated");
4779             box->set_unbalanced();
4780             this_box->set_unbalanced();
4781           }
4782         }
4783       }
4784     }
4785   }
4786 }
4787 
4788 /**
4789  * Remove the speculative part of types and clean up the graph
4790  */
4791 void Compile::remove_speculative_types(PhaseIterGVN &igvn) {
4792   if (UseTypeSpeculation) {
4793     Unique_Node_List worklist;
4794     worklist.push(root());
4795     int modified = 0;
4796     // Go over all type nodes that carry a speculative type, drop the
4797     // speculative part of the type and enqueue the node for an igvn
4798     // which may optimize it out.
4799     for (uint next = 0; next < worklist.size(); ++next) {
4800       Node *n  = worklist.at(next);
4801       if (n->is_Type()) {
4802         TypeNode* tn = n->as_Type();
4803         const Type* t = tn->type();
4804         const Type* t_no_spec = t->remove_speculative();
4805         if (t_no_spec != t) {
4806           bool in_hash = igvn.hash_delete(n);
4807           assert(in_hash || n->hash() == Node::NO_HASH, "node should be in igvn hash table");
4808           tn->set_type(t_no_spec);
4809           igvn.hash_insert(n);
4810           igvn._worklist.push(n); // give it a chance to go away
4811           modified++;
4812         }
4813       }
4814       // Iterate over outs - endless loops is unreachable from below
4815       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4816         Node *m = n->fast_out(i);
4817         if (not_a_node(m)) {
4818           continue;
4819         }
4820         worklist.push(m);
4821       }
4822     }
4823     // Drop the speculative part of all types in the igvn's type table
4824     igvn.remove_speculative_types();
4825     if (modified > 0) {
4826       igvn.optimize();
4827       if (failing())  return;
4828     }
4829 #ifdef ASSERT
4830     // Verify that after the IGVN is over no speculative type has resurfaced
4831     worklist.clear();
4832     worklist.push(root());
4833     for (uint next = 0; next < worklist.size(); ++next) {
4834       Node *n  = worklist.at(next);
4835       const Type* t = igvn.type_or_null(n);
4836       assert((t == nullptr) || (t == t->remove_speculative()), "no more speculative types");
4837       if (n->is_Type()) {
4838         t = n->as_Type()->type();
4839         assert(t == t->remove_speculative(), "no more speculative types");
4840       }
4841       // Iterate over outs - endless loops is unreachable from below
4842       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4843         Node *m = n->fast_out(i);
4844         if (not_a_node(m)) {
4845           continue;
4846         }
4847         worklist.push(m);
4848       }
4849     }
4850     igvn.check_no_speculative_types();
4851 #endif
4852   }
4853 }
4854 
4855 // Auxiliary methods to support randomized stressing/fuzzing.
4856 
4857 void Compile::initialize_stress_seed(const DirectiveSet* directive) {
4858   if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && directive->RepeatCompilationOption)) {
4859     _stress_seed = static_cast<uint>(Ticks::now().nanoseconds());
4860     FLAG_SET_ERGO(StressSeed, _stress_seed);
4861   } else {
4862     _stress_seed = StressSeed;
4863   }
4864   if (_log != nullptr) {
4865     _log->elem("stress_test seed='%u'", _stress_seed);
4866   }
4867 }
4868 
4869 int Compile::random() {
4870   _stress_seed = os::next_random(_stress_seed);
4871   return static_cast<int>(_stress_seed);
4872 }
4873 
4874 // This method can be called the arbitrary number of times, with current count
4875 // as the argument. The logic allows selecting a single candidate from the
4876 // running list of candidates as follows:
4877 //    int count = 0;
4878 //    Cand* selected = null;
4879 //    while(cand = cand->next()) {
4880 //      if (randomized_select(++count)) {
4881 //        selected = cand;
4882 //      }
4883 //    }
4884 //
4885 // Including count equalizes the chances any candidate is "selected".
4886 // This is useful when we don't have the complete list of candidates to choose
4887 // from uniformly. In this case, we need to adjust the randomicity of the
4888 // selection, or else we will end up biasing the selection towards the latter
4889 // candidates.
4890 //
4891 // Quick back-envelope calculation shows that for the list of n candidates
4892 // the equal probability for the candidate to persist as "best" can be
4893 // achieved by replacing it with "next" k-th candidate with the probability
4894 // of 1/k. It can be easily shown that by the end of the run, the
4895 // probability for any candidate is converged to 1/n, thus giving the
4896 // uniform distribution among all the candidates.
4897 //
4898 // We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
4899 #define RANDOMIZED_DOMAIN_POW 29
4900 #define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
4901 #define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
4902 bool Compile::randomized_select(int count) {
4903   assert(count > 0, "only positive");
4904   return (random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
4905 }
4906 
4907 #ifdef ASSERT
4908 // Failures are geometrically distributed with probability 1/StressBailoutMean.
4909 bool Compile::fail_randomly() {
4910   if ((random() % StressBailoutMean) != 0) {
4911     return false;
4912   }
4913   record_failure("StressBailout");
4914   return true;
4915 }
4916 
4917 bool Compile::failure_is_artificial() {
4918   return C->failure_reason_is("StressBailout");
4919 }
4920 #endif
4921 
4922 CloneMap&     Compile::clone_map()                 { return _clone_map; }
4923 void          Compile::set_clone_map(Dict* d)      { _clone_map._dict = d; }
4924 
4925 void NodeCloneInfo::dump_on(outputStream* st) const {
4926   st->print(" {%d:%d} ", idx(), gen());
4927 }
4928 
4929 void CloneMap::clone(Node* old, Node* nnn, int gen) {
4930   uint64_t val = value(old->_idx);
4931   NodeCloneInfo cio(val);
4932   assert(val != 0, "old node should be in the map");
4933   NodeCloneInfo cin(cio.idx(), gen + cio.gen());
4934   insert(nnn->_idx, cin.get());
4935 #ifndef PRODUCT
4936   if (is_debug()) {
4937     tty->print_cr("CloneMap::clone inserted node %d info {%d:%d} into CloneMap", nnn->_idx, cin.idx(), cin.gen());
4938   }
4939 #endif
4940 }
4941 
4942 void CloneMap::verify_insert_and_clone(Node* old, Node* nnn, int gen) {
4943   NodeCloneInfo cio(value(old->_idx));
4944   if (cio.get() == 0) {
4945     cio.set(old->_idx, 0);
4946     insert(old->_idx, cio.get());
4947 #ifndef PRODUCT
4948     if (is_debug()) {
4949       tty->print_cr("CloneMap::verify_insert_and_clone inserted node %d info {%d:%d} into CloneMap", old->_idx, cio.idx(), cio.gen());
4950     }
4951 #endif
4952   }
4953   clone(old, nnn, gen);
4954 }
4955 
4956 int CloneMap::max_gen() const {
4957   int g = 0;
4958   DictI di(_dict);
4959   for(; di.test(); ++di) {
4960     int t = gen(di._key);
4961     if (g < t) {
4962       g = t;
4963 #ifndef PRODUCT
4964       if (is_debug()) {
4965         tty->print_cr("CloneMap::max_gen() update max=%d from %d", g, _2_node_idx_t(di._key));
4966       }
4967 #endif
4968     }
4969   }
4970   return g;
4971 }
4972 
4973 void CloneMap::dump(node_idx_t key, outputStream* st) const {
4974   uint64_t val = value(key);
4975   if (val != 0) {
4976     NodeCloneInfo ni(val);
4977     ni.dump_on(st);
4978   }
4979 }
4980 
4981 void Compile::shuffle_macro_nodes() {
4982   if (_macro_nodes.length() < 2) {
4983     return;
4984   }
4985   for (uint i = _macro_nodes.length() - 1; i >= 1; i--) {
4986     uint j = C->random() % (i + 1);
4987     swap(_macro_nodes.at(i), _macro_nodes.at(j));
4988   }
4989 }
4990 
4991 // Move Allocate nodes to the start of the list
4992 void Compile::sort_macro_nodes() {
4993   int count = macro_count();
4994   int allocates = 0;
4995   for (int i = 0; i < count; i++) {
4996     Node* n = macro_node(i);
4997     if (n->is_Allocate()) {
4998       if (i != allocates) {
4999         Node* tmp = macro_node(allocates);
5000         _macro_nodes.at_put(allocates, n);
5001         _macro_nodes.at_put(i, tmp);
5002       }
5003       allocates++;
5004     }
5005   }
5006 }
5007 
5008 void Compile::print_method(CompilerPhaseType cpt, int level, Node* n) {
5009   if (failing_internal()) { return; } // failing_internal to not stress bailouts from printing code.
5010   EventCompilerPhase event(UNTIMED);
5011   if (event.should_commit()) {
5012     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, cpt, C->_compile_id, level);
5013   }
5014 #ifndef PRODUCT
5015   ResourceMark rm;
5016   stringStream ss;
5017   ss.print_raw(CompilerPhaseTypeHelper::to_description(cpt));
5018   int iter = ++_igv_phase_iter[cpt];
5019   if (iter > 1) {
5020     ss.print(" %d", iter);
5021   }
5022   if (n != nullptr) {
5023     ss.print(": %d %s", n->_idx, NodeClassNames[n->Opcode()]);
5024     if (n->is_Call()) {
5025       CallNode* call = n->as_Call();
5026       if (call->_name != nullptr) {
5027         // E.g. uncommon traps etc.
5028         ss.print(" - %s", call->_name);
5029       } else if (call->is_CallJava()) {
5030         CallJavaNode* call_java = call->as_CallJava();
5031         if (call_java->method() != nullptr) {
5032           ss.print(" -");
5033           call_java->method()->print_short_name(&ss);
5034         }
5035       }
5036     }
5037   }
5038 
5039   const char* name = ss.as_string();
5040   if (should_print_igv(level)) {
5041     _igv_printer->print_graph(name);
5042   }
5043   if (should_print_phase(cpt)) {
5044     print_ideal_ir(CompilerPhaseTypeHelper::to_name(cpt));
5045   }
5046 #endif
5047   C->_latest_stage_start_counter.stamp();
5048 }
5049 
5050 // Only used from CompileWrapper
5051 void Compile::begin_method() {
5052 #ifndef PRODUCT
5053   if (_method != nullptr && should_print_igv(1)) {
5054     _igv_printer->begin_method();
5055   }
5056 #endif
5057   C->_latest_stage_start_counter.stamp();
5058 }
5059 
5060 // Only used from CompileWrapper
5061 void Compile::end_method() {
5062   EventCompilerPhase event(UNTIMED);
5063   if (event.should_commit()) {
5064     CompilerEvent::PhaseEvent::post(event, C->_latest_stage_start_counter, PHASE_END, C->_compile_id, 1);
5065   }
5066 
5067 #ifndef PRODUCT
5068   if (_method != nullptr && should_print_igv(1)) {
5069     _igv_printer->end_method();
5070   }
5071 #endif
5072 }
5073 
5074 bool Compile::should_print_phase(CompilerPhaseType cpt) {
5075 #ifndef PRODUCT
5076   if (_directive->should_print_phase(cpt)) {
5077     return true;
5078   }
5079 #endif
5080   return false;
5081 }
5082 
5083 #ifndef PRODUCT
5084 void Compile::init_igv() {
5085   if (_igv_printer == nullptr) {
5086     _igv_printer = IdealGraphPrinter::printer();
5087     _igv_printer->set_compile(this);
5088   }
5089 }
5090 #endif
5091 
5092 bool Compile::should_print_igv(const int level) {
5093 #ifndef PRODUCT
5094   if (PrintIdealGraphLevel < 0) { // disabled by the user
5095     return false;
5096   }
5097 
5098   bool need = directive()->IGVPrintLevelOption >= level;
5099   if (need) {
5100     Compile::init_igv();
5101   }
5102   return need;
5103 #else
5104   return false;
5105 #endif
5106 }
5107 
5108 #ifndef PRODUCT
5109 IdealGraphPrinter* Compile::_debug_file_printer = nullptr;
5110 IdealGraphPrinter* Compile::_debug_network_printer = nullptr;
5111 
5112 // Called from debugger. Prints method to the default file with the default phase name.
5113 // This works regardless of any Ideal Graph Visualizer flags set or not.
5114 void igv_print() {
5115   Compile::current()->igv_print_method_to_file();
5116 }
5117 
5118 // Same as igv_print() above but with a specified phase name.
5119 void igv_print(const char* phase_name) {
5120   Compile::current()->igv_print_method_to_file(phase_name);
5121 }
5122 
5123 // Called from debugger. Prints method with the default phase name to the default network or the one specified with
5124 // the network flags for the Ideal Graph Visualizer, or to the default file depending on the 'network' argument.
5125 // This works regardless of any Ideal Graph Visualizer flags set or not.
5126 void igv_print(bool network) {
5127   if (network) {
5128     Compile::current()->igv_print_method_to_network();
5129   } else {
5130     Compile::current()->igv_print_method_to_file();
5131   }
5132 }
5133 
5134 // Same as igv_print(bool network) above but with a specified phase name.
5135 void igv_print(bool network, const char* phase_name) {
5136   if (network) {
5137     Compile::current()->igv_print_method_to_network(phase_name);
5138   } else {
5139     Compile::current()->igv_print_method_to_file(phase_name);
5140   }
5141 }
5142 
5143 // Called from debugger. Normal write to the default _printer. Only works if Ideal Graph Visualizer printing flags are set.
5144 void igv_print_default() {
5145   Compile::current()->print_method(PHASE_DEBUG, 0);
5146 }
5147 
5148 // Called from debugger, especially when replaying a trace in which the program state cannot be altered like with rr replay.
5149 // A method is appended to an existing default file with the default phase name. This means that igv_append() must follow
5150 // an earlier igv_print(*) call which sets up the file. This works regardless of any Ideal Graph Visualizer flags set or not.
5151 void igv_append() {
5152   Compile::current()->igv_print_method_to_file("Debug", true);
5153 }
5154 
5155 // Same as igv_append() above but with a specified phase name.
5156 void igv_append(const char* phase_name) {
5157   Compile::current()->igv_print_method_to_file(phase_name, true);
5158 }
5159 
5160 void Compile::igv_print_method_to_file(const char* phase_name, bool append) {
5161   const char* file_name = "custom_debug.xml";
5162   if (_debug_file_printer == nullptr) {
5163     _debug_file_printer = new IdealGraphPrinter(C, file_name, append);
5164   } else {
5165     _debug_file_printer->update_compiled_method(C->method());
5166   }
5167   tty->print_cr("Method %s to %s", append ? "appended" : "printed", file_name);
5168   _debug_file_printer->print_graph(phase_name);
5169 }
5170 
5171 void Compile::igv_print_method_to_network(const char* phase_name) {
5172   ResourceMark rm;
5173   GrowableArray<const Node*> empty_list;
5174   igv_print_graph_to_network(phase_name, (Node*) C->root(), empty_list);
5175 }
5176 
5177 void Compile::igv_print_graph_to_network(const char* name, Node* node, GrowableArray<const Node*>& visible_nodes) {
5178   if (_debug_network_printer == nullptr) {
5179     _debug_network_printer = new IdealGraphPrinter(C);
5180   } else {
5181     _debug_network_printer->update_compiled_method(C->method());
5182   }
5183   tty->print_cr("Method printed over network stream to IGV");
5184   _debug_network_printer->print(name, C->root(), visible_nodes);
5185 }
5186 #endif
5187 
5188 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
5189   if (type != nullptr && phase->type(value)->higher_equal(type)) {
5190     return value;
5191   }
5192   Node* result = nullptr;
5193   if (bt == T_BYTE) {
5194     result = phase->transform(new LShiftINode(value, phase->intcon(24)));
5195     result = new RShiftINode(result, phase->intcon(24));
5196   } else if (bt == T_BOOLEAN) {
5197     result = new AndINode(value, phase->intcon(0xFF));
5198   } else if (bt == T_CHAR) {
5199     result = new AndINode(value,phase->intcon(0xFFFF));
5200   } else {
5201     assert(bt == T_SHORT, "unexpected narrow type");
5202     result = phase->transform(new LShiftINode(value, phase->intcon(16)));
5203     result = new RShiftINode(result, phase->intcon(16));
5204   }
5205   if (transform_res) {
5206     result = phase->transform(result);
5207   }
5208   return result;
5209 }
5210 
5211 void Compile::record_method_not_compilable_oom() {
5212   record_method_not_compilable(CompilationMemoryStatistic::failure_reason_memlimit());
5213 }