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