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