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