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