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