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