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