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