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