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