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