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