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