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