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