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