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 
  25 #include "precompiled.hpp"
  26 #include "jvm_io.h"
  27 #include "asm/macroAssembler.hpp"
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "ci/ciReplay.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "code/exceptionHandlerTable.hpp"
  32 #include "code/nmethod.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/compileLog.hpp"
  35 #include "compiler/disassembler.hpp"
  36 #include "compiler/oopMap.hpp"
  37 #include "gc/shared/barrierSet.hpp"
  38 #include "gc/shared/c2/barrierSetC2.hpp"
  39 #include "jfr/jfrEvents.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "opto/addnode.hpp"
  42 #include "opto/block.hpp"
  43 #include "opto/c2compiler.hpp"
  44 #include "opto/callGenerator.hpp"
  45 #include "opto/callnode.hpp"
  46 #include "opto/castnode.hpp"
  47 #include "opto/cfgnode.hpp"
  48 #include "opto/chaitin.hpp"
  49 #include "opto/compile.hpp"
  50 #include "opto/connode.hpp"
  51 #include "opto/convertnode.hpp"
  52 #include "opto/divnode.hpp"
  53 #include "opto/escape.hpp"
  54 #include "opto/idealGraphPrinter.hpp"
  55 #include "opto/loopnode.hpp"
  56 #include "opto/machnode.hpp"
  57 #include "opto/macro.hpp"
  58 #include "opto/matcher.hpp"
  59 #include "opto/mathexactnode.hpp"
  60 #include "opto/memnode.hpp"
  61 #include "opto/mulnode.hpp"
  62 #include "opto/narrowptrnode.hpp"
  63 #include "opto/node.hpp"
  64 #include "opto/opcodes.hpp"
  65 #include "opto/output.hpp"
  66 #include "opto/parse.hpp"
  67 #include "opto/phaseX.hpp"
  68 #include "opto/rootnode.hpp"
  69 #include "opto/runtime.hpp"
  70 #include "opto/stringopts.hpp"
  71 #include "opto/type.hpp"
  72 #include "opto/vector.hpp"
  73 #include "opto/vectornode.hpp"
  74 #include "runtime/globals_extension.hpp"
  75 #include "runtime/sharedRuntime.hpp"
  76 #include "runtime/signature.hpp"
  77 #include "runtime/stubRoutines.hpp"
  78 #include "runtime/timer.hpp"
  79 #include "utilities/align.hpp"
  80 #include "utilities/copy.hpp"
  81 #include "utilities/macros.hpp"
  82 #include "utilities/resourceHash.hpp"
  83 
  84 
  85 // -------------------- Compile::mach_constant_base_node -----------------------
  86 // Constant table base node singleton.
  87 MachConstantBaseNode* Compile::mach_constant_base_node() {
  88   if (_mach_constant_base_node == NULL) {
  89     _mach_constant_base_node = new MachConstantBaseNode();
  90     _mach_constant_base_node->add_req(C->root());
  91   }
  92   return _mach_constant_base_node;
  93 }
  94 
  95 
  96 /// Support for intrinsics.
  97 
  98 // Return the index at which m must be inserted (or already exists).
  99 // The sort order is by the address of the ciMethod, with is_virtual as minor key.
 100 class IntrinsicDescPair {
 101  private:
 102   ciMethod* _m;
 103   bool _is_virtual;
 104  public:
 105   IntrinsicDescPair(ciMethod* m, bool is_virtual) : _m(m), _is_virtual(is_virtual) {}
 106   static int compare(IntrinsicDescPair* const& key, CallGenerator* const& elt) {
 107     ciMethod* m= elt->method();
 108     ciMethod* key_m = key->_m;
 109     if (key_m < m)      return -1;
 110     else if (key_m > m) return 1;
 111     else {
 112       bool is_virtual = elt->is_virtual();
 113       bool key_virtual = key->_is_virtual;
 114       if (key_virtual < is_virtual)      return -1;
 115       else if (key_virtual > is_virtual) return 1;
 116       else                               return 0;
 117     }
 118   }
 119 };
 120 int Compile::intrinsic_insertion_index(ciMethod* m, bool is_virtual, bool& found) {
 121 #ifdef ASSERT
 122   for (int i = 1; i < _intrinsics.length(); i++) {
 123     CallGenerator* cg1 = _intrinsics.at(i-1);
 124     CallGenerator* cg2 = _intrinsics.at(i);
 125     assert(cg1->method() != cg2->method()
 126            ? cg1->method()     < cg2->method()
 127            : cg1->is_virtual() < cg2->is_virtual(),
 128            "compiler intrinsics list must stay sorted");
 129   }
 130 #endif
 131   IntrinsicDescPair pair(m, is_virtual);
 132   return _intrinsics.find_sorted<IntrinsicDescPair*, IntrinsicDescPair::compare>(&pair, found);
 133 }
 134 
 135 void Compile::register_intrinsic(CallGenerator* cg) {
 136   bool found = false;
 137   int index = intrinsic_insertion_index(cg->method(), cg->is_virtual(), found);
 138   assert(!found, "registering twice");
 139   _intrinsics.insert_before(index, cg);
 140   assert(find_intrinsic(cg->method(), cg->is_virtual()) == cg, "registration worked");
 141 }
 142 
 143 CallGenerator* Compile::find_intrinsic(ciMethod* m, bool is_virtual) {
 144   assert(m->is_loaded(), "don't try this on unloaded methods");
 145   if (_intrinsics.length() > 0) {
 146     bool found = false;
 147     int index = intrinsic_insertion_index(m, is_virtual, found);
 148      if (found) {
 149       return _intrinsics.at(index);
 150     }
 151   }
 152   // Lazily create intrinsics for intrinsic IDs well-known in the runtime.
 153   if (m->intrinsic_id() != vmIntrinsics::_none &&
 154       m->intrinsic_id() <= vmIntrinsics::LAST_COMPILER_INLINE) {
 155     CallGenerator* cg = make_vm_intrinsic(m, is_virtual);
 156     if (cg != NULL) {
 157       // Save it for next time:
 158       register_intrinsic(cg);
 159       return cg;
 160     } else {
 161       gather_intrinsic_statistics(m->intrinsic_id(), is_virtual, _intrinsic_disabled);
 162     }
 163   }
 164   return NULL;
 165 }
 166 
 167 // Compile::make_vm_intrinsic is defined in library_call.cpp.
 168 
 169 #ifndef PRODUCT
 170 // statistics gathering...
 171 
 172 juint  Compile::_intrinsic_hist_count[vmIntrinsics::number_of_intrinsics()] = {0};
 173 jubyte Compile::_intrinsic_hist_flags[vmIntrinsics::number_of_intrinsics()] = {0};
 174 
 175 inline int as_int(vmIntrinsics::ID id) {
 176   return vmIntrinsics::as_int(id);
 177 }
 178 
 179 bool Compile::gather_intrinsic_statistics(vmIntrinsics::ID id, bool is_virtual, int flags) {
 180   assert(id > vmIntrinsics::_none && id < vmIntrinsics::ID_LIMIT, "oob");
 181   int oflags = _intrinsic_hist_flags[as_int(id)];
 182   assert(flags != 0, "what happened?");
 183   if (is_virtual) {
 184     flags |= _intrinsic_virtual;
 185   }
 186   bool changed = (flags != oflags);
 187   if ((flags & _intrinsic_worked) != 0) {
 188     juint count = (_intrinsic_hist_count[as_int(id)] += 1);
 189     if (count == 1) {
 190       changed = true;           // first time
 191     }
 192     // increment the overall count also:
 193     _intrinsic_hist_count[as_int(vmIntrinsics::_none)] += 1;
 194   }
 195   if (changed) {
 196     if (((oflags ^ flags) & _intrinsic_virtual) != 0) {
 197       // Something changed about the intrinsic's virtuality.
 198       if ((flags & _intrinsic_virtual) != 0) {
 199         // This is the first use of this intrinsic as a virtual call.
 200         if (oflags != 0) {
 201           // We already saw it as a non-virtual, so note both cases.
 202           flags |= _intrinsic_both;
 203         }
 204       } else if ((oflags & _intrinsic_both) == 0) {
 205         // This is the first use of this intrinsic as a non-virtual
 206         flags |= _intrinsic_both;
 207       }
 208     }
 209     _intrinsic_hist_flags[as_int(id)] = (jubyte) (oflags | flags);
 210   }
 211   // update the overall flags also:
 212   _intrinsic_hist_flags[as_int(vmIntrinsics::_none)] |= (jubyte) flags;
 213   return changed;
 214 }
 215 
 216 static char* format_flags(int flags, char* buf) {
 217   buf[0] = 0;
 218   if ((flags & Compile::_intrinsic_worked) != 0)    strcat(buf, ",worked");
 219   if ((flags & Compile::_intrinsic_failed) != 0)    strcat(buf, ",failed");
 220   if ((flags & Compile::_intrinsic_disabled) != 0)  strcat(buf, ",disabled");
 221   if ((flags & Compile::_intrinsic_virtual) != 0)   strcat(buf, ",virtual");
 222   if ((flags & Compile::_intrinsic_both) != 0)      strcat(buf, ",nonvirtual");
 223   if (buf[0] == 0)  strcat(buf, ",");
 224   assert(buf[0] == ',', "must be");
 225   return &buf[1];
 226 }
 227 
 228 void Compile::print_intrinsic_statistics() {
 229   char flagsbuf[100];
 230   ttyLocker ttyl;
 231   if (xtty != NULL)  xtty->head("statistics type='intrinsic'");
 232   tty->print_cr("Compiler intrinsic usage:");
 233   juint total = _intrinsic_hist_count[as_int(vmIntrinsics::_none)];
 234   if (total == 0)  total = 1;  // avoid div0 in case of no successes
 235   #define PRINT_STAT_LINE(name, c, f) \
 236     tty->print_cr("  %4d (%4.1f%%) %s (%s)", (int)(c), ((c) * 100.0) / total, name, f);
 237   for (auto id : EnumRange<vmIntrinsicID>{}) {
 238     int   flags = _intrinsic_hist_flags[as_int(id)];
 239     juint count = _intrinsic_hist_count[as_int(id)];
 240     if ((flags | count) != 0) {
 241       PRINT_STAT_LINE(vmIntrinsics::name_at(id), count, format_flags(flags, flagsbuf));
 242     }
 243   }
 244   PRINT_STAT_LINE("total", total, format_flags(_intrinsic_hist_flags[as_int(vmIntrinsics::_none)], flagsbuf));
 245   if (xtty != NULL)  xtty->tail("statistics");
 246 }
 247 
 248 void Compile::print_statistics() {
 249   { ttyLocker ttyl;
 250     if (xtty != NULL)  xtty->head("statistics type='opto'");
 251     Parse::print_statistics();
 252     PhaseCCP::print_statistics();
 253     PhaseRegAlloc::print_statistics();
 254     PhaseOutput::print_statistics();
 255     PhasePeephole::print_statistics();
 256     PhaseIdealLoop::print_statistics();
 257     if (xtty != NULL)  xtty->tail("statistics");
 258   }
 259   if (_intrinsic_hist_flags[as_int(vmIntrinsics::_none)] != 0) {
 260     // put this under its own <statistics> element.
 261     print_intrinsic_statistics();
 262   }
 263 }
 264 #endif //PRODUCT
 265 
 266 void Compile::gvn_replace_by(Node* n, Node* nn) {
 267   for (DUIterator_Last imin, i = n->last_outs(imin); i >= imin; ) {
 268     Node* use = n->last_out(i);
 269     bool is_in_table = initial_gvn()->hash_delete(use);
 270     uint uses_found = 0;
 271     for (uint j = 0; j < use->len(); j++) {
 272       if (use->in(j) == n) {
 273         if (j < use->req())
 274           use->set_req(j, nn);
 275         else
 276           use->set_prec(j, nn);
 277         uses_found++;
 278       }
 279     }
 280     if (is_in_table) {
 281       // reinsert into table
 282       initial_gvn()->hash_find_insert(use);
 283     }
 284     record_for_igvn(use);
 285     i -= uses_found;    // we deleted 1 or more copies of this edge
 286   }
 287 }
 288 
 289 
 290 // Identify all nodes that are reachable from below, useful.
 291 // Use breadth-first pass that records state in a Unique_Node_List,
 292 // recursive traversal is slower.
 293 void Compile::identify_useful_nodes(Unique_Node_List &useful) {
 294   int estimated_worklist_size = live_nodes();
 295   useful.map( estimated_worklist_size, NULL );  // preallocate space
 296 
 297   // Initialize worklist
 298   if (root() != NULL)     { useful.push(root()); }
 299   // If 'top' is cached, declare it useful to preserve cached node
 300   if( cached_top_node() ) { useful.push(cached_top_node()); }
 301 
 302   // Push all useful nodes onto the list, breadthfirst
 303   for( uint next = 0; next < useful.size(); ++next ) {
 304     assert( next < unique(), "Unique useful nodes < total nodes");
 305     Node *n  = useful.at(next);
 306     uint max = n->len();
 307     for( uint i = 0; i < max; ++i ) {
 308       Node *m = n->in(i);
 309       if (not_a_node(m))  continue;
 310       useful.push(m);
 311     }
 312   }
 313 }
 314 
 315 // Update dead_node_list with any missing dead nodes using useful
 316 // list. Consider all non-useful nodes to be useless i.e., dead nodes.
 317 void Compile::update_dead_node_list(Unique_Node_List &useful) {
 318   uint max_idx = unique();
 319   VectorSet& useful_node_set = useful.member_set();
 320 
 321   for (uint node_idx = 0; node_idx < max_idx; node_idx++) {
 322     // If node with index node_idx is not in useful set,
 323     // mark it as dead in dead node list.
 324     if (!useful_node_set.test(node_idx)) {
 325       record_dead_node(node_idx);
 326     }
 327   }
 328 }
 329 
 330 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Unique_Node_List &useful) {
 331   int shift = 0;
 332   for (int i = 0; i < inlines->length(); i++) {
 333     CallGenerator* cg = inlines->at(i);
 334     if (useful.member(cg->call_node())) {
 335       if (shift > 0) {
 336         inlines->at_put(i - shift, cg);
 337       }
 338     } else {
 339       shift++; // skip over the dead element
 340     }
 341   }
 342   if (shift > 0) {
 343     inlines->trunc_to(inlines->length() - shift); // remove last elements from compacted array
 344   }
 345 }
 346 
 347 void Compile::remove_useless_late_inlines(GrowableArray<CallGenerator*>* inlines, Node* dead) {
 348   assert(dead != NULL && dead->is_Call(), "sanity");
 349   int found = 0;
 350   for (int i = 0; i < inlines->length(); i++) {
 351     if (inlines->at(i)->call_node() == dead) {
 352       inlines->remove_at(i);
 353       found++;
 354       NOT_DEBUG( break; ) // elements are unique, so exit early
 355     }
 356   }
 357   assert(found <= 1, "not unique");
 358 }
 359 
 360 void Compile::remove_useless_nodes(GrowableArray<Node*>& node_list, Unique_Node_List& useful) {
 361   for (int i = node_list.length() - 1; i >= 0; i--) {
 362     Node* n = node_list.at(i);
 363     if (!useful.member(n)) {
 364       node_list.delete_at(i); // replaces i-th with last element which is known to be useful (already processed)
 365     }
 366   }
 367 }
 368 
 369 void Compile::remove_useless_node(Node* dead) {
 370   remove_modified_node(dead);
 371 
 372   // Constant node that has no out-edges and has only one in-edge from
 373   // root is usually dead. However, sometimes reshaping walk makes
 374   // it reachable by adding use edges. So, we will NOT count Con nodes
 375   // as dead to be conservative about the dead node count at any
 376   // given time.
 377   if (!dead->is_Con()) {
 378     record_dead_node(dead->_idx);
 379   }
 380   if (dead->is_macro()) {
 381     remove_macro_node(dead);
 382   }
 383   if (dead->is_expensive()) {
 384     remove_expensive_node(dead);
 385   }
 386   if (dead->Opcode() == Op_Opaque4) {
 387     remove_skeleton_predicate_opaq(dead);
 388   }
 389   if (dead->for_post_loop_opts_igvn()) {
 390     remove_from_post_loop_opts_igvn(dead);
 391   }
 392   if (dead->is_Call()) {
 393     remove_useless_late_inlines(                &_late_inlines, dead);
 394     remove_useless_late_inlines(         &_string_late_inlines, dead);
 395     remove_useless_late_inlines(         &_boxing_late_inlines, dead);
 396     remove_useless_late_inlines(&_vector_reboxing_late_inlines, dead);
 397   }
 398   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 399   bs->unregister_potential_barrier_node(dead);
 400 }
 401 
 402 // Disconnect all useless nodes by disconnecting those at the boundary.
 403 void Compile::remove_useless_nodes(Unique_Node_List &useful) {
 404   uint next = 0;
 405   while (next < useful.size()) {
 406     Node *n = useful.at(next++);
 407     if (n->is_SafePoint()) {
 408       // We're done with a parsing phase. Replaced nodes are not valid
 409       // beyond that point.
 410       n->as_SafePoint()->delete_replaced_nodes();
 411     }
 412     // Use raw traversal of out edges since this code removes out edges
 413     int max = n->outcnt();
 414     for (int j = 0; j < max; ++j) {
 415       Node* child = n->raw_out(j);
 416       if (!useful.member(child)) {
 417         assert(!child->is_top() || child != top(),
 418                "If top is cached in Compile object it is in useful list");
 419         // Only need to remove this out-edge to the useless node
 420         n->raw_del_out(j);
 421         --j;
 422         --max;
 423       }
 424     }
 425     if (n->outcnt() == 1 && n->has_special_unique_user()) {
 426       record_for_igvn(n->unique_out());
 427     }
 428   }
 429 
 430   remove_useless_nodes(_macro_nodes,        useful); // remove useless macro nodes
 431   remove_useless_nodes(_predicate_opaqs,    useful); // remove useless predicate opaque nodes
 432   remove_useless_nodes(_skeleton_predicate_opaqs, useful);
 433   remove_useless_nodes(_expensive_nodes,    useful); // remove useless expensive nodes
 434   remove_useless_nodes(_for_post_loop_igvn, useful); // remove useless node recorded for post loop opts IGVN pass
 435   remove_useless_coarsened_locks(useful);            // remove useless coarsened locks nodes
 436 
 437   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 438   bs->eliminate_useless_gc_barriers(useful, this);
 439   // clean up the late inline lists
 440   remove_useless_late_inlines(                &_late_inlines, useful);
 441   remove_useless_late_inlines(         &_string_late_inlines, useful);
 442   remove_useless_late_inlines(         &_boxing_late_inlines, useful);
 443   remove_useless_late_inlines(&_vector_reboxing_late_inlines, useful);
 444   debug_only(verify_graph_edges(true/*check for no_dead_code*/);)
 445 }
 446 
 447 // ============================================================================
 448 //------------------------------CompileWrapper---------------------------------
 449 class CompileWrapper : public StackObj {
 450   Compile *const _compile;
 451  public:
 452   CompileWrapper(Compile* compile);
 453 
 454   ~CompileWrapper();
 455 };
 456 
 457 CompileWrapper::CompileWrapper(Compile* compile) : _compile(compile) {
 458   // the Compile* pointer is stored in the current ciEnv:
 459   ciEnv* env = compile->env();
 460   assert(env == ciEnv::current(), "must already be a ciEnv active");
 461   assert(env->compiler_data() == NULL, "compile already active?");
 462   env->set_compiler_data(compile);
 463   assert(compile == Compile::current(), "sanity");
 464 
 465   compile->set_type_dict(NULL);
 466   compile->set_clone_map(new Dict(cmpkey, hashkey, _compile->comp_arena()));
 467   compile->clone_map().set_clone_idx(0);
 468   compile->set_type_last_size(0);
 469   compile->set_last_tf(NULL, NULL);
 470   compile->set_indexSet_arena(NULL);
 471   compile->set_indexSet_free_block_list(NULL);
 472   compile->init_type_arena();
 473   Type::Initialize(compile);
 474   _compile->begin_method();
 475   _compile->clone_map().set_debug(_compile->has_method() && _compile->directive()->CloneMapDebugOption);
 476 }
 477 CompileWrapper::~CompileWrapper() {
 478   // simulate crash during compilation
 479   assert(CICrashAt < 0 || _compile->compile_id() != CICrashAt, "just as planned");
 480 
 481   _compile->end_method();
 482   _compile->env()->set_compiler_data(NULL);
 483 }
 484 
 485 
 486 //----------------------------print_compile_messages---------------------------
 487 void Compile::print_compile_messages() {
 488 #ifndef PRODUCT
 489   // Check if recompiling
 490   if (!subsume_loads() && PrintOpto) {
 491     // Recompiling without allowing machine instructions to subsume loads
 492     tty->print_cr("*********************************************************");
 493     tty->print_cr("** Bailout: Recompile without subsuming loads          **");
 494     tty->print_cr("*********************************************************");
 495   }
 496   if ((do_escape_analysis() != DoEscapeAnalysis) && PrintOpto) {
 497     // Recompiling without escape analysis
 498     tty->print_cr("*********************************************************");
 499     tty->print_cr("** Bailout: Recompile without escape analysis          **");
 500     tty->print_cr("*********************************************************");
 501   }
 502   if (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   root()->dump(9999);
 552   if (xtty != NULL) {
 553     xtty->tail("ideal");
 554   }
 555 }
 556 #endif
 557 
 558 // ============================================================================
 559 //------------------------------Compile standard-------------------------------
 560 debug_only( int Compile::_debug_idx = 100000; )
 561 
 562 // Compile a method.  entry_bci is -1 for normal compilations and indicates
 563 // the continuation bci for on stack replacement.
 564 
 565 
 566 Compile::Compile( ciEnv* ci_env, ciMethod* target, int osr_bci,
 567                   Options options, DirectiveSet* directive)
 568                 : Phase(Compiler),
 569                   _compile_id(ci_env->compile_id()),
 570                   _options(options),
 571                   _method(target),
 572                   _entry_bci(osr_bci),
 573                   _ilt(NULL),
 574                   _stub_function(NULL),
 575                   _stub_name(NULL),
 576                   _stub_entry_point(NULL),
 577                   _max_node_limit(MaxNodeLimit),
 578                   _post_loop_opts_phase(false),
 579                   _inlining_progress(false),
 580                   _inlining_incrementally(false),
 581                   _do_cleanup(false),
 582                   _has_reserved_stack_access(target->has_reserved_stack_access()),
 583 #ifndef PRODUCT
 584                   _igv_idx(0),
 585                   _trace_opto_output(directive->TraceOptoOutputOption),
 586 #endif
 587                   _has_method_handle_invokes(false),
 588                   _clinit_barrier_on_entry(false),
 589                   _stress_seed(0),
 590                   _comp_arena(mtCompiler),
 591                   _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 592                   _env(ci_env),
 593                   _directive(directive),
 594                   _log(ci_env->log()),
 595                   _failure_reason(NULL),
 596                   _intrinsics        (comp_arena(), 0, 0, NULL),
 597                   _macro_nodes       (comp_arena(), 8, 0, NULL),
 598                   _predicate_opaqs   (comp_arena(), 8, 0, NULL),
 599                   _skeleton_predicate_opaqs (comp_arena(), 8, 0, NULL),
 600                   _expensive_nodes   (comp_arena(), 8, 0, NULL),
 601                   _for_post_loop_igvn(comp_arena(), 8, 0, NULL),
 602                   _coarsened_locks   (comp_arena(), 8, 0, NULL),
 603                   _congraph(NULL),
 604                   NOT_PRODUCT(_igv_printer(NULL) COMMA)
 605                   _dead_node_list(comp_arena()),
 606                   _dead_node_count(0),
 607                   _node_arena(mtCompiler),
 608                   _old_arena(mtCompiler),
 609                   _mach_constant_base_node(NULL),
 610                   _Compile_types(mtCompiler),
 611                   _initial_gvn(NULL),
 612                   _for_igvn(NULL),
 613                   _late_inlines(comp_arena(), 2, 0, NULL),
 614                   _string_late_inlines(comp_arena(), 2, 0, NULL),
 615                   _boxing_late_inlines(comp_arena(), 2, 0, NULL),
 616                   _vector_reboxing_late_inlines(comp_arena(), 2, 0, NULL),
 617                   _late_inlines_pos(0),
 618                   _number_of_mh_late_inlines(0),

 619                   _print_inlining_stream(NULL),
 620                   _print_inlining_list(NULL),
 621                   _print_inlining_idx(0),
 622                   _print_inlining_output(NULL),
 623                   _replay_inline_data(NULL),
 624                   _java_calls(0),
 625                   _inner_loops(0),
 626                   _interpreter_frame_size(0)
 627 #ifndef PRODUCT
 628                   , _in_dump_cnt(0)
 629 #endif
 630 {
 631   C = this;
 632   CompileWrapper cw(this);
 633 
 634   if (CITimeVerbose) {
 635     tty->print(" ");
 636     target->holder()->name()->print();
 637     tty->print(".");
 638     target->print_short_name();
 639     tty->print("  ");
 640   }
 641   TraceTime t1("Total compilation time", &_t_totalCompilation, CITime, CITimeVerbose);
 642   TraceTime t2(NULL, &_t_methodCompilation, CITime, false);
 643 
 644 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
 645   bool print_opto_assembly = directive->PrintOptoAssemblyOption;
 646   // We can always print a disassembly, either abstract (hex dump) or
 647   // with the help of a suitable hsdis library. Thus, we should not
 648   // couple print_assembly and print_opto_assembly controls.
 649   // But: always print opto and regular assembly on compile command 'print'.
 650   bool print_assembly = directive->PrintAssemblyOption;
 651   set_print_assembly(print_opto_assembly || print_assembly);
 652 #else
 653   set_print_assembly(false); // must initialize.
 654 #endif
 655 
 656 #ifndef PRODUCT
 657   set_parsed_irreducible_loop(false);
 658 
 659   if (directive->ReplayInlineOption) {
 660     _replay_inline_data = ciReplay::load_inline_data(method(), entry_bci(), ci_env->comp_level());
 661   }
 662 #endif
 663   set_print_inlining(directive->PrintInliningOption || PrintOptoInlining);
 664   set_print_intrinsics(directive->PrintIntrinsicsOption);
 665   set_has_irreducible_loop(true); // conservative until build_loop_tree() reset it
 666 
 667   if (ProfileTraps RTM_OPT_ONLY( || UseRTMLocking )) {
 668     // Make sure the method being compiled gets its own MDO,
 669     // so we can at least track the decompile_count().
 670     // Need MDO to record RTM code generation state.
 671     method()->ensure_method_data();
 672   }
 673 
 674   Init(::AliasLevel);
 675 
 676 
 677   print_compile_messages();
 678 
 679   _ilt = InlineTree::build_inline_tree_root();
 680 
 681   // Even if NO memory addresses are used, MergeMem nodes must have at least 1 slice
 682   assert(num_alias_types() >= AliasIdxRaw, "");
 683 
 684 #define MINIMUM_NODE_HASH  1023
 685   // Node list that Iterative GVN will start with
 686   Unique_Node_List for_igvn(comp_arena());
 687   set_for_igvn(&for_igvn);
 688 
 689   // GVN that will be run immediately on new nodes
 690   uint estimated_size = method()->code_size()*4+64;
 691   estimated_size = (estimated_size < MINIMUM_NODE_HASH ? MINIMUM_NODE_HASH : estimated_size);
 692   PhaseGVN gvn(node_arena(), estimated_size);
 693   set_initial_gvn(&gvn);
 694 
 695   print_inlining_init();
 696   { // Scope for timing the parser
 697     TracePhase tp("parse", &timers[_t_parser]);
 698 
 699     // Put top into the hash table ASAP.
 700     initial_gvn()->transform_no_reclaim(top());
 701 
 702     // Set up tf(), start(), and find a CallGenerator.
 703     CallGenerator* cg = NULL;
 704     if (is_osr_compilation()) {
 705       const TypeTuple *domain = StartOSRNode::osr_domain();
 706       const TypeTuple *range = TypeTuple::make_range(method()->signature());
 707       init_tf(TypeFunc::make(domain, range));
 708       StartNode* s = new StartOSRNode(root(), domain);
 709       initial_gvn()->set_type_bottom(s);
 710       init_start(s);
 711       cg = CallGenerator::for_osr(method(), entry_bci());
 712     } else {
 713       // Normal case.
 714       init_tf(TypeFunc::make(method()));
 715       StartNode* s = new StartNode(root(), tf()->domain());
 716       initial_gvn()->set_type_bottom(s);
 717       init_start(s);
 718       if (method()->intrinsic_id() == vmIntrinsics::_Reference_get) {
 719         // With java.lang.ref.reference.get() we must go through the
 720         // intrinsic - even when get() is the root
 721         // method of the compile - so that, if necessary, the value in
 722         // the referent field of the reference object gets recorded by
 723         // the pre-barrier code.
 724         cg = find_intrinsic(method(), false);
 725       }
 726       if (cg == NULL) {
 727         float past_uses = method()->interpreter_invocation_count();
 728         float expected_uses = past_uses;
 729         cg = CallGenerator::for_inline(method(), expected_uses);
 730       }
 731     }
 732     if (failing())  return;
 733     if (cg == NULL) {
 734       record_method_not_compilable("cannot parse method");
 735       return;
 736     }
 737     JVMState* jvms = build_start_state(start(), tf());
 738     if ((jvms = cg->generate(jvms)) == NULL) {
 739       if (!failure_reason_is(C2Compiler::retry_class_loading_during_parsing())) {
 740         record_method_not_compilable("method parse failed");
 741       }
 742       return;
 743     }
 744     GraphKit kit(jvms);
 745 
 746     if (!kit.stopped()) {
 747       // Accept return values, and transfer control we know not where.
 748       // This is done by a special, unique ReturnNode bound to root.
 749       return_values(kit.jvms());
 750     }
 751 
 752     if (kit.has_exceptions()) {
 753       // Any exceptions that escape from this call must be rethrown
 754       // to whatever caller is dynamically above us on the stack.
 755       // This is done by a special, unique RethrowNode bound to root.
 756       rethrow_exceptions(kit.transfer_exceptions_into_jvms());
 757     }
 758 
 759     assert(IncrementalInline || (_late_inlines.length() == 0 && !has_mh_late_inlines()), "incremental inlining is off");
 760 
 761     if (_late_inlines.length() == 0 && !has_mh_late_inlines() && !failing() && has_stringbuilder()) {
 762       inline_string_calls(true);
 763     }
 764 
 765     if (failing())  return;
 766 
 767     print_method(PHASE_BEFORE_REMOVEUSELESS, 3);
 768 
 769     // Remove clutter produced by parsing.
 770     if (!failing()) {
 771       ResourceMark rm;
 772       PhaseRemoveUseless pru(initial_gvn(), &for_igvn);
 773     }
 774   }
 775 
 776   // Note:  Large methods are capped off in do_one_bytecode().
 777   if (failing())  return;
 778 
 779   // After parsing, node notes are no longer automagic.
 780   // They must be propagated by register_new_node_with_optimizer(),
 781   // clone(), or the like.
 782   set_default_node_notes(NULL);
 783 
 784 #ifndef PRODUCT
 785   if (should_print_igv(1)) {
 786     _igv_printer->print_inlining();
 787   }
 788 #endif
 789 
 790   if (failing())  return;
 791   NOT_PRODUCT( verify_graph_edges(); )
 792 
 793   // If any phase is randomized for stress testing, seed random number
 794   // generation and log the seed for repeatability.
 795   if (StressLCM || StressGCM || StressIGVN || StressCCP) {
 796     if (FLAG_IS_DEFAULT(StressSeed) || (FLAG_IS_ERGO(StressSeed) && RepeatCompilation)) {
 797       _stress_seed = static_cast<uint>(Ticks::now().nanoseconds());
 798       FLAG_SET_ERGO(StressSeed, _stress_seed);
 799     } else {
 800       _stress_seed = StressSeed;
 801     }
 802     if (_log != NULL) {
 803       _log->elem("stress_test seed='%u'", _stress_seed);
 804     }
 805   }
 806 
 807   // Now optimize
 808   Optimize();
 809   if (failing())  return;
 810   NOT_PRODUCT( verify_graph_edges(); )
 811 
 812 #ifndef PRODUCT
 813   if (should_print_ideal()) {
 814     print_ideal_ir("print_ideal");
 815   }
 816 #endif
 817 
 818 #ifdef ASSERT
 819   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
 820   bs->verify_gc_barriers(this, BarrierSetC2::BeforeCodeGen);
 821 #endif
 822 
 823   // Dump compilation data to replay it.
 824   if (directive->DumpReplayOption) {
 825     env()->dump_replay_data(_compile_id);
 826   }
 827   if (directive->DumpInlineOption && (ilt() != NULL)) {
 828     env()->dump_inline_data(_compile_id);
 829   }
 830 
 831   // Now that we know the size of all the monitors we can add a fixed slot
 832   // for the original deopt pc.
 833   int next_slot = fixed_slots() + (sizeof(address) / VMRegImpl::stack_slot_size);
 834   set_fixed_slots(next_slot);
 835 
 836   // Compute when to use implicit null checks. Used by matching trap based
 837   // nodes and NullCheck optimization.
 838   set_allowed_deopt_reasons();
 839 
 840   // Now generate code
 841   Code_Gen();
 842 }
 843 
 844 //------------------------------Compile----------------------------------------
 845 // Compile a runtime stub
 846 Compile::Compile( ciEnv* ci_env,
 847                   TypeFunc_generator generator,
 848                   address stub_function,
 849                   const char *stub_name,
 850                   int is_fancy_jump,
 851                   bool pass_tls,
 852                   bool return_pc,
 853                   DirectiveSet* directive)
 854   : Phase(Compiler),
 855     _compile_id(0),
 856     _options(Options::for_runtime_stub()),
 857     _method(NULL),
 858     _entry_bci(InvocationEntryBci),
 859     _stub_function(stub_function),
 860     _stub_name(stub_name),
 861     _stub_entry_point(NULL),
 862     _max_node_limit(MaxNodeLimit),
 863     _post_loop_opts_phase(false),
 864     _inlining_progress(false),
 865     _inlining_incrementally(false),
 866     _has_reserved_stack_access(false),
 867 #ifndef PRODUCT
 868     _igv_idx(0),
 869     _trace_opto_output(directive->TraceOptoOutputOption),
 870 #endif
 871     _has_method_handle_invokes(false),
 872     _clinit_barrier_on_entry(false),
 873     _stress_seed(0),
 874     _comp_arena(mtCompiler),
 875     _barrier_set_state(BarrierSet::barrier_set()->barrier_set_c2()->create_barrier_state(comp_arena())),
 876     _env(ci_env),
 877     _directive(directive),
 878     _log(ci_env->log()),
 879     _failure_reason(NULL),
 880     _congraph(NULL),
 881     NOT_PRODUCT(_igv_printer(NULL) COMMA)
 882     _dead_node_list(comp_arena()),
 883     _dead_node_count(0),
 884     _node_arena(mtCompiler),
 885     _old_arena(mtCompiler),
 886     _mach_constant_base_node(NULL),
 887     _Compile_types(mtCompiler),
 888     _initial_gvn(NULL),
 889     _for_igvn(NULL),
 890     _number_of_mh_late_inlines(0),

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




4962 Node* Compile::narrow_value(BasicType bt, Node* value, const Type* type, PhaseGVN* phase, bool transform_res) {
4963   if (type != NULL && phase->type(value)->higher_equal(type)) {
4964     return value;
4965   }
4966   Node* result = NULL;
4967   if (bt == T_BYTE) {
4968     result = phase->transform(new LShiftINode(value, phase->intcon(24)));
4969     result = new RShiftINode(result, phase->intcon(24));
4970   } else if (bt == T_BOOLEAN) {
4971     result = new AndINode(value, phase->intcon(0xFF));
4972   } else if (bt == T_CHAR) {
4973     result = new AndINode(value,phase->intcon(0xFFFF));
4974   } else {
4975     assert(bt == T_SHORT, "unexpected narrow type");
4976     result = phase->transform(new LShiftINode(value, phase->intcon(16)));
4977     result = new RShiftINode(result, phase->intcon(16));
4978   }
4979   if (transform_res) {
4980     result = phase->transform(result);
4981   }
4982   return result;
4983 }
4984 
--- EOF ---