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