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