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