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