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