1 /*
   2  * Copyright (c) 1997, 2018, 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 "memory/allocation.inline.hpp"
  27 #include "opto/addnode.hpp"
  28 #include "opto/callnode.hpp"
  29 #include "opto/connode.hpp"
  30 #include "opto/idealGraphPrinter.hpp"
  31 #include "opto/matcher.hpp"
  32 #include "opto/memnode.hpp"
  33 #include "opto/opcodes.hpp"
  34 #include "opto/regmask.hpp"
  35 #include "opto/rootnode.hpp"
  36 #include "opto/runtime.hpp"
  37 #include "opto/type.hpp"
  38 #include "opto/vectornode.hpp"
  39 #include "runtime/atomic.hpp"
  40 #include "runtime/os.hpp"
  41 #if defined AD_MD_HPP
  42 # include AD_MD_HPP
  43 #elif defined TARGET_ARCH_MODEL_x86_32
  44 # include "adfiles/ad_x86_32.hpp"
  45 #elif defined TARGET_ARCH_MODEL_x86_64
  46 # include "adfiles/ad_x86_64.hpp"
  47 #elif defined TARGET_ARCH_MODEL_sparc
  48 # include "adfiles/ad_sparc.hpp"
  49 #elif defined TARGET_ARCH_MODEL_zero
  50 # include "adfiles/ad_zero.hpp"
  51 #elif defined TARGET_ARCH_MODEL_ppc_64
  52 # include "adfiles/ad_ppc_64.hpp"
  53 #endif
  54 
  55 OptoReg::Name OptoReg::c_frame_pointer;
  56 
  57 const RegMask *Matcher::idealreg2regmask[_last_machine_leaf];
  58 RegMask Matcher::mreg2regmask[_last_Mach_Reg];
  59 RegMask Matcher::STACK_ONLY_mask;
  60 RegMask Matcher::c_frame_ptr_mask;
  61 const uint Matcher::_begin_rematerialize = _BEGIN_REMATERIALIZE;
  62 const uint Matcher::_end_rematerialize   = _END_REMATERIALIZE;
  63 
  64 //---------------------------Matcher-------------------------------------------
  65 Matcher::Matcher()
  66 : PhaseTransform( Phase::Ins_Select ),
  67 #ifdef ASSERT
  68   _old2new_map(C->comp_arena()),
  69   _new2old_map(C->comp_arena()),
  70 #endif
  71   _shared_nodes(C->comp_arena()),
  72   _reduceOp(reduceOp), _leftOp(leftOp), _rightOp(rightOp),
  73   _swallowed(swallowed),
  74   _begin_inst_chain_rule(_BEGIN_INST_CHAIN_RULE),
  75   _end_inst_chain_rule(_END_INST_CHAIN_RULE),
  76   _must_clone(must_clone),
  77   _register_save_policy(register_save_policy),
  78   _c_reg_save_policy(c_reg_save_policy),
  79   _register_save_type(register_save_type),
  80   _ruleName(ruleName),
  81   _allocation_started(false),
  82   _states_arena(Chunk::medium_size, mtCompiler),
  83   _visited(&_states_arena),
  84   _shared(&_states_arena),
  85   _dontcare(&_states_arena) {
  86   C->set_matcher(this);
  87 
  88   idealreg2spillmask  [Op_RegI] = NULL;
  89   idealreg2spillmask  [Op_RegN] = NULL;
  90   idealreg2spillmask  [Op_RegL] = NULL;
  91   idealreg2spillmask  [Op_RegF] = NULL;
  92   idealreg2spillmask  [Op_RegD] = NULL;
  93   idealreg2spillmask  [Op_RegP] = NULL;
  94   idealreg2spillmask  [Op_VecS] = NULL;
  95   idealreg2spillmask  [Op_VecD] = NULL;
  96   idealreg2spillmask  [Op_VecX] = NULL;
  97   idealreg2spillmask  [Op_VecY] = NULL;
  98 
  99   idealreg2debugmask  [Op_RegI] = NULL;
 100   idealreg2debugmask  [Op_RegN] = NULL;
 101   idealreg2debugmask  [Op_RegL] = NULL;
 102   idealreg2debugmask  [Op_RegF] = NULL;
 103   idealreg2debugmask  [Op_RegD] = NULL;
 104   idealreg2debugmask  [Op_RegP] = NULL;
 105   idealreg2debugmask  [Op_VecS] = NULL;
 106   idealreg2debugmask  [Op_VecD] = NULL;
 107   idealreg2debugmask  [Op_VecX] = NULL;
 108   idealreg2debugmask  [Op_VecY] = NULL;
 109 
 110   idealreg2mhdebugmask[Op_RegI] = NULL;
 111   idealreg2mhdebugmask[Op_RegN] = NULL;
 112   idealreg2mhdebugmask[Op_RegL] = NULL;
 113   idealreg2mhdebugmask[Op_RegF] = NULL;
 114   idealreg2mhdebugmask[Op_RegD] = NULL;
 115   idealreg2mhdebugmask[Op_RegP] = NULL;
 116   idealreg2mhdebugmask[Op_VecS] = NULL;
 117   idealreg2mhdebugmask[Op_VecD] = NULL;
 118   idealreg2mhdebugmask[Op_VecX] = NULL;
 119   idealreg2mhdebugmask[Op_VecY] = NULL;
 120 
 121   debug_only(_mem_node = NULL;)   // Ideal memory node consumed by mach node
 122 }
 123 
 124 //------------------------------warp_incoming_stk_arg------------------------
 125 // This warps a VMReg into an OptoReg::Name
 126 OptoReg::Name Matcher::warp_incoming_stk_arg( VMReg reg ) {
 127   OptoReg::Name warped;
 128   if( reg->is_stack() ) {  // Stack slot argument?
 129     warped = OptoReg::add(_old_SP, reg->reg2stack() );
 130     warped = OptoReg::add(warped, C->out_preserve_stack_slots());
 131     if( warped >= _in_arg_limit )
 132       _in_arg_limit = OptoReg::add(warped, 1); // Bump max stack slot seen
 133     if (!RegMask::can_represent_arg(warped)) {
 134       // the compiler cannot represent this method's calling sequence
 135       C->record_method_not_compilable_all_tiers("unsupported incoming calling sequence");
 136       return OptoReg::Bad;
 137     }
 138     return warped;
 139   }
 140   return OptoReg::as_OptoReg(reg);
 141 }
 142 
 143 //---------------------------compute_old_SP------------------------------------
 144 OptoReg::Name Compile::compute_old_SP() {
 145   int fixed    = fixed_slots();
 146   int preserve = in_preserve_stack_slots();
 147   return OptoReg::stack2reg(round_to(fixed + preserve, Matcher::stack_alignment_in_slots()));
 148 }
 149 
 150 
 151 
 152 #ifdef ASSERT
 153 void Matcher::verify_new_nodes_only(Node* xroot) {
 154   // Make sure that the new graph only references new nodes
 155   ResourceMark rm;
 156   Unique_Node_List worklist;
 157   VectorSet visited(Thread::current()->resource_area());
 158   worklist.push(xroot);
 159   while (worklist.size() > 0) {
 160     Node* n = worklist.pop();
 161     visited <<= n->_idx;
 162     assert(C->node_arena()->contains(n), "dead node");
 163     for (uint j = 0; j < n->req(); j++) {
 164       Node* in = n->in(j);
 165       if (in != NULL) {
 166         assert(C->node_arena()->contains(in), "dead node");
 167         if (!visited.test(in->_idx)) {
 168           worklist.push(in);
 169         }
 170       }
 171     }
 172   }
 173 }
 174 #endif
 175 
 176 
 177 //---------------------------match---------------------------------------------
 178 void Matcher::match( ) {
 179   if( MaxLabelRootDepth < 100 ) { // Too small?
 180     assert(false, "invalid MaxLabelRootDepth, increase it to 100 minimum");
 181     MaxLabelRootDepth = 100;
 182   }
 183   // One-time initialization of some register masks.
 184   init_spill_mask( C->root()->in(1) );
 185   _return_addr_mask = return_addr();
 186 #ifdef _LP64
 187   // Pointers take 2 slots in 64-bit land
 188   _return_addr_mask.Insert(OptoReg::add(return_addr(),1));
 189 #endif
 190 
 191   // Map a Java-signature return type into return register-value
 192   // machine registers for 0, 1 and 2 returned values.
 193   const TypeTuple *range = C->tf()->range();
 194   if( range->cnt() > TypeFunc::Parms ) { // If not a void function
 195     // Get ideal-register return type
 196     uint ireg = range->field_at(TypeFunc::Parms)->ideal_reg();
 197     // Get machine return register
 198     uint sop = C->start()->Opcode();
 199     OptoRegPair regs = return_value(ireg, false);
 200 
 201     // And mask for same
 202     _return_value_mask = RegMask(regs.first());
 203     if( OptoReg::is_valid(regs.second()) )
 204       _return_value_mask.Insert(regs.second());
 205   }
 206 
 207   // ---------------
 208   // Frame Layout
 209 
 210   // Need the method signature to determine the incoming argument types,
 211   // because the types determine which registers the incoming arguments are
 212   // in, and this affects the matched code.
 213   const TypeTuple *domain = C->tf()->domain();
 214   uint             argcnt = domain->cnt() - TypeFunc::Parms;
 215   BasicType *sig_bt        = NEW_RESOURCE_ARRAY( BasicType, argcnt );
 216   VMRegPair *vm_parm_regs  = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
 217   _parm_regs               = NEW_RESOURCE_ARRAY( OptoRegPair, argcnt );
 218   _calling_convention_mask = NEW_RESOURCE_ARRAY( RegMask, argcnt );
 219   uint i;
 220   for( i = 0; i<argcnt; i++ ) {
 221     sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
 222   }
 223 
 224   // Pass array of ideal registers and length to USER code (from the AD file)
 225   // that will convert this to an array of register numbers.
 226   const StartNode *start = C->start();
 227   start->calling_convention( sig_bt, vm_parm_regs, argcnt );
 228 #ifdef ASSERT
 229   // Sanity check users' calling convention.  Real handy while trying to
 230   // get the initial port correct.
 231   { for (uint i = 0; i<argcnt; i++) {
 232       if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
 233         assert(domain->field_at(i+TypeFunc::Parms)==Type::HALF, "only allowed on halve" );
 234         _parm_regs[i].set_bad();
 235         continue;
 236       }
 237       VMReg parm_reg = vm_parm_regs[i].first();
 238       assert(parm_reg->is_valid(), "invalid arg?");
 239       if (parm_reg->is_reg()) {
 240         OptoReg::Name opto_parm_reg = OptoReg::as_OptoReg(parm_reg);
 241         assert(can_be_java_arg(opto_parm_reg) ||
 242                C->stub_function() == CAST_FROM_FN_PTR(address, OptoRuntime::rethrow_C) ||
 243                opto_parm_reg == inline_cache_reg(),
 244                "parameters in register must be preserved by runtime stubs");
 245       }
 246       for (uint j = 0; j < i; j++) {
 247         assert(parm_reg != vm_parm_regs[j].first(),
 248                "calling conv. must produce distinct regs");
 249       }
 250     }
 251   }
 252 #endif
 253 
 254   // Do some initial frame layout.
 255 
 256   // Compute the old incoming SP (may be called FP) as
 257   //   OptoReg::stack0() + locks + in_preserve_stack_slots + pad2.
 258   _old_SP = C->compute_old_SP();
 259   assert( is_even(_old_SP), "must be even" );
 260 
 261   // Compute highest incoming stack argument as
 262   //   _old_SP + out_preserve_stack_slots + incoming argument size.
 263   _in_arg_limit = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
 264   assert( is_even(_in_arg_limit), "out_preserve must be even" );
 265   for( i = 0; i < argcnt; i++ ) {
 266     // Permit args to have no register
 267     _calling_convention_mask[i].Clear();
 268     if( !vm_parm_regs[i].first()->is_valid() && !vm_parm_regs[i].second()->is_valid() ) {
 269       continue;
 270     }
 271     // calling_convention returns stack arguments as a count of
 272     // slots beyond OptoReg::stack0()/VMRegImpl::stack0.  We need to convert this to
 273     // the allocators point of view, taking into account all the
 274     // preserve area, locks & pad2.
 275 
 276     OptoReg::Name reg1 = warp_incoming_stk_arg(vm_parm_regs[i].first());
 277     if( OptoReg::is_valid(reg1))
 278       _calling_convention_mask[i].Insert(reg1);
 279 
 280     OptoReg::Name reg2 = warp_incoming_stk_arg(vm_parm_regs[i].second());
 281     if( OptoReg::is_valid(reg2))
 282       _calling_convention_mask[i].Insert(reg2);
 283 
 284     // Saved biased stack-slot register number
 285     _parm_regs[i].set_pair(reg2, reg1);
 286   }
 287 
 288   // Finally, make sure the incoming arguments take up an even number of
 289   // words, in case the arguments or locals need to contain doubleword stack
 290   // slots.  The rest of the system assumes that stack slot pairs (in
 291   // particular, in the spill area) which look aligned will in fact be
 292   // aligned relative to the stack pointer in the target machine.  Double
 293   // stack slots will always be allocated aligned.
 294   _new_SP = OptoReg::Name(round_to(_in_arg_limit, RegMask::SlotsPerLong));
 295 
 296   // Compute highest outgoing stack argument as
 297   //   _new_SP + out_preserve_stack_slots + max(outgoing argument size).
 298   _out_arg_limit = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
 299   assert( is_even(_out_arg_limit), "out_preserve must be even" );
 300 
 301   if (!RegMask::can_represent_arg(OptoReg::add(_out_arg_limit,-1))) {
 302     // the compiler cannot represent this method's calling sequence
 303     C->record_method_not_compilable("must be able to represent all call arguments in reg mask");
 304   }
 305 
 306   if (C->failing())  return;  // bailed out on incoming arg failure
 307 
 308   // ---------------
 309   // Collect roots of matcher trees.  Every node for which
 310   // _shared[_idx] is cleared is guaranteed to not be shared, and thus
 311   // can be a valid interior of some tree.
 312   find_shared( C->root() );
 313   find_shared( C->top() );
 314 
 315   C->print_method(PHASE_BEFORE_MATCHING);
 316 
 317   // Create new ideal node ConP #NULL even if it does exist in old space
 318   // to avoid false sharing if the corresponding mach node is not used.
 319   // The corresponding mach node is only used in rare cases for derived
 320   // pointers.
 321   Node* new_ideal_null = ConNode::make(C, TypePtr::NULL_PTR);
 322 
 323   // Swap out to old-space; emptying new-space
 324   Arena *old = C->node_arena()->move_contents(C->old_arena());
 325 
 326   // Save debug and profile information for nodes in old space:
 327   _old_node_note_array = C->node_note_array();
 328   if (_old_node_note_array != NULL) {
 329     C->set_node_note_array(new(C->comp_arena()) GrowableArray<Node_Notes*>
 330                            (C->comp_arena(), _old_node_note_array->length(),
 331                             0, NULL));
 332   }
 333 
 334   // Pre-size the new_node table to avoid the need for range checks.
 335   grow_new_node_array(C->unique());
 336 
 337   // Reset node counter so MachNodes start with _idx at 0
 338   int live_nodes = C->live_nodes();
 339   C->set_unique(0);
 340   C->reset_dead_node_list();
 341 
 342   // Recursively match trees from old space into new space.
 343   // Correct leaves of new-space Nodes; they point to old-space.
 344   _visited.Clear();             // Clear visit bits for xform call
 345   C->set_cached_top_node(xform( C->top(), live_nodes));
 346   if (!C->failing()) {
 347     Node* xroot =        xform( C->root(), 1 );
 348     if (xroot == NULL) {
 349       Matcher::soft_match_failure();  // recursive matching process failed
 350       C->record_method_not_compilable("instruction match failed");
 351     } else {
 352       // During matching shared constants were attached to C->root()
 353       // because xroot wasn't available yet, so transfer the uses to
 354       // the xroot.
 355       for( DUIterator_Fast jmax, j = C->root()->fast_outs(jmax); j < jmax; j++ ) {
 356         Node* n = C->root()->fast_out(j);
 357         if (C->node_arena()->contains(n)) {
 358           assert(n->in(0) == C->root(), "should be control user");
 359           n->set_req(0, xroot);
 360           --j;
 361           --jmax;
 362         }
 363       }
 364 
 365       // Generate new mach node for ConP #NULL
 366       assert(new_ideal_null != NULL, "sanity");
 367       _mach_null = match_tree(new_ideal_null);
 368       // Don't set control, it will confuse GCM since there are no uses.
 369       // The control will be set when this node is used first time
 370       // in find_base_for_derived().
 371       assert(_mach_null != NULL, "");
 372 
 373       C->set_root(xroot->is_Root() ? xroot->as_Root() : NULL);
 374 
 375 #ifdef ASSERT
 376       verify_new_nodes_only(xroot);
 377 #endif
 378     }
 379   }
 380   if (C->top() == NULL || C->root() == NULL) {
 381     C->record_method_not_compilable("graph lost"); // %%% cannot happen?
 382   }
 383   if (C->failing()) {
 384     // delete old;
 385     old->destruct_contents();
 386     return;
 387   }
 388   assert( C->top(), "" );
 389   assert( C->root(), "" );
 390   validate_null_checks();
 391 
 392   // Now smoke old-space
 393   NOT_DEBUG( old->destruct_contents() );
 394 
 395   // ------------------------
 396   // Set up save-on-entry registers
 397   Fixup_Save_On_Entry( );
 398 }
 399 
 400 
 401 //------------------------------Fixup_Save_On_Entry----------------------------
 402 // The stated purpose of this routine is to take care of save-on-entry
 403 // registers.  However, the overall goal of the Match phase is to convert into
 404 // machine-specific instructions which have RegMasks to guide allocation.
 405 // So what this procedure really does is put a valid RegMask on each input
 406 // to the machine-specific variations of all Return, TailCall and Halt
 407 // instructions.  It also adds edgs to define the save-on-entry values (and of
 408 // course gives them a mask).
 409 
 410 static RegMask *init_input_masks( uint size, RegMask &ret_adr, RegMask &fp ) {
 411   RegMask *rms = NEW_RESOURCE_ARRAY( RegMask, size );
 412   // Do all the pre-defined register masks
 413   rms[TypeFunc::Control  ] = RegMask::Empty;
 414   rms[TypeFunc::I_O      ] = RegMask::Empty;
 415   rms[TypeFunc::Memory   ] = RegMask::Empty;
 416   rms[TypeFunc::ReturnAdr] = ret_adr;
 417   rms[TypeFunc::FramePtr ] = fp;
 418   return rms;
 419 }
 420 
 421 //---------------------------init_first_stack_mask-----------------------------
 422 // Create the initial stack mask used by values spilling to the stack.
 423 // Disallow any debug info in outgoing argument areas by setting the
 424 // initial mask accordingly.
 425 void Matcher::init_first_stack_mask() {
 426 
 427   // Allocate storage for spill masks as masks for the appropriate load type.
 428   RegMask *rms = (RegMask*)C->comp_arena()->Amalloc_D(sizeof(RegMask) * (3*6+4));
 429 
 430   idealreg2spillmask  [Op_RegN] = &rms[0];
 431   idealreg2spillmask  [Op_RegI] = &rms[1];
 432   idealreg2spillmask  [Op_RegL] = &rms[2];
 433   idealreg2spillmask  [Op_RegF] = &rms[3];
 434   idealreg2spillmask  [Op_RegD] = &rms[4];
 435   idealreg2spillmask  [Op_RegP] = &rms[5];
 436 
 437   idealreg2debugmask  [Op_RegN] = &rms[6];
 438   idealreg2debugmask  [Op_RegI] = &rms[7];
 439   idealreg2debugmask  [Op_RegL] = &rms[8];
 440   idealreg2debugmask  [Op_RegF] = &rms[9];
 441   idealreg2debugmask  [Op_RegD] = &rms[10];
 442   idealreg2debugmask  [Op_RegP] = &rms[11];
 443 
 444   idealreg2mhdebugmask[Op_RegN] = &rms[12];
 445   idealreg2mhdebugmask[Op_RegI] = &rms[13];
 446   idealreg2mhdebugmask[Op_RegL] = &rms[14];
 447   idealreg2mhdebugmask[Op_RegF] = &rms[15];
 448   idealreg2mhdebugmask[Op_RegD] = &rms[16];
 449   idealreg2mhdebugmask[Op_RegP] = &rms[17];
 450 
 451   idealreg2spillmask  [Op_VecS] = &rms[18];
 452   idealreg2spillmask  [Op_VecD] = &rms[19];
 453   idealreg2spillmask  [Op_VecX] = &rms[20];
 454   idealreg2spillmask  [Op_VecY] = &rms[21];
 455 
 456   OptoReg::Name i;
 457 
 458   // At first, start with the empty mask
 459   C->FIRST_STACK_mask().Clear();
 460 
 461   // Add in the incoming argument area
 462   OptoReg::Name init_in = OptoReg::add(_old_SP, C->out_preserve_stack_slots());
 463   for (i = init_in; i < _in_arg_limit; i = OptoReg::add(i,1)) {
 464     C->FIRST_STACK_mask().Insert(i);
 465   }
 466   // Add in all bits past the outgoing argument area
 467   guarantee(RegMask::can_represent_arg(OptoReg::add(_out_arg_limit,-1)),
 468             "must be able to represent all call arguments in reg mask");
 469   OptoReg::Name init = _out_arg_limit;
 470   for (i = init; RegMask::can_represent(i); i = OptoReg::add(i,1)) {
 471     C->FIRST_STACK_mask().Insert(i);
 472   }
 473   // Finally, set the "infinite stack" bit.
 474   C->FIRST_STACK_mask().set_AllStack();
 475 
 476   // Make spill masks.  Registers for their class, plus FIRST_STACK_mask.
 477   RegMask aligned_stack_mask = C->FIRST_STACK_mask();
 478   // Keep spill masks aligned.
 479   aligned_stack_mask.clear_to_pairs();
 480   assert(aligned_stack_mask.is_AllStack(), "should be infinite stack");
 481 
 482   *idealreg2spillmask[Op_RegP] = *idealreg2regmask[Op_RegP];
 483 #ifdef _LP64
 484   *idealreg2spillmask[Op_RegN] = *idealreg2regmask[Op_RegN];
 485    idealreg2spillmask[Op_RegN]->OR(C->FIRST_STACK_mask());
 486    idealreg2spillmask[Op_RegP]->OR(aligned_stack_mask);
 487 #else
 488    idealreg2spillmask[Op_RegP]->OR(C->FIRST_STACK_mask());
 489 #endif
 490   *idealreg2spillmask[Op_RegI] = *idealreg2regmask[Op_RegI];
 491    idealreg2spillmask[Op_RegI]->OR(C->FIRST_STACK_mask());
 492   *idealreg2spillmask[Op_RegL] = *idealreg2regmask[Op_RegL];
 493    idealreg2spillmask[Op_RegL]->OR(aligned_stack_mask);
 494   *idealreg2spillmask[Op_RegF] = *idealreg2regmask[Op_RegF];
 495    idealreg2spillmask[Op_RegF]->OR(C->FIRST_STACK_mask());
 496   *idealreg2spillmask[Op_RegD] = *idealreg2regmask[Op_RegD];
 497    idealreg2spillmask[Op_RegD]->OR(aligned_stack_mask);
 498 
 499   if (Matcher::vector_size_supported(T_BYTE,4)) {
 500     *idealreg2spillmask[Op_VecS] = *idealreg2regmask[Op_VecS];
 501      idealreg2spillmask[Op_VecS]->OR(C->FIRST_STACK_mask());
 502   }
 503   if (Matcher::vector_size_supported(T_FLOAT,2)) {
 504     // For VecD we need dual alignment and 8 bytes (2 slots) for spills.
 505     // RA guarantees such alignment since it is needed for Double and Long values.
 506     *idealreg2spillmask[Op_VecD] = *idealreg2regmask[Op_VecD];
 507      idealreg2spillmask[Op_VecD]->OR(aligned_stack_mask);
 508   }
 509   if (Matcher::vector_size_supported(T_FLOAT,4)) {
 510     // For VecX we need quadro alignment and 16 bytes (4 slots) for spills.
 511     //
 512     // RA can use input arguments stack slots for spills but until RA
 513     // we don't know frame size and offset of input arg stack slots.
 514     //
 515     // Exclude last input arg stack slots to avoid spilling vectors there
 516     // otherwise vector spills could stomp over stack slots in caller frame.
 517     OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
 518     for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecX); k++) {
 519       aligned_stack_mask.Remove(in);
 520       in = OptoReg::add(in, -1);
 521     }
 522      aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecX);
 523      assert(aligned_stack_mask.is_AllStack(), "should be infinite stack");
 524     *idealreg2spillmask[Op_VecX] = *idealreg2regmask[Op_VecX];
 525      idealreg2spillmask[Op_VecX]->OR(aligned_stack_mask);
 526   }
 527   if (Matcher::vector_size_supported(T_FLOAT,8)) {
 528     // For VecY we need octo alignment and 32 bytes (8 slots) for spills.
 529     OptoReg::Name in = OptoReg::add(_in_arg_limit, -1);
 530     for (int k = 1; (in >= init_in) && (k < RegMask::SlotsPerVecY); k++) {
 531       aligned_stack_mask.Remove(in);
 532       in = OptoReg::add(in, -1);
 533     }
 534      aligned_stack_mask.clear_to_sets(RegMask::SlotsPerVecY);
 535      assert(aligned_stack_mask.is_AllStack(), "should be infinite stack");
 536     *idealreg2spillmask[Op_VecY] = *idealreg2regmask[Op_VecY];
 537      idealreg2spillmask[Op_VecY]->OR(aligned_stack_mask);
 538   }
 539    if (UseFPUForSpilling) {
 540      // This mask logic assumes that the spill operations are
 541      // symmetric and that the registers involved are the same size.
 542      // On sparc for instance we may have to use 64 bit moves will
 543      // kill 2 registers when used with F0-F31.
 544      idealreg2spillmask[Op_RegI]->OR(*idealreg2regmask[Op_RegF]);
 545      idealreg2spillmask[Op_RegF]->OR(*idealreg2regmask[Op_RegI]);
 546 #ifdef _LP64
 547      idealreg2spillmask[Op_RegN]->OR(*idealreg2regmask[Op_RegF]);
 548      idealreg2spillmask[Op_RegL]->OR(*idealreg2regmask[Op_RegD]);
 549      idealreg2spillmask[Op_RegD]->OR(*idealreg2regmask[Op_RegL]);
 550      idealreg2spillmask[Op_RegP]->OR(*idealreg2regmask[Op_RegD]);
 551 #else
 552      idealreg2spillmask[Op_RegP]->OR(*idealreg2regmask[Op_RegF]);
 553 #ifdef ARM
 554      // ARM has support for moving 64bit values between a pair of
 555      // integer registers and a double register
 556      idealreg2spillmask[Op_RegL]->OR(*idealreg2regmask[Op_RegD]);
 557      idealreg2spillmask[Op_RegD]->OR(*idealreg2regmask[Op_RegL]);
 558 #endif
 559 #endif
 560    }
 561 
 562   // Make up debug masks.  Any spill slot plus callee-save registers.
 563   // Caller-save registers are assumed to be trashable by the various
 564   // inline-cache fixup routines.
 565   *idealreg2debugmask  [Op_RegN]= *idealreg2spillmask[Op_RegN];
 566   *idealreg2debugmask  [Op_RegI]= *idealreg2spillmask[Op_RegI];
 567   *idealreg2debugmask  [Op_RegL]= *idealreg2spillmask[Op_RegL];
 568   *idealreg2debugmask  [Op_RegF]= *idealreg2spillmask[Op_RegF];
 569   *idealreg2debugmask  [Op_RegD]= *idealreg2spillmask[Op_RegD];
 570   *idealreg2debugmask  [Op_RegP]= *idealreg2spillmask[Op_RegP];
 571 
 572   *idealreg2mhdebugmask[Op_RegN]= *idealreg2spillmask[Op_RegN];
 573   *idealreg2mhdebugmask[Op_RegI]= *idealreg2spillmask[Op_RegI];
 574   *idealreg2mhdebugmask[Op_RegL]= *idealreg2spillmask[Op_RegL];
 575   *idealreg2mhdebugmask[Op_RegF]= *idealreg2spillmask[Op_RegF];
 576   *idealreg2mhdebugmask[Op_RegD]= *idealreg2spillmask[Op_RegD];
 577   *idealreg2mhdebugmask[Op_RegP]= *idealreg2spillmask[Op_RegP];
 578 
 579   // Prevent stub compilations from attempting to reference
 580   // callee-saved registers from debug info
 581   bool exclude_soe = !Compile::current()->is_method_compilation();
 582 
 583   for( i=OptoReg::Name(0); i<OptoReg::Name(_last_Mach_Reg); i = OptoReg::add(i,1) ) {
 584     // registers the caller has to save do not work
 585     if( _register_save_policy[i] == 'C' ||
 586         _register_save_policy[i] == 'A' ||
 587         (_register_save_policy[i] == 'E' && exclude_soe) ) {
 588       idealreg2debugmask  [Op_RegN]->Remove(i);
 589       idealreg2debugmask  [Op_RegI]->Remove(i); // Exclude save-on-call
 590       idealreg2debugmask  [Op_RegL]->Remove(i); // registers from debug
 591       idealreg2debugmask  [Op_RegF]->Remove(i); // masks
 592       idealreg2debugmask  [Op_RegD]->Remove(i);
 593       idealreg2debugmask  [Op_RegP]->Remove(i);
 594 
 595       idealreg2mhdebugmask[Op_RegN]->Remove(i);
 596       idealreg2mhdebugmask[Op_RegI]->Remove(i);
 597       idealreg2mhdebugmask[Op_RegL]->Remove(i);
 598       idealreg2mhdebugmask[Op_RegF]->Remove(i);
 599       idealreg2mhdebugmask[Op_RegD]->Remove(i);
 600       idealreg2mhdebugmask[Op_RegP]->Remove(i);
 601     }
 602   }
 603 
 604   // Subtract the register we use to save the SP for MethodHandle
 605   // invokes to from the debug mask.
 606   const RegMask save_mask = method_handle_invoke_SP_save_mask();
 607   idealreg2mhdebugmask[Op_RegN]->SUBTRACT(save_mask);
 608   idealreg2mhdebugmask[Op_RegI]->SUBTRACT(save_mask);
 609   idealreg2mhdebugmask[Op_RegL]->SUBTRACT(save_mask);
 610   idealreg2mhdebugmask[Op_RegF]->SUBTRACT(save_mask);
 611   idealreg2mhdebugmask[Op_RegD]->SUBTRACT(save_mask);
 612   idealreg2mhdebugmask[Op_RegP]->SUBTRACT(save_mask);
 613 }
 614 
 615 //---------------------------is_save_on_entry----------------------------------
 616 bool Matcher::is_save_on_entry( int reg ) {
 617   return
 618     _register_save_policy[reg] == 'E' ||
 619     _register_save_policy[reg] == 'A' || // Save-on-entry register?
 620     // Also save argument registers in the trampolining stubs
 621     (C->save_argument_registers() && is_spillable_arg(reg));
 622 }
 623 
 624 //---------------------------Fixup_Save_On_Entry-------------------------------
 625 void Matcher::Fixup_Save_On_Entry( ) {
 626   init_first_stack_mask();
 627 
 628   Node *root = C->root();       // Short name for root
 629   // Count number of save-on-entry registers.
 630   uint soe_cnt = number_of_saved_registers();
 631   uint i;
 632 
 633   // Find the procedure Start Node
 634   StartNode *start = C->start();
 635   assert( start, "Expect a start node" );
 636 
 637   // Save argument registers in the trampolining stubs
 638   if( C->save_argument_registers() )
 639     for( i = 0; i < _last_Mach_Reg; i++ )
 640       if( is_spillable_arg(i) )
 641         soe_cnt++;
 642 
 643   // Input RegMask array shared by all Returns.
 644   // The type for doubles and longs has a count of 2, but
 645   // there is only 1 returned value
 646   uint ret_edge_cnt = TypeFunc::Parms + ((C->tf()->range()->cnt() == TypeFunc::Parms) ? 0 : 1);
 647   RegMask *ret_rms  = init_input_masks( ret_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
 648   // Returns have 0 or 1 returned values depending on call signature.
 649   // Return register is specified by return_value in the AD file.
 650   if (ret_edge_cnt > TypeFunc::Parms)
 651     ret_rms[TypeFunc::Parms+0] = _return_value_mask;
 652 
 653   // Input RegMask array shared by all Rethrows.
 654   uint reth_edge_cnt = TypeFunc::Parms+1;
 655   RegMask *reth_rms  = init_input_masks( reth_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
 656   // Rethrow takes exception oop only, but in the argument 0 slot.
 657   reth_rms[TypeFunc::Parms] = mreg2regmask[find_receiver(false)];
 658 #ifdef _LP64
 659   // Need two slots for ptrs in 64-bit land
 660   reth_rms[TypeFunc::Parms].Insert(OptoReg::add(OptoReg::Name(find_receiver(false)),1));
 661 #endif
 662 
 663   // Input RegMask array shared by all TailCalls
 664   uint tail_call_edge_cnt = TypeFunc::Parms+2;
 665   RegMask *tail_call_rms = init_input_masks( tail_call_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
 666 
 667   // Input RegMask array shared by all TailJumps
 668   uint tail_jump_edge_cnt = TypeFunc::Parms+2;
 669   RegMask *tail_jump_rms = init_input_masks( tail_jump_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
 670 
 671   // TailCalls have 2 returned values (target & moop), whose masks come
 672   // from the usual MachNode/MachOper mechanism.  Find a sample
 673   // TailCall to extract these masks and put the correct masks into
 674   // the tail_call_rms array.
 675   for( i=1; i < root->req(); i++ ) {
 676     MachReturnNode *m = root->in(i)->as_MachReturn();
 677     if( m->ideal_Opcode() == Op_TailCall ) {
 678       tail_call_rms[TypeFunc::Parms+0] = m->MachNode::in_RegMask(TypeFunc::Parms+0);
 679       tail_call_rms[TypeFunc::Parms+1] = m->MachNode::in_RegMask(TypeFunc::Parms+1);
 680       break;
 681     }
 682   }
 683 
 684   // TailJumps have 2 returned values (target & ex_oop), whose masks come
 685   // from the usual MachNode/MachOper mechanism.  Find a sample
 686   // TailJump to extract these masks and put the correct masks into
 687   // the tail_jump_rms array.
 688   for( i=1; i < root->req(); i++ ) {
 689     MachReturnNode *m = root->in(i)->as_MachReturn();
 690     if( m->ideal_Opcode() == Op_TailJump ) {
 691       tail_jump_rms[TypeFunc::Parms+0] = m->MachNode::in_RegMask(TypeFunc::Parms+0);
 692       tail_jump_rms[TypeFunc::Parms+1] = m->MachNode::in_RegMask(TypeFunc::Parms+1);
 693       break;
 694     }
 695   }
 696 
 697   // Input RegMask array shared by all Halts
 698   uint halt_edge_cnt = TypeFunc::Parms;
 699   RegMask *halt_rms = init_input_masks( halt_edge_cnt + soe_cnt, _return_addr_mask, c_frame_ptr_mask );
 700 
 701   // Capture the return input masks into each exit flavor
 702   for( i=1; i < root->req(); i++ ) {
 703     MachReturnNode *exit = root->in(i)->as_MachReturn();
 704     switch( exit->ideal_Opcode() ) {
 705       case Op_Return   : exit->_in_rms = ret_rms;  break;
 706       case Op_Rethrow  : exit->_in_rms = reth_rms; break;
 707       case Op_TailCall : exit->_in_rms = tail_call_rms; break;
 708       case Op_TailJump : exit->_in_rms = tail_jump_rms; break;
 709       case Op_Halt     : exit->_in_rms = halt_rms; break;
 710       default          : ShouldNotReachHere();
 711     }
 712   }
 713 
 714   // Next unused projection number from Start.
 715   int proj_cnt = C->tf()->domain()->cnt();
 716 
 717   // Do all the save-on-entry registers.  Make projections from Start for
 718   // them, and give them a use at the exit points.  To the allocator, they
 719   // look like incoming register arguments.
 720   for( i = 0; i < _last_Mach_Reg; i++ ) {
 721     if( is_save_on_entry(i) ) {
 722 
 723       // Add the save-on-entry to the mask array
 724       ret_rms      [      ret_edge_cnt] = mreg2regmask[i];
 725       reth_rms     [     reth_edge_cnt] = mreg2regmask[i];
 726       tail_call_rms[tail_call_edge_cnt] = mreg2regmask[i];
 727       tail_jump_rms[tail_jump_edge_cnt] = mreg2regmask[i];
 728       // Halts need the SOE registers, but only in the stack as debug info.
 729       // A just-prior uncommon-trap or deoptimization will use the SOE regs.
 730       halt_rms     [     halt_edge_cnt] = *idealreg2spillmask[_register_save_type[i]];
 731 
 732       Node *mproj;
 733 
 734       // Is this a RegF low half of a RegD?  Double up 2 adjacent RegF's
 735       // into a single RegD.
 736       if( (i&1) == 0 &&
 737           _register_save_type[i  ] == Op_RegF &&
 738           _register_save_type[i+1] == Op_RegF &&
 739           is_save_on_entry(i+1) ) {
 740         // Add other bit for double
 741         ret_rms      [      ret_edge_cnt].Insert(OptoReg::Name(i+1));
 742         reth_rms     [     reth_edge_cnt].Insert(OptoReg::Name(i+1));
 743         tail_call_rms[tail_call_edge_cnt].Insert(OptoReg::Name(i+1));
 744         tail_jump_rms[tail_jump_edge_cnt].Insert(OptoReg::Name(i+1));
 745         halt_rms     [     halt_edge_cnt].Insert(OptoReg::Name(i+1));
 746         mproj = new (C) MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegD );
 747         proj_cnt += 2;          // Skip 2 for doubles
 748       }
 749       else if( (i&1) == 1 &&    // Else check for high half of double
 750                _register_save_type[i-1] == Op_RegF &&
 751                _register_save_type[i  ] == Op_RegF &&
 752                is_save_on_entry(i-1) ) {
 753         ret_rms      [      ret_edge_cnt] = RegMask::Empty;
 754         reth_rms     [     reth_edge_cnt] = RegMask::Empty;
 755         tail_call_rms[tail_call_edge_cnt] = RegMask::Empty;
 756         tail_jump_rms[tail_jump_edge_cnt] = RegMask::Empty;
 757         halt_rms     [     halt_edge_cnt] = RegMask::Empty;
 758         mproj = C->top();
 759       }
 760       // Is this a RegI low half of a RegL?  Double up 2 adjacent RegI's
 761       // into a single RegL.
 762       else if( (i&1) == 0 &&
 763           _register_save_type[i  ] == Op_RegI &&
 764           _register_save_type[i+1] == Op_RegI &&
 765         is_save_on_entry(i+1) ) {
 766         // Add other bit for long
 767         ret_rms      [      ret_edge_cnt].Insert(OptoReg::Name(i+1));
 768         reth_rms     [     reth_edge_cnt].Insert(OptoReg::Name(i+1));
 769         tail_call_rms[tail_call_edge_cnt].Insert(OptoReg::Name(i+1));
 770         tail_jump_rms[tail_jump_edge_cnt].Insert(OptoReg::Name(i+1));
 771         halt_rms     [     halt_edge_cnt].Insert(OptoReg::Name(i+1));
 772         mproj = new (C) MachProjNode( start, proj_cnt, ret_rms[ret_edge_cnt], Op_RegL );
 773         proj_cnt += 2;          // Skip 2 for longs
 774       }
 775       else if( (i&1) == 1 &&    // Else check for high half of long
 776                _register_save_type[i-1] == Op_RegI &&
 777                _register_save_type[i  ] == Op_RegI &&
 778                is_save_on_entry(i-1) ) {
 779         ret_rms      [      ret_edge_cnt] = RegMask::Empty;
 780         reth_rms     [     reth_edge_cnt] = RegMask::Empty;
 781         tail_call_rms[tail_call_edge_cnt] = RegMask::Empty;
 782         tail_jump_rms[tail_jump_edge_cnt] = RegMask::Empty;
 783         halt_rms     [     halt_edge_cnt] = RegMask::Empty;
 784         mproj = C->top();
 785       } else {
 786         // Make a projection for it off the Start
 787         mproj = new (C) MachProjNode( start, proj_cnt++, ret_rms[ret_edge_cnt], _register_save_type[i] );
 788       }
 789 
 790       ret_edge_cnt ++;
 791       reth_edge_cnt ++;
 792       tail_call_edge_cnt ++;
 793       tail_jump_edge_cnt ++;
 794       halt_edge_cnt ++;
 795 
 796       // Add a use of the SOE register to all exit paths
 797       for( uint j=1; j < root->req(); j++ )
 798         root->in(j)->add_req(mproj);
 799     } // End of if a save-on-entry register
 800   } // End of for all machine registers
 801 }
 802 
 803 //------------------------------init_spill_mask--------------------------------
 804 void Matcher::init_spill_mask( Node *ret ) {
 805   if( idealreg2regmask[Op_RegI] ) return; // One time only init
 806 
 807   OptoReg::c_frame_pointer = c_frame_pointer();
 808   c_frame_ptr_mask = c_frame_pointer();
 809 #ifdef _LP64
 810   // pointers are twice as big
 811   c_frame_ptr_mask.Insert(OptoReg::add(c_frame_pointer(),1));
 812 #endif
 813 
 814   // Start at OptoReg::stack0()
 815   STACK_ONLY_mask.Clear();
 816   OptoReg::Name init = OptoReg::stack2reg(0);
 817   // STACK_ONLY_mask is all stack bits
 818   OptoReg::Name i;
 819   for (i = init; RegMask::can_represent(i); i = OptoReg::add(i,1))
 820     STACK_ONLY_mask.Insert(i);
 821   // Also set the "infinite stack" bit.
 822   STACK_ONLY_mask.set_AllStack();
 823 
 824   // Copy the register names over into the shared world
 825   for( i=OptoReg::Name(0); i<OptoReg::Name(_last_Mach_Reg); i = OptoReg::add(i,1) ) {
 826     // SharedInfo::regName[i] = regName[i];
 827     // Handy RegMasks per machine register
 828     mreg2regmask[i].Insert(i);
 829   }
 830 
 831   // Grab the Frame Pointer
 832   Node *fp  = ret->in(TypeFunc::FramePtr);
 833   Node *mem = ret->in(TypeFunc::Memory);
 834   const TypePtr* atp = TypePtr::BOTTOM;
 835   // Share frame pointer while making spill ops
 836   set_shared(fp);
 837 
 838   // Compute generic short-offset Loads
 839 #ifdef _LP64
 840   MachNode *spillCP = match_tree(new (C) LoadNNode(NULL,mem,fp,atp,TypeInstPtr::BOTTOM,MemNode::unordered));
 841 #endif
 842   MachNode *spillI  = match_tree(new (C) LoadINode(NULL,mem,fp,atp,TypeInt::INT,MemNode::unordered));
 843   MachNode *spillL  = match_tree(new (C) LoadLNode(NULL,mem,fp,atp,TypeLong::LONG,MemNode::unordered, LoadNode::DependsOnlyOnTest,false));
 844   MachNode *spillF  = match_tree(new (C) LoadFNode(NULL,mem,fp,atp,Type::FLOAT,MemNode::unordered));
 845   MachNode *spillD  = match_tree(new (C) LoadDNode(NULL,mem,fp,atp,Type::DOUBLE,MemNode::unordered));
 846   MachNode *spillP  = match_tree(new (C) LoadPNode(NULL,mem,fp,atp,TypeInstPtr::BOTTOM,MemNode::unordered));
 847   assert(spillI != NULL && spillL != NULL && spillF != NULL &&
 848          spillD != NULL && spillP != NULL, "");
 849   // Get the ADLC notion of the right regmask, for each basic type.
 850 #ifdef _LP64
 851   idealreg2regmask[Op_RegN] = &spillCP->out_RegMask();
 852 #endif
 853   idealreg2regmask[Op_RegI] = &spillI->out_RegMask();
 854   idealreg2regmask[Op_RegL] = &spillL->out_RegMask();
 855   idealreg2regmask[Op_RegF] = &spillF->out_RegMask();
 856   idealreg2regmask[Op_RegD] = &spillD->out_RegMask();
 857   idealreg2regmask[Op_RegP] = &spillP->out_RegMask();
 858 
 859   // Vector regmasks.
 860   if (Matcher::vector_size_supported(T_BYTE,4)) {
 861     TypeVect::VECTS = TypeVect::make(T_BYTE, 4);
 862     MachNode *spillVectS = match_tree(new (C) LoadVectorNode(NULL,mem,fp,atp,TypeVect::VECTS));
 863     idealreg2regmask[Op_VecS] = &spillVectS->out_RegMask();
 864   }
 865   if (Matcher::vector_size_supported(T_FLOAT,2)) {
 866     MachNode *spillVectD = match_tree(new (C) LoadVectorNode(NULL,mem,fp,atp,TypeVect::VECTD));
 867     idealreg2regmask[Op_VecD] = &spillVectD->out_RegMask();
 868   }
 869   if (Matcher::vector_size_supported(T_FLOAT,4)) {
 870     MachNode *spillVectX = match_tree(new (C) LoadVectorNode(NULL,mem,fp,atp,TypeVect::VECTX));
 871     idealreg2regmask[Op_VecX] = &spillVectX->out_RegMask();
 872   }
 873   if (Matcher::vector_size_supported(T_FLOAT,8)) {
 874     MachNode *spillVectY = match_tree(new (C) LoadVectorNode(NULL,mem,fp,atp,TypeVect::VECTY));
 875     idealreg2regmask[Op_VecY] = &spillVectY->out_RegMask();
 876   }
 877 }
 878 
 879 #ifdef ASSERT
 880 static void match_alias_type(Compile* C, Node* n, Node* m) {
 881   if (!VerifyAliases)  return;  // do not go looking for trouble by default
 882   const TypePtr* nat = n->adr_type();
 883   const TypePtr* mat = m->adr_type();
 884   int nidx = C->get_alias_index(nat);
 885   int midx = C->get_alias_index(mat);
 886   // Detune the assert for cases like (AndI 0xFF (LoadB p)).
 887   if (nidx == Compile::AliasIdxTop && midx >= Compile::AliasIdxRaw) {
 888     for (uint i = 1; i < n->req(); i++) {
 889       Node* n1 = n->in(i);
 890       const TypePtr* n1at = n1->adr_type();
 891       if (n1at != NULL) {
 892         nat = n1at;
 893         nidx = C->get_alias_index(n1at);
 894       }
 895     }
 896   }
 897   // %%% Kludgery.  Instead, fix ideal adr_type methods for all these cases:
 898   if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxRaw) {
 899     switch (n->Opcode()) {
 900     case Op_PrefetchRead:
 901     case Op_PrefetchWrite:
 902     case Op_PrefetchAllocation:
 903       nidx = Compile::AliasIdxRaw;
 904       nat = TypeRawPtr::BOTTOM;
 905       break;
 906     }
 907   }
 908   if (nidx == Compile::AliasIdxRaw && midx == Compile::AliasIdxTop) {
 909     switch (n->Opcode()) {
 910     case Op_ClearArray:
 911       midx = Compile::AliasIdxRaw;
 912       mat = TypeRawPtr::BOTTOM;
 913       break;
 914     }
 915   }
 916   if (nidx == Compile::AliasIdxTop && midx == Compile::AliasIdxBot) {
 917     switch (n->Opcode()) {
 918     case Op_Return:
 919     case Op_Rethrow:
 920     case Op_Halt:
 921     case Op_TailCall:
 922     case Op_TailJump:
 923       nidx = Compile::AliasIdxBot;
 924       nat = TypePtr::BOTTOM;
 925       break;
 926     }
 927   }
 928   if (nidx == Compile::AliasIdxBot && midx == Compile::AliasIdxTop) {
 929     switch (n->Opcode()) {
 930     case Op_StrComp:
 931     case Op_StrEquals:
 932     case Op_StrIndexOf:
 933     case Op_AryEq:
 934     case Op_MemBarVolatile:
 935     case Op_MemBarCPUOrder: // %%% these ideals should have narrower adr_type?
 936     case Op_EncodeISOArray:
 937       nidx = Compile::AliasIdxTop;
 938       nat = NULL;
 939       break;
 940     }
 941   }
 942   if (nidx != midx) {
 943     if (PrintOpto || (PrintMiscellaneous && (WizardMode || Verbose))) {
 944       tty->print_cr("==== Matcher alias shift %d => %d", nidx, midx);
 945       n->dump();
 946       m->dump();
 947     }
 948     assert(C->subsume_loads() && C->must_alias(nat, midx),
 949            "must not lose alias info when matching");
 950   }
 951 }
 952 #endif
 953 
 954 
 955 //------------------------------MStack-----------------------------------------
 956 // State and MStack class used in xform() and find_shared() iterative methods.
 957 enum Node_State { Pre_Visit,  // node has to be pre-visited
 958                       Visit,  // visit node
 959                  Post_Visit,  // post-visit node
 960              Alt_Post_Visit   // alternative post-visit path
 961                 };
 962 
 963 class MStack: public Node_Stack {
 964   public:
 965     MStack(int size) : Node_Stack(size) { }
 966 
 967     void push(Node *n, Node_State ns) {
 968       Node_Stack::push(n, (uint)ns);
 969     }
 970     void push(Node *n, Node_State ns, Node *parent, int indx) {
 971       ++_inode_top;
 972       if ((_inode_top + 1) >= _inode_max) grow();
 973       _inode_top->node = parent;
 974       _inode_top->indx = (uint)indx;
 975       ++_inode_top;
 976       _inode_top->node = n;
 977       _inode_top->indx = (uint)ns;
 978     }
 979     Node *parent() {
 980       pop();
 981       return node();
 982     }
 983     Node_State state() const {
 984       return (Node_State)index();
 985     }
 986     void set_state(Node_State ns) {
 987       set_index((uint)ns);
 988     }
 989 };
 990 
 991 
 992 //------------------------------xform------------------------------------------
 993 // Given a Node in old-space, Match him (Label/Reduce) to produce a machine
 994 // Node in new-space.  Given a new-space Node, recursively walk his children.
 995 Node *Matcher::transform( Node *n ) { ShouldNotCallThis(); return n; }
 996 Node *Matcher::xform( Node *n, int max_stack ) {
 997   // Use one stack to keep both: child's node/state and parent's node/index
 998   MStack mstack(max_stack * 2 * 2); // usually: C->live_nodes() * 2 * 2
 999   mstack.push(n, Visit, NULL, -1);  // set NULL as parent to indicate root
1000 
1001   while (mstack.is_nonempty()) {
1002     C->check_node_count(NodeLimitFudgeFactor, "too many nodes matching instructions");
1003     if (C->failing()) return NULL;
1004     n = mstack.node();          // Leave node on stack
1005     Node_State nstate = mstack.state();
1006     if (nstate == Visit) {
1007       mstack.set_state(Post_Visit);
1008       Node *oldn = n;
1009       // Old-space or new-space check
1010       if (!C->node_arena()->contains(n)) {
1011         // Old space!
1012         Node* m;
1013         if (has_new_node(n)) {  // Not yet Label/Reduced
1014           m = new_node(n);
1015         } else {
1016           if (!is_dontcare(n)) { // Matcher can match this guy
1017             // Calls match special.  They match alone with no children.
1018             // Their children, the incoming arguments, match normally.
1019             m = n->is_SafePoint() ? match_sfpt(n->as_SafePoint()):match_tree(n);
1020             if (C->failing())  return NULL;
1021             if (m == NULL) { Matcher::soft_match_failure(); return NULL; }
1022           } else {                  // Nothing the matcher cares about
1023             if (n->is_Proj() && n->in(0) != NULL && n->in(0)->is_Multi()) {       // Projections?
1024               // Convert to machine-dependent projection
1025               m = n->in(0)->as_Multi()->match( n->as_Proj(), this );
1026 #ifdef ASSERT
1027               _new2old_map.map(m->_idx, n);
1028 #endif
1029               if (m->in(0) != NULL) // m might be top
1030                 collect_null_checks(m, n);
1031             } else {                // Else just a regular 'ol guy
1032               m = n->clone();       // So just clone into new-space
1033 #ifdef ASSERT
1034               _new2old_map.map(m->_idx, n);
1035 #endif
1036               // Def-Use edges will be added incrementally as Uses
1037               // of this node are matched.
1038               assert(m->outcnt() == 0, "no Uses of this clone yet");
1039             }
1040           }
1041 
1042           set_new_node(n, m);       // Map old to new
1043           if (_old_node_note_array != NULL) {
1044             Node_Notes* nn = C->locate_node_notes(_old_node_note_array,
1045                                                   n->_idx);
1046             C->set_node_notes_at(m->_idx, nn);
1047           }
1048           debug_only(match_alias_type(C, n, m));
1049         }
1050         n = m;    // n is now a new-space node
1051         mstack.set_node(n);
1052       }
1053 
1054       // New space!
1055       if (_visited.test_set(n->_idx)) continue; // while(mstack.is_nonempty())
1056 
1057       int i;
1058       // Put precedence edges on stack first (match them last).
1059       for (i = oldn->req(); (uint)i < oldn->len(); i++) {
1060         Node *m = oldn->in(i);
1061         if (m == NULL) break;
1062         // set -1 to call add_prec() instead of set_req() during Step1
1063         mstack.push(m, Visit, n, -1);
1064       }
1065 
1066       // For constant debug info, I'd rather have unmatched constants.
1067       int cnt = n->req();
1068       JVMState* jvms = n->jvms();
1069       int debug_cnt = jvms ? jvms->debug_start() : cnt;
1070 
1071       // Now do only debug info.  Clone constants rather than matching.
1072       // Constants are represented directly in the debug info without
1073       // the need for executable machine instructions.
1074       // Monitor boxes are also represented directly.
1075       for (i = cnt - 1; i >= debug_cnt; --i) { // For all debug inputs do
1076         Node *m = n->in(i);          // Get input
1077         int op = m->Opcode();
1078         assert((op == Op_BoxLock) == jvms->is_monitor_use(i), "boxes only at monitor sites");
1079         if( op == Op_ConI || op == Op_ConP || op == Op_ConN || op == Op_ConNKlass ||
1080             op == Op_ConF || op == Op_ConD || op == Op_ConL
1081             // || op == Op_BoxLock  // %%%% enable this and remove (+++) in chaitin.cpp
1082             ) {
1083           m = m->clone();
1084 #ifdef ASSERT
1085           _new2old_map.map(m->_idx, n);
1086 #endif
1087           mstack.push(m, Post_Visit, n, i); // Don't need to visit
1088           mstack.push(m->in(0), Visit, m, 0);
1089         } else {
1090           mstack.push(m, Visit, n, i);
1091         }
1092       }
1093 
1094       // And now walk his children, and convert his inputs to new-space.
1095       for( ; i >= 0; --i ) { // For all normal inputs do
1096         Node *m = n->in(i);  // Get input
1097         if(m != NULL)
1098           mstack.push(m, Visit, n, i);
1099       }
1100 
1101     }
1102     else if (nstate == Post_Visit) {
1103       // Set xformed input
1104       Node *p = mstack.parent();
1105       if (p != NULL) { // root doesn't have parent
1106         int i = (int)mstack.index();
1107         if (i >= 0)
1108           p->set_req(i, n); // required input
1109         else if (i == -1)
1110           p->add_prec(n);   // precedence input
1111         else
1112           ShouldNotReachHere();
1113       }
1114       mstack.pop(); // remove processed node from stack
1115     }
1116     else {
1117       ShouldNotReachHere();
1118     }
1119   } // while (mstack.is_nonempty())
1120   return n; // Return new-space Node
1121 }
1122 
1123 //------------------------------warp_outgoing_stk_arg------------------------
1124 OptoReg::Name Matcher::warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call ) {
1125   // Convert outgoing argument location to a pre-biased stack offset
1126   if (reg->is_stack()) {
1127     OptoReg::Name warped = reg->reg2stack();
1128     // Adjust the stack slot offset to be the register number used
1129     // by the allocator.
1130     warped = OptoReg::add(begin_out_arg_area, warped);
1131     // Keep track of the largest numbered stack slot used for an arg.
1132     // Largest used slot per call-site indicates the amount of stack
1133     // that is killed by the call.
1134     if( warped >= out_arg_limit_per_call )
1135       out_arg_limit_per_call = OptoReg::add(warped,1);
1136     if (!RegMask::can_represent_arg(warped)) {
1137       C->record_method_not_compilable_all_tiers("unsupported calling sequence");
1138       return OptoReg::Bad;
1139     }
1140     return warped;
1141   }
1142   return OptoReg::as_OptoReg(reg);
1143 }
1144 
1145 
1146 //------------------------------match_sfpt-------------------------------------
1147 // Helper function to match call instructions.  Calls match special.
1148 // They match alone with no children.  Their children, the incoming
1149 // arguments, match normally.
1150 MachNode *Matcher::match_sfpt( SafePointNode *sfpt ) {
1151   MachSafePointNode *msfpt = NULL;
1152   MachCallNode      *mcall = NULL;
1153   uint               cnt;
1154   // Split out case for SafePoint vs Call
1155   CallNode *call;
1156   const TypeTuple *domain;
1157   ciMethod*        method = NULL;
1158   bool             is_method_handle_invoke = false;  // for special kill effects
1159   if( sfpt->is_Call() ) {
1160     call = sfpt->as_Call();
1161     domain = call->tf()->domain();
1162     cnt = domain->cnt();
1163 
1164     // Match just the call, nothing else
1165     MachNode *m = match_tree(call);
1166     if (C->failing())  return NULL;
1167     if( m == NULL ) { Matcher::soft_match_failure(); return NULL; }
1168 
1169     // Copy data from the Ideal SafePoint to the machine version
1170     mcall = m->as_MachCall();
1171 
1172     mcall->set_tf(         call->tf());
1173     mcall->set_entry_point(call->entry_point());
1174     mcall->set_cnt(        call->cnt());
1175 
1176     if( mcall->is_MachCallJava() ) {
1177       MachCallJavaNode *mcall_java  = mcall->as_MachCallJava();
1178       const CallJavaNode *call_java =  call->as_CallJava();
1179       method = call_java->method();
1180       mcall_java->_method = method;
1181       mcall_java->_bci = call_java->_bci;
1182       mcall_java->_optimized_virtual = call_java->is_optimized_virtual();
1183       is_method_handle_invoke = call_java->is_method_handle_invoke();
1184       mcall_java->_method_handle_invoke = is_method_handle_invoke;
1185       if (is_method_handle_invoke) {
1186         C->set_has_method_handle_invokes(true);
1187       }
1188       if( mcall_java->is_MachCallStaticJava() )
1189         mcall_java->as_MachCallStaticJava()->_name =
1190          call_java->as_CallStaticJava()->_name;
1191       if( mcall_java->is_MachCallDynamicJava() )
1192         mcall_java->as_MachCallDynamicJava()->_vtable_index =
1193          call_java->as_CallDynamicJava()->_vtable_index;
1194     }
1195     else if( mcall->is_MachCallRuntime() ) {
1196       mcall->as_MachCallRuntime()->_name = call->as_CallRuntime()->_name;
1197     }
1198     msfpt = mcall;
1199   }
1200   // This is a non-call safepoint
1201   else {
1202     call = NULL;
1203     domain = NULL;
1204     MachNode *mn = match_tree(sfpt);
1205     if (C->failing())  return NULL;
1206     msfpt = mn->as_MachSafePoint();
1207     cnt = TypeFunc::Parms;
1208   }
1209 
1210   // Advertise the correct memory effects (for anti-dependence computation).
1211   msfpt->set_adr_type(sfpt->adr_type());
1212 
1213   // Allocate a private array of RegMasks.  These RegMasks are not shared.
1214   msfpt->_in_rms = NEW_RESOURCE_ARRAY( RegMask, cnt );
1215   // Empty them all.
1216   memset( msfpt->_in_rms, 0, sizeof(RegMask)*cnt );
1217 
1218   // Do all the pre-defined non-Empty register masks
1219   msfpt->_in_rms[TypeFunc::ReturnAdr] = _return_addr_mask;
1220   msfpt->_in_rms[TypeFunc::FramePtr ] = c_frame_ptr_mask;
1221 
1222   // Place first outgoing argument can possibly be put.
1223   OptoReg::Name begin_out_arg_area = OptoReg::add(_new_SP, C->out_preserve_stack_slots());
1224   assert( is_even(begin_out_arg_area), "" );
1225   // Compute max outgoing register number per call site.
1226   OptoReg::Name out_arg_limit_per_call = begin_out_arg_area;
1227   // Calls to C may hammer extra stack slots above and beyond any arguments.
1228   // These are usually backing store for register arguments for varargs.
1229   if( call != NULL && call->is_CallRuntime() )
1230     out_arg_limit_per_call = OptoReg::add(out_arg_limit_per_call,C->varargs_C_out_slots_killed());
1231 
1232 
1233   // Do the normal argument list (parameters) register masks
1234   int argcnt = cnt - TypeFunc::Parms;
1235   if( argcnt > 0 ) {          // Skip it all if we have no args
1236     BasicType *sig_bt  = NEW_RESOURCE_ARRAY( BasicType, argcnt );
1237     VMRegPair *parm_regs = NEW_RESOURCE_ARRAY( VMRegPair, argcnt );
1238     int i;
1239     for( i = 0; i < argcnt; i++ ) {
1240       sig_bt[i] = domain->field_at(i+TypeFunc::Parms)->basic_type();
1241     }
1242     // V-call to pick proper calling convention
1243     call->calling_convention( sig_bt, parm_regs, argcnt );
1244 
1245 #ifdef ASSERT
1246     // Sanity check users' calling convention.  Really handy during
1247     // the initial porting effort.  Fairly expensive otherwise.
1248     { for (int i = 0; i<argcnt; i++) {
1249       if( !parm_regs[i].first()->is_valid() &&
1250           !parm_regs[i].second()->is_valid() ) continue;
1251       VMReg reg1 = parm_regs[i].first();
1252       VMReg reg2 = parm_regs[i].second();
1253       for (int j = 0; j < i; j++) {
1254         if( !parm_regs[j].first()->is_valid() &&
1255             !parm_regs[j].second()->is_valid() ) continue;
1256         VMReg reg3 = parm_regs[j].first();
1257         VMReg reg4 = parm_regs[j].second();
1258         if( !reg1->is_valid() ) {
1259           assert( !reg2->is_valid(), "valid halvsies" );
1260         } else if( !reg3->is_valid() ) {
1261           assert( !reg4->is_valid(), "valid halvsies" );
1262         } else {
1263           assert( reg1 != reg2, "calling conv. must produce distinct regs");
1264           assert( reg1 != reg3, "calling conv. must produce distinct regs");
1265           assert( reg1 != reg4, "calling conv. must produce distinct regs");
1266           assert( reg2 != reg3, "calling conv. must produce distinct regs");
1267           assert( reg2 != reg4 || !reg2->is_valid(), "calling conv. must produce distinct regs");
1268           assert( reg3 != reg4, "calling conv. must produce distinct regs");
1269         }
1270       }
1271     }
1272     }
1273 #endif
1274 
1275     // Visit each argument.  Compute its outgoing register mask.
1276     // Return results now can have 2 bits returned.
1277     // Compute max over all outgoing arguments both per call-site
1278     // and over the entire method.
1279     for( i = 0; i < argcnt; i++ ) {
1280       // Address of incoming argument mask to fill in
1281       RegMask *rm = &mcall->_in_rms[i+TypeFunc::Parms];
1282       if( !parm_regs[i].first()->is_valid() &&
1283           !parm_regs[i].second()->is_valid() ) {
1284         continue;               // Avoid Halves
1285       }
1286       // Grab first register, adjust stack slots and insert in mask.
1287       OptoReg::Name reg1 = warp_outgoing_stk_arg(parm_regs[i].first(), begin_out_arg_area, out_arg_limit_per_call );
1288       if (OptoReg::is_valid(reg1))
1289         rm->Insert( reg1 );
1290       // Grab second register (if any), adjust stack slots and insert in mask.
1291       OptoReg::Name reg2 = warp_outgoing_stk_arg(parm_regs[i].second(), begin_out_arg_area, out_arg_limit_per_call );
1292       if (OptoReg::is_valid(reg2))
1293         rm->Insert( reg2 );
1294     } // End of for all arguments
1295 
1296     // Compute number of stack slots needed to restore stack in case of
1297     // Pascal-style argument popping.
1298     mcall->_argsize = out_arg_limit_per_call - begin_out_arg_area;
1299   }
1300 
1301   // Compute the max stack slot killed by any call.  These will not be
1302   // available for debug info, and will be used to adjust FIRST_STACK_mask
1303   // after all call sites have been visited.
1304   if( _out_arg_limit < out_arg_limit_per_call)
1305     _out_arg_limit = out_arg_limit_per_call;
1306 
1307   if (mcall) {
1308     // Kill the outgoing argument area, including any non-argument holes and
1309     // any legacy C-killed slots.  Use Fat-Projections to do the killing.
1310     // Since the max-per-method covers the max-per-call-site and debug info
1311     // is excluded on the max-per-method basis, debug info cannot land in
1312     // this killed area.
1313     uint r_cnt = mcall->tf()->range()->cnt();
1314     MachProjNode *proj = new (C) MachProjNode( mcall, r_cnt+10000, RegMask::Empty, MachProjNode::fat_proj );
1315     if (!RegMask::can_represent_arg(OptoReg::Name(out_arg_limit_per_call-1))) {
1316       C->record_method_not_compilable_all_tiers("unsupported outgoing calling sequence");
1317     } else {
1318       for (int i = begin_out_arg_area; i < out_arg_limit_per_call; i++)
1319         proj->_rout.Insert(OptoReg::Name(i));
1320     }
1321     if (proj->_rout.is_NotEmpty()) {
1322       push_projection(proj);
1323     }
1324   }
1325   // Transfer the safepoint information from the call to the mcall
1326   // Move the JVMState list
1327   msfpt->set_jvms(sfpt->jvms());
1328   for (JVMState* jvms = msfpt->jvms(); jvms; jvms = jvms->caller()) {
1329     jvms->set_map(sfpt);
1330   }
1331 
1332   // Debug inputs begin just after the last incoming parameter
1333   assert((mcall == NULL) || (mcall->jvms() == NULL) ||
1334          (mcall->jvms()->debug_start() + mcall->_jvmadj == mcall->tf()->domain()->cnt()), "");
1335 
1336   // Move the OopMap
1337   msfpt->_oop_map = sfpt->_oop_map;
1338 
1339   // Add additional edges.
1340   if (msfpt->mach_constant_base_node_input() != (uint)-1 && !msfpt->is_MachCallLeaf()) {
1341     // For these calls we can not add MachConstantBase in expand(), as the
1342     // ins are not complete then.
1343     msfpt->ins_req(msfpt->mach_constant_base_node_input(), C->mach_constant_base_node());
1344     if (msfpt->jvms() &&
1345         msfpt->mach_constant_base_node_input() <= msfpt->jvms()->debug_start() + msfpt->_jvmadj) {
1346       // We added an edge before jvms, so we must adapt the position of the ins.
1347       msfpt->jvms()->adapt_position(+1);
1348     }
1349   }
1350 
1351   // Registers killed by the call are set in the local scheduling pass
1352   // of Global Code Motion.
1353   return msfpt;
1354 }
1355 
1356 //---------------------------match_tree----------------------------------------
1357 // Match a Ideal Node DAG - turn it into a tree; Label & Reduce.  Used as part
1358 // of the whole-sale conversion from Ideal to Mach Nodes.  Also used for
1359 // making GotoNodes while building the CFG and in init_spill_mask() to identify
1360 // a Load's result RegMask for memoization in idealreg2regmask[]
1361 MachNode *Matcher::match_tree( const Node *n ) {
1362   assert( n->Opcode() != Op_Phi, "cannot match" );
1363   assert( !n->is_block_start(), "cannot match" );
1364   // Set the mark for all locally allocated State objects.
1365   // When this call returns, the _states_arena arena will be reset
1366   // freeing all State objects.
1367   ResourceMark rm( &_states_arena );
1368 
1369   LabelRootDepth = 0;
1370 
1371   // StoreNodes require their Memory input to match any LoadNodes
1372   Node *mem = n->is_Store() ? n->in(MemNode::Memory) : (Node*)1 ;
1373 #ifdef ASSERT
1374   Node* save_mem_node = _mem_node;
1375   _mem_node = n->is_Store() ? (Node*)n : NULL;
1376 #endif
1377   // State object for root node of match tree
1378   // Allocate it on _states_arena - stack allocation can cause stack overflow.
1379   State *s = new (&_states_arena) State;
1380   s->_kids[0] = NULL;
1381   s->_kids[1] = NULL;
1382   s->_leaf = (Node*)n;
1383   // Label the input tree, allocating labels from top-level arena
1384   Label_Root( n, s, n->in(0), mem );
1385   if (C->failing())  return NULL;
1386 
1387   // The minimum cost match for the whole tree is found at the root State
1388   uint mincost = max_juint;
1389   uint cost = max_juint;
1390   uint i;
1391   for( i = 0; i < NUM_OPERANDS; i++ ) {
1392     if( s->valid(i) &&                // valid entry and
1393         s->_cost[i] < cost &&         // low cost and
1394         s->_rule[i] >= NUM_OPERANDS ) // not an operand
1395       cost = s->_cost[mincost=i];
1396   }
1397   if (mincost == max_juint) {
1398 #ifndef PRODUCT
1399     tty->print("No matching rule for:");
1400     s->dump();
1401 #endif
1402     Matcher::soft_match_failure();
1403     return NULL;
1404   }
1405   // Reduce input tree based upon the state labels to machine Nodes
1406   MachNode *m = ReduceInst( s, s->_rule[mincost], mem );
1407 #ifdef ASSERT
1408   _old2new_map.map(n->_idx, m);
1409   _new2old_map.map(m->_idx, (Node*)n);
1410 #endif
1411 
1412   // Add any Matcher-ignored edges
1413   uint cnt = n->req();
1414   uint start = 1;
1415   if( mem != (Node*)1 ) start = MemNode::Memory+1;
1416   if( n->is_AddP() ) {
1417     assert( mem == (Node*)1, "" );
1418     start = AddPNode::Base+1;
1419   }
1420   for( i = start; i < cnt; i++ ) {
1421     if( !n->match_edge(i) ) {
1422       if( i < m->req() )
1423         m->ins_req( i, n->in(i) );
1424       else
1425         m->add_req( n->in(i) );
1426     }
1427   }
1428 
1429   debug_only( _mem_node = save_mem_node; )
1430   return m;
1431 }
1432 
1433 
1434 //------------------------------match_into_reg---------------------------------
1435 // Choose to either match this Node in a register or part of the current
1436 // match tree.  Return true for requiring a register and false for matching
1437 // as part of the current match tree.
1438 static bool match_into_reg( const Node *n, Node *m, Node *control, int i, bool shared ) {
1439 
1440   const Type *t = m->bottom_type();
1441 
1442   if (t->singleton()) {
1443     // Never force constants into registers.  Allow them to match as
1444     // constants or registers.  Copies of the same value will share
1445     // the same register.  See find_shared_node.
1446     return false;
1447   } else {                      // Not a constant
1448     // Stop recursion if they have different Controls.
1449     Node* m_control = m->in(0);
1450     // Control of load's memory can post-dominates load's control.
1451     // So use it since load can't float above its memory.
1452     Node* mem_control = (m->is_Load()) ? m->in(MemNode::Memory)->in(0) : NULL;
1453     if (control && m_control && control != m_control && control != mem_control) {
1454 
1455       // Actually, we can live with the most conservative control we
1456       // find, if it post-dominates the others.  This allows us to
1457       // pick up load/op/store trees where the load can float a little
1458       // above the store.
1459       Node *x = control;
1460       const uint max_scan = 6;  // Arbitrary scan cutoff
1461       uint j;
1462       for (j=0; j<max_scan; j++) {
1463         if (x->is_Region())     // Bail out at merge points
1464           return true;
1465         x = x->in(0);
1466         if (x == m_control)     // Does 'control' post-dominate
1467           break;                // m->in(0)?  If so, we can use it
1468         if (x == mem_control)   // Does 'control' post-dominate
1469           break;                // mem_control?  If so, we can use it
1470       }
1471       if (j == max_scan)        // No post-domination before scan end?
1472         return true;            // Then break the match tree up
1473     }
1474     if ((m->is_DecodeN() && Matcher::narrow_oop_use_complex_address()) ||
1475         (m->is_DecodeNKlass() && Matcher::narrow_klass_use_complex_address())) {
1476       // These are commonly used in address expressions and can
1477       // efficiently fold into them on X64 in some cases.
1478       return false;
1479     }
1480   }
1481 
1482   // Not forceable cloning.  If shared, put it into a register.
1483   return shared;
1484 }
1485 
1486 
1487 //------------------------------Instruction Selection--------------------------
1488 // Label method walks a "tree" of nodes, using the ADLC generated DFA to match
1489 // ideal nodes to machine instructions.  Trees are delimited by shared Nodes,
1490 // things the Matcher does not match (e.g., Memory), and things with different
1491 // Controls (hence forced into different blocks).  We pass in the Control
1492 // selected for this entire State tree.
1493 
1494 // The Matcher works on Trees, but an Intel add-to-memory requires a DAG: the
1495 // Store and the Load must have identical Memories (as well as identical
1496 // pointers).  Since the Matcher does not have anything for Memory (and
1497 // does not handle DAGs), I have to match the Memory input myself.  If the
1498 // Tree root is a Store, I require all Loads to have the identical memory.
1499 Node *Matcher::Label_Root( const Node *n, State *svec, Node *control, const Node *mem){
1500   // Since Label_Root is a recursive function, its possible that we might run
1501   // out of stack space.  See bugs 6272980 & 6227033 for more info.
1502   LabelRootDepth++;
1503   if (LabelRootDepth > MaxLabelRootDepth) {
1504     C->record_method_not_compilable_all_tiers("Out of stack space, increase MaxLabelRootDepth");
1505     return NULL;
1506   }
1507   uint care = 0;                // Edges matcher cares about
1508   uint cnt = n->req();
1509   uint i = 0;
1510 
1511   // Examine children for memory state
1512   // Can only subsume a child into your match-tree if that child's memory state
1513   // is not modified along the path to another input.
1514   // It is unsafe even if the other inputs are separate roots.
1515   Node *input_mem = NULL;
1516   for( i = 1; i < cnt; i++ ) {
1517     if( !n->match_edge(i) ) continue;
1518     Node *m = n->in(i);         // Get ith input
1519     assert( m, "expect non-null children" );
1520     if( m->is_Load() ) {
1521       if( input_mem == NULL ) {
1522         input_mem = m->in(MemNode::Memory);
1523       } else if( input_mem != m->in(MemNode::Memory) ) {
1524         input_mem = NodeSentinel;
1525       }
1526     }
1527   }
1528 
1529   for( i = 1; i < cnt; i++ ){// For my children
1530     if( !n->match_edge(i) ) continue;
1531     Node *m = n->in(i);         // Get ith input
1532     // Allocate states out of a private arena
1533     State *s = new (&_states_arena) State;
1534     svec->_kids[care++] = s;
1535     assert( care <= 2, "binary only for now" );
1536 
1537     // Recursively label the State tree.
1538     s->_kids[0] = NULL;
1539     s->_kids[1] = NULL;
1540     s->_leaf = m;
1541 
1542     // Check for leaves of the State Tree; things that cannot be a part of
1543     // the current tree.  If it finds any, that value is matched as a
1544     // register operand.  If not, then the normal matching is used.
1545     if( match_into_reg(n, m, control, i, is_shared(m)) ||
1546         //
1547         // Stop recursion if this is LoadNode and the root of this tree is a
1548         // StoreNode and the load & store have different memories.
1549         ((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem) ||
1550         // Can NOT include the match of a subtree when its memory state
1551         // is used by any of the other subtrees
1552         (input_mem == NodeSentinel) ) {
1553 #ifndef PRODUCT
1554       // Print when we exclude matching due to different memory states at input-loads
1555       if( PrintOpto && (Verbose && WizardMode) && (input_mem == NodeSentinel)
1556         && !((mem!=(Node*)1) && m->is_Load() && m->in(MemNode::Memory) != mem) ) {
1557         tty->print_cr("invalid input_mem");
1558       }
1559 #endif
1560       // Switch to a register-only opcode; this value must be in a register
1561       // and cannot be subsumed as part of a larger instruction.
1562       s->DFA( m->ideal_reg(), m );
1563 
1564     } else {
1565       // If match tree has no control and we do, adopt it for entire tree
1566       if( control == NULL && m->in(0) != NULL && m->req() > 1 )
1567         control = m->in(0);         // Pick up control
1568       // Else match as a normal part of the match tree.
1569       control = Label_Root(m,s,control,mem);
1570       if (C->failing()) return NULL;
1571     }
1572   }
1573 
1574 
1575   // Call DFA to match this node, and return
1576   svec->DFA( n->Opcode(), n );
1577 
1578 #ifdef ASSERT
1579   uint x;
1580   for( x = 0; x < _LAST_MACH_OPER; x++ )
1581     if( svec->valid(x) )
1582       break;
1583 
1584   if (x >= _LAST_MACH_OPER) {
1585     n->dump();
1586     svec->dump();
1587     assert( false, "bad AD file" );
1588   }
1589 #endif
1590   return control;
1591 }
1592 
1593 
1594 // Con nodes reduced using the same rule can share their MachNode
1595 // which reduces the number of copies of a constant in the final
1596 // program.  The register allocator is free to split uses later to
1597 // split live ranges.
1598 MachNode* Matcher::find_shared_node(Node* leaf, uint rule) {
1599   if (!leaf->is_Con() && !leaf->is_DecodeNarrowPtr()) return NULL;
1600 
1601   // See if this Con has already been reduced using this rule.
1602   if (_shared_nodes.Size() <= leaf->_idx) return NULL;
1603   MachNode* last = (MachNode*)_shared_nodes.at(leaf->_idx);
1604   if (last != NULL && rule == last->rule()) {
1605     // Don't expect control change for DecodeN
1606     if (leaf->is_DecodeNarrowPtr())
1607       return last;
1608     // Get the new space root.
1609     Node* xroot = new_node(C->root());
1610     if (xroot == NULL) {
1611       // This shouldn't happen give the order of matching.
1612       return NULL;
1613     }
1614 
1615     // Shared constants need to have their control be root so they
1616     // can be scheduled properly.
1617     Node* control = last->in(0);
1618     if (control != xroot) {
1619       if (control == NULL || control == C->root()) {
1620         last->set_req(0, xroot);
1621       } else {
1622         assert(false, "unexpected control");
1623         return NULL;
1624       }
1625     }
1626     return last;
1627   }
1628   return NULL;
1629 }
1630 
1631 
1632 //------------------------------ReduceInst-------------------------------------
1633 // Reduce a State tree (with given Control) into a tree of MachNodes.
1634 // This routine (and it's cohort ReduceOper) convert Ideal Nodes into
1635 // complicated machine Nodes.  Each MachNode covers some tree of Ideal Nodes.
1636 // Each MachNode has a number of complicated MachOper operands; each
1637 // MachOper also covers a further tree of Ideal Nodes.
1638 
1639 // The root of the Ideal match tree is always an instruction, so we enter
1640 // the recursion here.  After building the MachNode, we need to recurse
1641 // the tree checking for these cases:
1642 // (1) Child is an instruction -
1643 //     Build the instruction (recursively), add it as an edge.
1644 //     Build a simple operand (register) to hold the result of the instruction.
1645 // (2) Child is an interior part of an instruction -
1646 //     Skip over it (do nothing)
1647 // (3) Child is the start of a operand -
1648 //     Build the operand, place it inside the instruction
1649 //     Call ReduceOper.
1650 MachNode *Matcher::ReduceInst( State *s, int rule, Node *&mem ) {
1651   assert( rule >= NUM_OPERANDS, "called with operand rule" );
1652 
1653   MachNode* shared_node = find_shared_node(s->_leaf, rule);
1654   if (shared_node != NULL) {
1655     return shared_node;
1656   }
1657 
1658   // Build the object to represent this state & prepare for recursive calls
1659   MachNode *mach = s->MachNodeGenerator( rule, C );
1660   guarantee(mach != NULL, "Missing MachNode");
1661   mach->_opnds[0] = s->MachOperGenerator( _reduceOp[rule], C );
1662   assert( mach->_opnds[0] != NULL, "Missing result operand" );
1663   Node *leaf = s->_leaf;
1664   // Check for instruction or instruction chain rule
1665   if( rule >= _END_INST_CHAIN_RULE || rule < _BEGIN_INST_CHAIN_RULE ) {
1666     assert(C->node_arena()->contains(s->_leaf) || !has_new_node(s->_leaf),
1667            "duplicating node that's already been matched");
1668     // Instruction
1669     mach->add_req( leaf->in(0) ); // Set initial control
1670     // Reduce interior of complex instruction
1671     ReduceInst_Interior( s, rule, mem, mach, 1 );
1672   } else {
1673     // Instruction chain rules are data-dependent on their inputs
1674     mach->add_req(0);             // Set initial control to none
1675     ReduceInst_Chain_Rule( s, rule, mem, mach );
1676   }
1677 
1678   // If a Memory was used, insert a Memory edge
1679   if( mem != (Node*)1 ) {
1680     mach->ins_req(MemNode::Memory,mem);
1681 #ifdef ASSERT
1682     // Verify adr type after matching memory operation
1683     const MachOper* oper = mach->memory_operand();
1684     if (oper != NULL && oper != (MachOper*)-1) {
1685       // It has a unique memory operand.  Find corresponding ideal mem node.
1686       Node* m = NULL;
1687       if (leaf->is_Mem()) {
1688         m = leaf;
1689       } else {
1690         m = _mem_node;
1691         assert(m != NULL && m->is_Mem(), "expecting memory node");
1692       }
1693       const Type* mach_at = mach->adr_type();
1694       // DecodeN node consumed by an address may have different type
1695       // then its input. Don't compare types for such case.
1696       if (m->adr_type() != mach_at &&
1697           (m->in(MemNode::Address)->is_DecodeNarrowPtr() ||
1698            m->in(MemNode::Address)->is_AddP() &&
1699            m->in(MemNode::Address)->in(AddPNode::Address)->is_DecodeNarrowPtr() ||
1700            m->in(MemNode::Address)->is_AddP() &&
1701            m->in(MemNode::Address)->in(AddPNode::Address)->is_AddP() &&
1702            m->in(MemNode::Address)->in(AddPNode::Address)->in(AddPNode::Address)->is_DecodeNarrowPtr())) {
1703         mach_at = m->adr_type();
1704       }
1705       if (m->adr_type() != mach_at) {
1706         m->dump();
1707         tty->print_cr("mach:");
1708         mach->dump(1);
1709       }
1710       assert(m->adr_type() == mach_at, "matcher should not change adr type");
1711     }
1712 #endif
1713   }
1714 
1715   // If the _leaf is an AddP, insert the base edge
1716   if (leaf->is_AddP()) {
1717     mach->ins_req(AddPNode::Base,leaf->in(AddPNode::Base));
1718   }
1719 
1720   uint number_of_projections_prior = number_of_projections();
1721 
1722   // Perform any 1-to-many expansions required
1723   MachNode *ex = mach->Expand(s, _projection_list, mem);
1724   if (ex != mach) {
1725     assert(ex->ideal_reg() == mach->ideal_reg(), "ideal types should match");
1726     if( ex->in(1)->is_Con() )
1727       ex->in(1)->set_req(0, C->root());
1728     // Remove old node from the graph
1729     for( uint i=0; i<mach->req(); i++ ) {
1730       mach->set_req(i,NULL);
1731     }
1732 #ifdef ASSERT
1733     _new2old_map.map(ex->_idx, s->_leaf);
1734 #endif
1735   }
1736 
1737   // PhaseChaitin::fixup_spills will sometimes generate spill code
1738   // via the matcher.  By the time, nodes have been wired into the CFG,
1739   // and any further nodes generated by expand rules will be left hanging
1740   // in space, and will not get emitted as output code.  Catch this.
1741   // Also, catch any new register allocation constraints ("projections")
1742   // generated belatedly during spill code generation.
1743   if (_allocation_started) {
1744     guarantee(ex == mach, "no expand rules during spill generation");
1745     guarantee(number_of_projections_prior == number_of_projections(), "no allocation during spill generation");
1746   }
1747 
1748   if (leaf->is_Con() || leaf->is_DecodeNarrowPtr()) {
1749     // Record the con for sharing
1750     _shared_nodes.map(leaf->_idx, ex);
1751   }
1752 
1753   return ex;
1754 }
1755 
1756 void Matcher::ReduceInst_Chain_Rule( State *s, int rule, Node *&mem, MachNode *mach ) {
1757   // 'op' is what I am expecting to receive
1758   int op = _leftOp[rule];
1759   // Operand type to catch childs result
1760   // This is what my child will give me.
1761   int opnd_class_instance = s->_rule[op];
1762   // Choose between operand class or not.
1763   // This is what I will receive.
1764   int catch_op = (FIRST_OPERAND_CLASS <= op && op < NUM_OPERANDS) ? opnd_class_instance : op;
1765   // New rule for child.  Chase operand classes to get the actual rule.
1766   int newrule = s->_rule[catch_op];
1767 
1768   if( newrule < NUM_OPERANDS ) {
1769     // Chain from operand or operand class, may be output of shared node
1770     assert( 0 <= opnd_class_instance && opnd_class_instance < NUM_OPERANDS,
1771             "Bad AD file: Instruction chain rule must chain from operand");
1772     // Insert operand into array of operands for this instruction
1773     mach->_opnds[1] = s->MachOperGenerator( opnd_class_instance, C );
1774 
1775     ReduceOper( s, newrule, mem, mach );
1776   } else {
1777     // Chain from the result of an instruction
1778     assert( newrule >= _LAST_MACH_OPER, "Do NOT chain from internal operand");
1779     mach->_opnds[1] = s->MachOperGenerator( _reduceOp[catch_op], C );
1780     Node *mem1 = (Node*)1;
1781     debug_only(Node *save_mem_node = _mem_node;)
1782     mach->add_req( ReduceInst(s, newrule, mem1) );
1783     debug_only(_mem_node = save_mem_node;)
1784   }
1785   return;
1786 }
1787 
1788 
1789 uint Matcher::ReduceInst_Interior( State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds ) {
1790   if( s->_leaf->is_Load() ) {
1791     Node *mem2 = s->_leaf->in(MemNode::Memory);
1792     assert( mem == (Node*)1 || mem == mem2, "multiple Memories being matched at once?" );
1793     debug_only( if( mem == (Node*)1 ) _mem_node = s->_leaf;)
1794     mem = mem2;
1795   }
1796   if( s->_leaf->in(0) != NULL && s->_leaf->req() > 1) {
1797     if( mach->in(0) == NULL )
1798       mach->set_req(0, s->_leaf->in(0));
1799   }
1800 
1801   // Now recursively walk the state tree & add operand list.
1802   for( uint i=0; i<2; i++ ) {   // binary tree
1803     State *newstate = s->_kids[i];
1804     if( newstate == NULL ) break;      // Might only have 1 child
1805     // 'op' is what I am expecting to receive
1806     int op;
1807     if( i == 0 ) {
1808       op = _leftOp[rule];
1809     } else {
1810       op = _rightOp[rule];
1811     }
1812     // Operand type to catch childs result
1813     // This is what my child will give me.
1814     int opnd_class_instance = newstate->_rule[op];
1815     // Choose between operand class or not.
1816     // This is what I will receive.
1817     int catch_op = (op >= FIRST_OPERAND_CLASS && op < NUM_OPERANDS) ? opnd_class_instance : op;
1818     // New rule for child.  Chase operand classes to get the actual rule.
1819     int newrule = newstate->_rule[catch_op];
1820 
1821     if( newrule < NUM_OPERANDS ) { // Operand/operandClass or internalOp/instruction?
1822       // Operand/operandClass
1823       // Insert operand into array of operands for this instruction
1824       mach->_opnds[num_opnds++] = newstate->MachOperGenerator( opnd_class_instance, C );
1825       ReduceOper( newstate, newrule, mem, mach );
1826 
1827     } else {                    // Child is internal operand or new instruction
1828       if( newrule < _LAST_MACH_OPER ) { // internal operand or instruction?
1829         // internal operand --> call ReduceInst_Interior
1830         // Interior of complex instruction.  Do nothing but recurse.
1831         num_opnds = ReduceInst_Interior( newstate, newrule, mem, mach, num_opnds );
1832       } else {
1833         // instruction --> call build operand(  ) to catch result
1834         //             --> ReduceInst( newrule )
1835         mach->_opnds[num_opnds++] = s->MachOperGenerator( _reduceOp[catch_op], C );
1836         Node *mem1 = (Node*)1;
1837         debug_only(Node *save_mem_node = _mem_node;)
1838         mach->add_req( ReduceInst( newstate, newrule, mem1 ) );
1839         debug_only(_mem_node = save_mem_node;)
1840       }
1841     }
1842     assert( mach->_opnds[num_opnds-1], "" );
1843   }
1844   return num_opnds;
1845 }
1846 
1847 // This routine walks the interior of possible complex operands.
1848 // At each point we check our children in the match tree:
1849 // (1) No children -
1850 //     We are a leaf; add _leaf field as an input to the MachNode
1851 // (2) Child is an internal operand -
1852 //     Skip over it ( do nothing )
1853 // (3) Child is an instruction -
1854 //     Call ReduceInst recursively and
1855 //     and instruction as an input to the MachNode
1856 void Matcher::ReduceOper( State *s, int rule, Node *&mem, MachNode *mach ) {
1857   assert( rule < _LAST_MACH_OPER, "called with operand rule" );
1858   State *kid = s->_kids[0];
1859   assert( kid == NULL || s->_leaf->in(0) == NULL, "internal operands have no control" );
1860 
1861   // Leaf?  And not subsumed?
1862   if( kid == NULL && !_swallowed[rule] ) {
1863     mach->add_req( s->_leaf );  // Add leaf pointer
1864     return;                     // Bail out
1865   }
1866 
1867   if( s->_leaf->is_Load() ) {
1868     assert( mem == (Node*)1, "multiple Memories being matched at once?" );
1869     mem = s->_leaf->in(MemNode::Memory);
1870     debug_only(_mem_node = s->_leaf;)
1871   }
1872   if( s->_leaf->in(0) && s->_leaf->req() > 1) {
1873     if( !mach->in(0) )
1874       mach->set_req(0,s->_leaf->in(0));
1875     else {
1876       assert( s->_leaf->in(0) == mach->in(0), "same instruction, differing controls?" );
1877     }
1878   }
1879 
1880   for( uint i=0; kid != NULL && i<2; kid = s->_kids[1], i++ ) {   // binary tree
1881     int newrule;
1882     if( i == 0)
1883       newrule = kid->_rule[_leftOp[rule]];
1884     else
1885       newrule = kid->_rule[_rightOp[rule]];
1886 
1887     if( newrule < _LAST_MACH_OPER ) { // Operand or instruction?
1888       // Internal operand; recurse but do nothing else
1889       ReduceOper( kid, newrule, mem, mach );
1890 
1891     } else {                    // Child is a new instruction
1892       // Reduce the instruction, and add a direct pointer from this
1893       // machine instruction to the newly reduced one.
1894       Node *mem1 = (Node*)1;
1895       debug_only(Node *save_mem_node = _mem_node;)
1896       mach->add_req( ReduceInst( kid, newrule, mem1 ) );
1897       debug_only(_mem_node = save_mem_node;)
1898     }
1899   }
1900 }
1901 
1902 
1903 // -------------------------------------------------------------------------
1904 // Java-Java calling convention
1905 // (what you use when Java calls Java)
1906 
1907 //------------------------------find_receiver----------------------------------
1908 // For a given signature, return the OptoReg for parameter 0.
1909 OptoReg::Name Matcher::find_receiver( bool is_outgoing ) {
1910   VMRegPair regs;
1911   BasicType sig_bt = T_OBJECT;
1912   calling_convention(&sig_bt, &regs, 1, is_outgoing);
1913   // Return argument 0 register.  In the LP64 build pointers
1914   // take 2 registers, but the VM wants only the 'main' name.
1915   return OptoReg::as_OptoReg(regs.first());
1916 }
1917 
1918 // This function identifies sub-graphs in which a 'load' node is
1919 // input to two different nodes, and such that it can be matched
1920 // with BMI instructions like blsi, blsr, etc.
1921 // Example : for b = -a[i] & a[i] can be matched to blsi r32, m32.
1922 // The graph is (AndL (SubL Con0 LoadL*) LoadL*), where LoadL*
1923 // refers to the same node.
1924 #ifdef X86
1925 // Match the generic fused operations pattern (op1 (op2 Con{ConType} mop) mop)
1926 // This is a temporary solution until we make DAGs expressible in ADL.
1927 template<typename ConType>
1928 class FusedPatternMatcher {
1929   Node* _op1_node;
1930   Node* _mop_node;
1931   int _con_op;
1932 
1933   static int match_next(Node* n, int next_op, int next_op_idx) {
1934     if (n->in(1) == NULL || n->in(2) == NULL) {
1935       return -1;
1936     }
1937 
1938     if (next_op_idx == -1) { // n is commutative, try rotations
1939       if (n->in(1)->Opcode() == next_op) {
1940         return 1;
1941       } else if (n->in(2)->Opcode() == next_op) {
1942         return 2;
1943       }
1944     } else {
1945       assert(next_op_idx > 0 && next_op_idx <= 2, "Bad argument index");
1946       if (n->in(next_op_idx)->Opcode() == next_op) {
1947         return next_op_idx;
1948       }
1949     }
1950     return -1;
1951   }
1952 public:
1953   FusedPatternMatcher(Node* op1_node, Node *mop_node, int con_op) :
1954     _op1_node(op1_node), _mop_node(mop_node), _con_op(con_op) { }
1955 
1956   bool match(int op1, int op1_op2_idx,  // op1 and the index of the op1->op2 edge, -1 if op1 is commutative
1957              int op2, int op2_con_idx,  // op2 and the index of the op2->con edge, -1 if op2 is commutative
1958              typename ConType::NativeType con_value) {
1959     if (_op1_node->Opcode() != op1) {
1960       return false;
1961     }
1962     if (_mop_node->outcnt() > 2) {
1963       return false;
1964     }
1965     op1_op2_idx = match_next(_op1_node, op2, op1_op2_idx);
1966     if (op1_op2_idx == -1) {
1967       return false;
1968     }
1969     // Memory operation must be the other edge
1970     int op1_mop_idx = (op1_op2_idx & 1) + 1;
1971 
1972     // Check that the mop node is really what we want
1973     if (_op1_node->in(op1_mop_idx) == _mop_node) {
1974       Node *op2_node = _op1_node->in(op1_op2_idx);
1975       if (op2_node->outcnt() > 1) {
1976         return false;
1977       }
1978       assert(op2_node->Opcode() == op2, "Should be");
1979       op2_con_idx = match_next(op2_node, _con_op, op2_con_idx);
1980       if (op2_con_idx == -1) {
1981         return false;
1982       }
1983       // Memory operation must be the other edge
1984       int op2_mop_idx = (op2_con_idx & 1) + 1;
1985       // Check that the memory operation is the same node
1986       if (op2_node->in(op2_mop_idx) == _mop_node) {
1987         // Now check the constant
1988         const Type* con_type = op2_node->in(op2_con_idx)->bottom_type();
1989         if (con_type != Type::TOP && ConType::as_self(con_type)->get_con() == con_value) {
1990           return true;
1991         }
1992       }
1993     }
1994     return false;
1995   }
1996 };
1997 
1998 
1999 bool Matcher::is_bmi_pattern(Node *n, Node *m) {
2000   if (n != NULL && m != NULL) {
2001     if (m->Opcode() == Op_LoadI) {
2002       FusedPatternMatcher<TypeInt> bmii(n, m, Op_ConI);
2003       return bmii.match(Op_AndI, -1, Op_SubI,  1,  0)  ||
2004              bmii.match(Op_AndI, -1, Op_AddI, -1, -1)  ||
2005              bmii.match(Op_XorI, -1, Op_AddI, -1, -1);
2006     } else if (m->Opcode() == Op_LoadL) {
2007       FusedPatternMatcher<TypeLong> bmil(n, m, Op_ConL);
2008       return bmil.match(Op_AndL, -1, Op_SubL,  1,  0) ||
2009              bmil.match(Op_AndL, -1, Op_AddL, -1, -1) ||
2010              bmil.match(Op_XorL, -1, Op_AddL, -1, -1);
2011     }
2012   }
2013   return false;
2014 }
2015 #endif // X86
2016 
2017 // A method-klass-holder may be passed in the inline_cache_reg
2018 // and then expanded into the inline_cache_reg and a method_oop register
2019 //   defined in ad_<arch>.cpp
2020 
2021 
2022 //------------------------------find_shared------------------------------------
2023 // Set bits if Node is shared or otherwise a root
2024 void Matcher::find_shared( Node *n ) {
2025   // Allocate stack of size C->live_nodes() * 2 to avoid frequent realloc
2026   MStack mstack(C->live_nodes() * 2);
2027   // Mark nodes as address_visited if they are inputs to an address expression
2028   VectorSet address_visited(Thread::current()->resource_area());
2029   mstack.push(n, Visit);     // Don't need to pre-visit root node
2030   while (mstack.is_nonempty()) {
2031     n = mstack.node();       // Leave node on stack
2032     Node_State nstate = mstack.state();
2033     uint nop = n->Opcode();
2034     if (nstate == Pre_Visit) {
2035       if (address_visited.test(n->_idx)) { // Visited in address already?
2036         // Flag as visited and shared now.
2037         set_visited(n);
2038       }
2039       if (is_visited(n)) {   // Visited already?
2040         // Node is shared and has no reason to clone.  Flag it as shared.
2041         // This causes it to match into a register for the sharing.
2042         set_shared(n);       // Flag as shared and
2043         mstack.pop();        // remove node from stack
2044         continue;
2045       }
2046       nstate = Visit; // Not already visited; so visit now
2047     }
2048     if (nstate == Visit) {
2049       mstack.set_state(Post_Visit);
2050       set_visited(n);   // Flag as visited now
2051       bool mem_op = false;
2052 
2053       switch( nop ) {  // Handle some opcodes special
2054       case Op_Phi:             // Treat Phis as shared roots
2055       case Op_Parm:
2056       case Op_Proj:            // All handled specially during matching
2057       case Op_SafePointScalarObject:
2058         set_shared(n);
2059         set_dontcare(n);
2060         break;
2061       case Op_If:
2062       case Op_CountedLoopEnd:
2063         mstack.set_state(Alt_Post_Visit); // Alternative way
2064         // Convert (If (Bool (CmpX A B))) into (If (Bool) (CmpX A B)).  Helps
2065         // with matching cmp/branch in 1 instruction.  The Matcher needs the
2066         // Bool and CmpX side-by-side, because it can only get at constants
2067         // that are at the leaves of Match trees, and the Bool's condition acts
2068         // as a constant here.
2069         mstack.push(n->in(1), Visit);         // Clone the Bool
2070         mstack.push(n->in(0), Pre_Visit);     // Visit control input
2071         continue; // while (mstack.is_nonempty())
2072       case Op_ConvI2D:         // These forms efficiently match with a prior
2073       case Op_ConvI2F:         //   Load but not a following Store
2074         if( n->in(1)->is_Load() &&        // Prior load
2075             n->outcnt() == 1 &&           // Not already shared
2076             n->unique_out()->is_Store() ) // Following store
2077           set_shared(n);       // Force it to be a root
2078         break;
2079       case Op_ReverseBytesI:
2080       case Op_ReverseBytesL:
2081         if( n->in(1)->is_Load() &&        // Prior load
2082             n->outcnt() == 1 )            // Not already shared
2083           set_shared(n);                  // Force it to be a root
2084         break;
2085       case Op_BoxLock:         // Cant match until we get stack-regs in ADLC
2086       case Op_IfFalse:
2087       case Op_IfTrue:
2088       case Op_MachProj:
2089       case Op_MergeMem:
2090       case Op_Catch:
2091       case Op_CatchProj:
2092       case Op_CProj:
2093       case Op_JumpProj:
2094       case Op_JProj:
2095       case Op_NeverBranch:
2096         set_dontcare(n);
2097         break;
2098       case Op_Jump:
2099         mstack.push(n->in(1), Pre_Visit);     // Switch Value (could be shared)
2100         mstack.push(n->in(0), Pre_Visit);     // Visit Control input
2101         continue;                             // while (mstack.is_nonempty())
2102       case Op_StrComp:
2103       case Op_StrEquals:
2104       case Op_StrIndexOf:
2105       case Op_AryEq:
2106       case Op_EncodeISOArray:
2107         set_shared(n); // Force result into register (it will be anyways)
2108         break;
2109       case Op_ConP: {  // Convert pointers above the centerline to NUL
2110         TypeNode *tn = n->as_Type(); // Constants derive from type nodes
2111         const TypePtr* tp = tn->type()->is_ptr();
2112         if (tp->_ptr == TypePtr::AnyNull) {
2113           tn->set_type(TypePtr::NULL_PTR);
2114         }
2115         break;
2116       }
2117       case Op_ConN: {  // Convert narrow pointers above the centerline to NUL
2118         TypeNode *tn = n->as_Type(); // Constants derive from type nodes
2119         const TypePtr* tp = tn->type()->make_ptr();
2120         if (tp && tp->_ptr == TypePtr::AnyNull) {
2121           tn->set_type(TypeNarrowOop::NULL_PTR);
2122         }
2123         break;
2124       }
2125       case Op_Binary:         // These are introduced in the Post_Visit state.
2126         ShouldNotReachHere();
2127         break;
2128       case Op_ClearArray:
2129       case Op_SafePoint:
2130         mem_op = true;
2131         break;
2132       default:
2133         if( n->is_Store() ) {
2134           // Do match stores, despite no ideal reg
2135           mem_op = true;
2136           break;
2137         }
2138         if( n->is_Mem() ) { // Loads and LoadStores
2139           mem_op = true;
2140           // Loads must be root of match tree due to prior load conflict
2141           if( C->subsume_loads() == false )
2142             set_shared(n);
2143         }
2144         // Fall into default case
2145         if( !n->ideal_reg() )
2146           set_dontcare(n);  // Unmatchable Nodes
2147       } // end_switch
2148 
2149       for(int i = n->req() - 1; i >= 0; --i) { // For my children
2150         Node *m = n->in(i); // Get ith input
2151         if (m == NULL) continue;  // Ignore NULLs
2152         uint mop = m->Opcode();
2153 
2154         // Must clone all producers of flags, or we will not match correctly.
2155         // Suppose a compare setting int-flags is shared (e.g., a switch-tree)
2156         // then it will match into an ideal Op_RegFlags.  Alas, the fp-flags
2157         // are also there, so we may match a float-branch to int-flags and
2158         // expect the allocator to haul the flags from the int-side to the
2159         // fp-side.  No can do.
2160         if( _must_clone[mop] ) {
2161           mstack.push(m, Visit);
2162           continue; // for(int i = ...)
2163         }
2164 
2165         if( mop == Op_AddP && m->in(AddPNode::Base)->is_DecodeNarrowPtr()) {
2166           // Bases used in addresses must be shared but since
2167           // they are shared through a DecodeN they may appear
2168           // to have a single use so force sharing here.
2169           set_shared(m->in(AddPNode::Base)->in(1));
2170         }
2171 
2172         // if 'n' and 'm' are part of a graph for BMI instruction, clone this node.
2173 #ifdef X86
2174         if (UseBMI1Instructions && is_bmi_pattern(n, m)) {
2175           mstack.push(m, Visit);
2176           continue;
2177         }
2178 #endif
2179 
2180         // Clone addressing expressions as they are "free" in memory access instructions
2181         if( mem_op && i == MemNode::Address && mop == Op_AddP ) {
2182           // Some inputs for address expression are not put on stack
2183           // to avoid marking them as shared and forcing them into register
2184           // if they are used only in address expressions.
2185           // But they should be marked as shared if there are other uses
2186           // besides address expressions.
2187 
2188           Node *off = m->in(AddPNode::Offset);
2189           if( off->is_Con() &&
2190               // When there are other uses besides address expressions
2191               // put it on stack and mark as shared.
2192               !is_visited(m) ) {
2193             address_visited.test_set(m->_idx); // Flag as address_visited
2194             Node *adr = m->in(AddPNode::Address);
2195 
2196             // Intel, ARM and friends can handle 2 adds in addressing mode
2197             if( clone_shift_expressions && adr->is_AddP() &&
2198                 // AtomicAdd is not an addressing expression.
2199                 // Cheap to find it by looking for screwy base.
2200                 !adr->in(AddPNode::Base)->is_top() &&
2201                 // Are there other uses besides address expressions?
2202                 !is_visited(adr) ) {
2203               address_visited.set(adr->_idx); // Flag as address_visited
2204               Node *shift = adr->in(AddPNode::Offset);
2205               // Check for shift by small constant as well
2206               if( shift->Opcode() == Op_LShiftX && shift->in(2)->is_Con() &&
2207                   shift->in(2)->get_int() <= 3 &&
2208                   // Are there other uses besides address expressions?
2209                   !is_visited(shift) ) {
2210                 address_visited.set(shift->_idx); // Flag as address_visited
2211                 mstack.push(shift->in(2), Visit);
2212                 Node *conv = shift->in(1);
2213 #ifdef _LP64
2214                 // Allow Matcher to match the rule which bypass
2215                 // ConvI2L operation for an array index on LP64
2216                 // if the index value is positive.
2217                 if( conv->Opcode() == Op_ConvI2L &&
2218                     conv->as_Type()->type()->is_long()->_lo >= 0 &&
2219                     // Are there other uses besides address expressions?
2220                     !is_visited(conv) ) {
2221                   address_visited.set(conv->_idx); // Flag as address_visited
2222                   mstack.push(conv->in(1), Pre_Visit);
2223                 } else
2224 #endif
2225                 mstack.push(conv, Pre_Visit);
2226               } else {
2227                 mstack.push(shift, Pre_Visit);
2228               }
2229               mstack.push(adr->in(AddPNode::Address), Pre_Visit);
2230               mstack.push(adr->in(AddPNode::Base), Pre_Visit);
2231             } else {  // Sparc, Alpha, PPC and friends
2232               mstack.push(adr, Pre_Visit);
2233             }
2234 
2235             // Clone X+offset as it also folds into most addressing expressions
2236             mstack.push(off, Visit);
2237             mstack.push(m->in(AddPNode::Base), Pre_Visit);
2238             continue; // for(int i = ...)
2239           } // if( off->is_Con() )
2240         }   // if( mem_op &&
2241         mstack.push(m, Pre_Visit);
2242       }     // for(int i = ...)
2243     }
2244     else if (nstate == Alt_Post_Visit) {
2245       mstack.pop(); // Remove node from stack
2246       // We cannot remove the Cmp input from the Bool here, as the Bool may be
2247       // shared and all users of the Bool need to move the Cmp in parallel.
2248       // This leaves both the Bool and the If pointing at the Cmp.  To
2249       // prevent the Matcher from trying to Match the Cmp along both paths
2250       // BoolNode::match_edge always returns a zero.
2251 
2252       // We reorder the Op_If in a pre-order manner, so we can visit without
2253       // accidentally sharing the Cmp (the Bool and the If make 2 users).
2254       n->add_req( n->in(1)->in(1) ); // Add the Cmp next to the Bool
2255     }
2256     else if (nstate == Post_Visit) {
2257       mstack.pop(); // Remove node from stack
2258 
2259       // Now hack a few special opcodes
2260       switch( n->Opcode() ) {       // Handle some opcodes special
2261       case Op_StorePConditional:
2262       case Op_StoreIConditional:
2263       case Op_StoreLConditional:
2264       case Op_CompareAndSwapI:
2265       case Op_CompareAndSwapL:
2266       case Op_CompareAndSwapP:
2267       case Op_CompareAndSwapN: {   // Convert trinary to binary-tree
2268         Node *newval = n->in(MemNode::ValueIn );
2269         Node *oldval  = n->in(LoadStoreConditionalNode::ExpectedIn);
2270         Node *pair = new (C) BinaryNode( oldval, newval );
2271         n->set_req(MemNode::ValueIn,pair);
2272         n->del_req(LoadStoreConditionalNode::ExpectedIn);
2273         break;
2274       }
2275       case Op_CMoveD:              // Convert trinary to binary-tree
2276       case Op_CMoveF:
2277       case Op_CMoveI:
2278       case Op_CMoveL:
2279       case Op_CMoveN:
2280       case Op_CMoveP: {
2281         // Restructure into a binary tree for Matching.  It's possible that
2282         // we could move this code up next to the graph reshaping for IfNodes
2283         // or vice-versa, but I do not want to debug this for Ladybird.
2284         // 10/2/2000 CNC.
2285         Node *pair1 = new (C) BinaryNode(n->in(1),n->in(1)->in(1));
2286         n->set_req(1,pair1);
2287         Node *pair2 = new (C) BinaryNode(n->in(2),n->in(3));
2288         n->set_req(2,pair2);
2289         n->del_req(3);
2290         break;
2291       }
2292       case Op_LoopLimit: {
2293         Node *pair1 = new (C) BinaryNode(n->in(1),n->in(2));
2294         n->set_req(1,pair1);
2295         n->set_req(2,n->in(3));
2296         n->del_req(3);
2297         break;
2298       }
2299       case Op_StrEquals: {
2300         Node *pair1 = new (C) BinaryNode(n->in(2),n->in(3));
2301         n->set_req(2,pair1);
2302         n->set_req(3,n->in(4));
2303         n->del_req(4);
2304         break;
2305       }
2306       case Op_StrComp:
2307       case Op_StrIndexOf: {
2308         Node *pair1 = new (C) BinaryNode(n->in(2),n->in(3));
2309         n->set_req(2,pair1);
2310         Node *pair2 = new (C) BinaryNode(n->in(4),n->in(5));
2311         n->set_req(3,pair2);
2312         n->del_req(5);
2313         n->del_req(4);
2314         break;
2315       }
2316       case Op_EncodeISOArray: {
2317         // Restructure into a binary tree for Matching.
2318         Node* pair = new (C) BinaryNode(n->in(3), n->in(4));
2319         n->set_req(3, pair);
2320         n->del_req(4);
2321         break;
2322       }
2323       default:
2324         break;
2325       }
2326     }
2327     else {
2328       ShouldNotReachHere();
2329     }
2330   } // end of while (mstack.is_nonempty())
2331 }
2332 
2333 #ifdef ASSERT
2334 // machine-independent root to machine-dependent root
2335 void Matcher::dump_old2new_map() {
2336   _old2new_map.dump();
2337 }
2338 #endif
2339 
2340 //---------------------------collect_null_checks-------------------------------
2341 // Find null checks in the ideal graph; write a machine-specific node for
2342 // it.  Used by later implicit-null-check handling.  Actually collects
2343 // either an IfTrue or IfFalse for the common NOT-null path, AND the ideal
2344 // value being tested.
2345 void Matcher::collect_null_checks( Node *proj, Node *orig_proj ) {
2346   Node *iff = proj->in(0);
2347   if( iff->Opcode() == Op_If ) {
2348     // During matching If's have Bool & Cmp side-by-side
2349     BoolNode *b = iff->in(1)->as_Bool();
2350     Node *cmp = iff->in(2);
2351     int opc = cmp->Opcode();
2352     if (opc != Op_CmpP && opc != Op_CmpN) return;
2353 
2354     const Type* ct = cmp->in(2)->bottom_type();
2355     if (ct == TypePtr::NULL_PTR ||
2356         (opc == Op_CmpN && ct == TypeNarrowOop::NULL_PTR)) {
2357 
2358       bool push_it = false;
2359       if( proj->Opcode() == Op_IfTrue ) {
2360         extern int all_null_checks_found;
2361         all_null_checks_found++;
2362         if( b->_test._test == BoolTest::ne ) {
2363           push_it = true;
2364         }
2365       } else {
2366         assert( proj->Opcode() == Op_IfFalse, "" );
2367         if( b->_test._test == BoolTest::eq ) {
2368           push_it = true;
2369         }
2370       }
2371       if( push_it ) {
2372         _null_check_tests.push(proj);
2373         Node* val = cmp->in(1);
2374 #ifdef _LP64
2375         if (val->bottom_type()->isa_narrowoop() &&
2376             !Matcher::narrow_oop_use_complex_address()) {
2377           //
2378           // Look for DecodeN node which should be pinned to orig_proj.
2379           // On platforms (Sparc) which can not handle 2 adds
2380           // in addressing mode we have to keep a DecodeN node and
2381           // use it to do implicit NULL check in address.
2382           //
2383           // DecodeN node was pinned to non-null path (orig_proj) during
2384           // CastPP transformation in final_graph_reshaping_impl().
2385           //
2386           uint cnt = orig_proj->outcnt();
2387           for (uint i = 0; i < orig_proj->outcnt(); i++) {
2388             Node* d = orig_proj->raw_out(i);
2389             if (d->is_DecodeN() && d->in(1) == val) {
2390               val = d;
2391               val->set_req(0, NULL); // Unpin now.
2392               // Mark this as special case to distinguish from
2393               // a regular case: CmpP(DecodeN, NULL).
2394               val = (Node*)(((intptr_t)val) | 1);
2395               break;
2396             }
2397           }
2398         }
2399 #endif
2400         _null_check_tests.push(val);
2401       }
2402     }
2403   }
2404 }
2405 
2406 //---------------------------validate_null_checks------------------------------
2407 // Its possible that the value being NULL checked is not the root of a match
2408 // tree.  If so, I cannot use the value in an implicit null check.
2409 void Matcher::validate_null_checks( ) {
2410   uint cnt = _null_check_tests.size();
2411   for( uint i=0; i < cnt; i+=2 ) {
2412     Node *test = _null_check_tests[i];
2413     Node *val = _null_check_tests[i+1];
2414     bool is_decoden = ((intptr_t)val) & 1;
2415     val = (Node*)(((intptr_t)val) & ~1);
2416     if (has_new_node(val)) {
2417       Node* new_val = new_node(val);
2418       if (is_decoden) {
2419         assert(val->is_DecodeNarrowPtr() && val->in(0) == NULL, "sanity");
2420         // Note: new_val may have a control edge if
2421         // the original ideal node DecodeN was matched before
2422         // it was unpinned in Matcher::collect_null_checks().
2423         // Unpin the mach node and mark it.
2424         new_val->set_req(0, NULL);
2425         new_val = (Node*)(((intptr_t)new_val) | 1);
2426       }
2427       // Is a match-tree root, so replace with the matched value
2428       _null_check_tests.map(i+1, new_val);
2429     } else {
2430       // Yank from candidate list
2431       _null_check_tests.map(i+1,_null_check_tests[--cnt]);
2432       _null_check_tests.map(i,_null_check_tests[--cnt]);
2433       _null_check_tests.pop();
2434       _null_check_tests.pop();
2435       i-=2;
2436     }
2437   }
2438 }
2439 
2440 // Used by the DFA in dfa_xxx.cpp.  Check for a following barrier or
2441 // atomic instruction acting as a store_load barrier without any
2442 // intervening volatile load, and thus we don't need a barrier here.
2443 // We retain the Node to act as a compiler ordering barrier.
2444 bool Matcher::post_store_load_barrier(const Node* vmb) {
2445   Compile* C = Compile::current();
2446   assert(vmb->is_MemBar(), "");
2447   assert(vmb->Opcode() != Op_MemBarAcquire && vmb->Opcode() != Op_LoadFence, "");
2448   const MemBarNode* membar = vmb->as_MemBar();
2449 
2450   // Get the Ideal Proj node, ctrl, that can be used to iterate forward
2451   Node* ctrl = NULL;
2452   for (DUIterator_Fast imax, i = membar->fast_outs(imax); i < imax; i++) {
2453     Node* p = membar->fast_out(i);
2454     assert(p->is_Proj(), "only projections here");
2455     if ((p->as_Proj()->_con == TypeFunc::Control) &&
2456         !C->node_arena()->contains(p)) { // Unmatched old-space only
2457       ctrl = p;
2458       break;
2459     }
2460   }
2461   assert((ctrl != NULL), "missing control projection");
2462 
2463   for (DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++) {
2464     Node *x = ctrl->fast_out(j);
2465     int xop = x->Opcode();
2466 
2467     // We don't need current barrier if we see another or a lock
2468     // before seeing volatile load.
2469     //
2470     // Op_Fastunlock previously appeared in the Op_* list below.
2471     // With the advent of 1-0 lock operations we're no longer guaranteed
2472     // that a monitor exit operation contains a serializing instruction.
2473 
2474     if (xop == Op_MemBarVolatile ||
2475         xop == Op_CompareAndSwapL ||
2476         xop == Op_CompareAndSwapP ||
2477         xop == Op_CompareAndSwapN ||
2478         xop == Op_CompareAndSwapI) {
2479       return true;
2480     }
2481 
2482     // Op_FastLock previously appeared in the Op_* list above.
2483     // With biased locking we're no longer guaranteed that a monitor
2484     // enter operation contains a serializing instruction.
2485     if ((xop == Op_FastLock) && !UseBiasedLocking) {
2486       return true;
2487     }
2488 
2489     if (x->is_MemBar()) {
2490       // We must retain this membar if there is an upcoming volatile
2491       // load, which will be followed by acquire membar.
2492       if (xop == Op_MemBarAcquire || xop == Op_LoadFence) {
2493         return false;
2494       } else {
2495         // For other kinds of barriers, check by pretending we
2496         // are them, and seeing if we can be removed.
2497         return post_store_load_barrier(x->as_MemBar());
2498       }
2499     }
2500 
2501     // probably not necessary to check for these
2502     if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) {
2503       return false;
2504     }
2505   }
2506   return false;
2507 }
2508 
2509 // Check whether node n is a branch to an uncommon trap that we could
2510 // optimize as test with very high branch costs in case of going to
2511 // the uncommon trap. The code must be able to be recompiled to use
2512 // a cheaper test.
2513 bool Matcher::branches_to_uncommon_trap(const Node *n) {
2514   // Don't do it for natives, adapters, or runtime stubs
2515   Compile *C = Compile::current();
2516   if (!C->is_method_compilation()) return false;
2517 
2518   assert(n->is_If(), "You should only call this on if nodes.");
2519   IfNode *ifn = n->as_If();
2520 
2521   Node *ifFalse = NULL;
2522   for (DUIterator_Fast imax, i = ifn->fast_outs(imax); i < imax; i++) {
2523     if (ifn->fast_out(i)->is_IfFalse()) {
2524       ifFalse = ifn->fast_out(i);
2525       break;
2526     }
2527   }
2528   assert(ifFalse, "An If should have an ifFalse. Graph is broken.");
2529 
2530   Node *reg = ifFalse;
2531   int cnt = 4; // We must protect against cycles.  Limit to 4 iterations.
2532                // Alternatively use visited set?  Seems too expensive.
2533   while (reg != NULL && cnt > 0) {
2534     CallNode *call = NULL;
2535     RegionNode *nxt_reg = NULL;
2536     for (DUIterator_Fast imax, i = reg->fast_outs(imax); i < imax; i++) {
2537       Node *o = reg->fast_out(i);
2538       if (o->is_Call()) {
2539         call = o->as_Call();
2540       }
2541       if (o->is_Region()) {
2542         nxt_reg = o->as_Region();
2543       }
2544     }
2545 
2546     if (call &&
2547         call->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point()) {
2548       const Type* trtype = call->in(TypeFunc::Parms)->bottom_type();
2549       if (trtype->isa_int() && trtype->is_int()->is_con()) {
2550         jint tr_con = trtype->is_int()->get_con();
2551         Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
2552         Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
2553         assert((int)reason < (int)BitsPerInt, "recode bit map");
2554 
2555         if (is_set_nth_bit(C->allowed_deopt_reasons(), (int)reason)
2556             && action != Deoptimization::Action_none) {
2557           // This uncommon trap is sure to recompile, eventually.
2558           // When that happens, C->too_many_traps will prevent
2559           // this transformation from happening again.
2560           return true;
2561         }
2562       }
2563     }
2564 
2565     reg = nxt_reg;
2566     cnt--;
2567   }
2568 
2569   return false;
2570 }
2571 
2572 //=============================================================================
2573 //---------------------------State---------------------------------------------
2574 State::State(void) {
2575 #ifdef ASSERT
2576   _id = 0;
2577   _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2578   _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2579   //memset(_cost, -1, sizeof(_cost));
2580   //memset(_rule, -1, sizeof(_rule));
2581 #endif
2582   memset(_valid, 0, sizeof(_valid));
2583 }
2584 
2585 #ifdef ASSERT
2586 State::~State() {
2587   _id = 99;
2588   _kids[0] = _kids[1] = (State*)(intptr_t) CONST64(0xcafebabecafebabe);
2589   _leaf = (Node*)(intptr_t) CONST64(0xbaadf00dbaadf00d);
2590   memset(_cost, -3, sizeof(_cost));
2591   memset(_rule, -3, sizeof(_rule));
2592 }
2593 #endif
2594 
2595 #ifndef PRODUCT
2596 //---------------------------dump----------------------------------------------
2597 void State::dump() {
2598   tty->print("\n");
2599   dump(0);
2600 }
2601 
2602 void State::dump(int depth) {
2603   for( int j = 0; j < depth; j++ )
2604     tty->print("   ");
2605   tty->print("--N: ");
2606   _leaf->dump();
2607   uint i;
2608   for( i = 0; i < _LAST_MACH_OPER; i++ )
2609     // Check for valid entry
2610     if( valid(i) ) {
2611       for( int j = 0; j < depth; j++ )
2612         tty->print("   ");
2613         assert(_cost[i] != max_juint, "cost must be a valid value");
2614         assert(_rule[i] < _last_Mach_Node, "rule[i] must be valid rule");
2615         tty->print_cr("%s  %d  %s",
2616                       ruleName[i], _cost[i], ruleName[_rule[i]] );
2617       }
2618   tty->cr();
2619 
2620   for( i=0; i<2; i++ )
2621     if( _kids[i] )
2622       _kids[i]->dump(depth+1);
2623 }
2624 #endif