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