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