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