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