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