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