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