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