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