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