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