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