1 /*
   2  * Copyright 1998-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 // FORMS.CPP - Definitions for ADL Parser Forms Classes
  26 #include "adlc.hpp"
  27 
  28 //==============================Instructions===================================
  29 //------------------------------InstructForm-----------------------------------
  30 InstructForm::InstructForm(const char *id, bool ideal_only)
  31   : _ident(id), _ideal_only(ideal_only),
  32     _localNames(cmpstr, hashstr, Form::arena),
  33     _effects(cmpstr, hashstr, Form::arena) {
  34       _ftype = Form::INS;
  35 
  36       _matrule   = NULL;
  37       _insencode = NULL;
  38       _opcode    = NULL;
  39       _size      = NULL;
  40       _attribs   = NULL;
  41       _predicate = NULL;
  42       _exprule   = NULL;
  43       _rewrule   = NULL;
  44       _format    = NULL;
  45       _peephole  = NULL;
  46       _ins_pipe  = NULL;
  47       _uniq_idx  = NULL;
  48       _num_uniq  = 0;
  49       _cisc_spill_operand = Not_cisc_spillable;// Which operand may cisc-spill
  50       _cisc_spill_alternate = NULL;            // possible cisc replacement
  51       _cisc_reg_mask_name = NULL;
  52       _is_cisc_alternate = false;
  53       _is_short_branch = false;
  54       _short_branch_form = NULL;
  55       _alignment = 1;
  56 }
  57 
  58 InstructForm::InstructForm(const char *id, InstructForm *instr, MatchRule *rule)
  59   : _ident(id), _ideal_only(false),
  60     _localNames(instr->_localNames),
  61     _effects(instr->_effects) {
  62       _ftype = Form::INS;
  63 
  64       _matrule   = rule;
  65       _insencode = instr->_insencode;
  66       _opcode    = instr->_opcode;
  67       _size      = instr->_size;
  68       _attribs   = instr->_attribs;
  69       _predicate = instr->_predicate;
  70       _exprule   = instr->_exprule;
  71       _rewrule   = instr->_rewrule;
  72       _format    = instr->_format;
  73       _peephole  = instr->_peephole;
  74       _ins_pipe  = instr->_ins_pipe;
  75       _uniq_idx  = instr->_uniq_idx;
  76       _num_uniq  = instr->_num_uniq;
  77       _cisc_spill_operand = Not_cisc_spillable;// Which operand may cisc-spill
  78       _cisc_spill_alternate = NULL;            // possible cisc replacement
  79       _cisc_reg_mask_name = NULL;
  80       _is_cisc_alternate = false;
  81       _is_short_branch = false;
  82       _short_branch_form = NULL;
  83       _alignment = 1;
  84      // Copy parameters
  85      const char *name;
  86      instr->_parameters.reset();
  87      for (; (name = instr->_parameters.iter()) != NULL;)
  88        _parameters.addName(name);
  89 }
  90 
  91 InstructForm::~InstructForm() {
  92 }
  93 
  94 InstructForm *InstructForm::is_instruction() const {
  95   return (InstructForm*)this;
  96 }
  97 
  98 bool InstructForm::ideal_only() const {
  99   return _ideal_only;
 100 }
 101 
 102 bool InstructForm::sets_result() const {
 103   return (_matrule != NULL && _matrule->sets_result());
 104 }
 105 
 106 bool InstructForm::needs_projections() {
 107   _components.reset();
 108   for( Component *comp; (comp = _components.iter()) != NULL; ) {
 109     if (comp->isa(Component::KILL)) {
 110       return true;
 111     }
 112   }
 113   return false;
 114 }
 115 
 116 
 117 bool InstructForm::has_temps() {
 118   if (_matrule) {
 119     // Examine each component to see if it is a TEMP
 120     _components.reset();
 121     // Skip the first component, if already handled as (SET dst (...))
 122     Component *comp = NULL;
 123     if (sets_result())  comp = _components.iter();
 124     while ((comp = _components.iter()) != NULL) {
 125       if (comp->isa(Component::TEMP)) {
 126         return true;
 127       }
 128     }
 129   }
 130 
 131   return false;
 132 }
 133 
 134 uint InstructForm::num_defs_or_kills() {
 135   uint   defs_or_kills = 0;
 136 
 137   _components.reset();
 138   for( Component *comp; (comp = _components.iter()) != NULL; ) {
 139     if( comp->isa(Component::DEF) || comp->isa(Component::KILL) ) {
 140       ++defs_or_kills;
 141     }
 142   }
 143 
 144   return  defs_or_kills;
 145 }
 146 
 147 // This instruction has an expand rule?
 148 bool InstructForm::expands() const {
 149   return ( _exprule != NULL );
 150 }
 151 
 152 // This instruction has a peephole rule?
 153 Peephole *InstructForm::peepholes() const {
 154   return _peephole;
 155 }
 156 
 157 // This instruction has a peephole rule?
 158 void InstructForm::append_peephole(Peephole *peephole) {
 159   if( _peephole == NULL ) {
 160     _peephole = peephole;
 161   } else {
 162     _peephole->append_peephole(peephole);
 163   }
 164 }
 165 
 166 
 167 // ideal opcode enumeration
 168 const char *InstructForm::ideal_Opcode( FormDict &globalNames )  const {
 169   if( !_matrule ) return "Node"; // Something weird
 170   // Chain rules do not really have ideal Opcodes; use their source
 171   // operand ideal Opcode instead.
 172   if( is_simple_chain_rule(globalNames) ) {
 173     const char *src = _matrule->_rChild->_opType;
 174     OperandForm *src_op = globalNames[src]->is_operand();
 175     assert( src_op, "Not operand class of chain rule" );
 176     if( !src_op->_matrule ) return "Node";
 177     return src_op->_matrule->_opType;
 178   }
 179   // Operand chain rules do not really have ideal Opcodes
 180   if( _matrule->is_chain_rule(globalNames) )
 181     return "Node";
 182   return strcmp(_matrule->_opType,"Set")
 183     ? _matrule->_opType
 184     : _matrule->_rChild->_opType;
 185 }
 186 
 187 // Recursive check on all operands' match rules in my match rule
 188 bool InstructForm::is_pinned(FormDict &globals) {
 189   if ( ! _matrule)  return false;
 190 
 191   int  index   = 0;
 192   if (_matrule->find_type("Goto",          index)) return true;
 193   if (_matrule->find_type("If",            index)) return true;
 194   if (_matrule->find_type("CountedLoopEnd",index)) return true;
 195   if (_matrule->find_type("Return",        index)) return true;
 196   if (_matrule->find_type("Rethrow",       index)) return true;
 197   if (_matrule->find_type("TailCall",      index)) return true;
 198   if (_matrule->find_type("TailJump",      index)) return true;
 199   if (_matrule->find_type("Halt",          index)) return true;
 200   if (_matrule->find_type("Jump",          index)) return true;
 201 
 202   return is_parm(globals);
 203 }
 204 
 205 // Recursive check on all operands' match rules in my match rule
 206 bool InstructForm::is_projection(FormDict &globals) {
 207   if ( ! _matrule)  return false;
 208 
 209   int  index   = 0;
 210   if (_matrule->find_type("Goto",    index)) return true;
 211   if (_matrule->find_type("Return",  index)) return true;
 212   if (_matrule->find_type("Rethrow", index)) return true;
 213   if (_matrule->find_type("TailCall",index)) return true;
 214   if (_matrule->find_type("TailJump",index)) return true;
 215   if (_matrule->find_type("Halt",    index)) return true;
 216 
 217   return false;
 218 }
 219 
 220 // Recursive check on all operands' match rules in my match rule
 221 bool InstructForm::is_parm(FormDict &globals) {
 222   if ( ! _matrule)  return false;
 223 
 224   int  index   = 0;
 225   if (_matrule->find_type("Parm",index)) return true;
 226 
 227   return false;
 228 }
 229 
 230 
 231 // Return 'true' if this instruction matches an ideal 'Copy*' node
 232 int InstructForm::is_ideal_copy() const {
 233   return _matrule ? _matrule->is_ideal_copy() : 0;
 234 }
 235 
 236 // Return 'true' if this instruction is too complex to rematerialize.
 237 int InstructForm::is_expensive() const {
 238   // We can prove it is cheap if it has an empty encoding.
 239   // This helps with platform-specific nops like ThreadLocal and RoundFloat.
 240   if (is_empty_encoding())
 241     return 0;
 242 
 243   if (is_tls_instruction())
 244     return 1;
 245 
 246   if (_matrule == NULL)  return 0;
 247 
 248   return _matrule->is_expensive();
 249 }
 250 
 251 // Has an empty encoding if _size is a constant zero or there
 252 // are no ins_encode tokens.
 253 int InstructForm::is_empty_encoding() const {
 254   if (_insencode != NULL) {
 255     _insencode->reset();
 256     if (_insencode->encode_class_iter() == NULL) {
 257       return 1;
 258     }
 259   }
 260   if (_size != NULL && strcmp(_size, "0") == 0) {
 261     return 1;
 262   }
 263   return 0;
 264 }
 265 
 266 int InstructForm::is_tls_instruction() const {
 267   if (_ident != NULL &&
 268       ( ! strcmp( _ident,"tlsLoadP") ||
 269         ! strncmp(_ident,"tlsLoadP_",9)) ) {
 270     return 1;
 271   }
 272 
 273   if (_matrule != NULL && _insencode != NULL) {
 274     const char* opType = _matrule->_opType;
 275     if (strcmp(opType, "Set")==0)
 276       opType = _matrule->_rChild->_opType;
 277     if (strcmp(opType,"ThreadLocal")==0) {
 278       fprintf(stderr, "Warning: ThreadLocal instruction %s should be named 'tlsLoadP_*'\n",
 279               (_ident == NULL ? "NULL" : _ident));
 280       return 1;
 281     }
 282   }
 283 
 284   return 0;
 285 }
 286 
 287 
 288 // Return 'true' if this instruction matches an ideal 'Copy*' node
 289 bool InstructForm::is_ideal_unlock() const {
 290   return _matrule ? _matrule->is_ideal_unlock() : false;
 291 }
 292 
 293 bool InstructForm::is_ideal_call_leaf() const {
 294   return _matrule ? _matrule->is_ideal_call_leaf() : false;
 295 }
 296 
 297 // Return 'true' if this instruction matches an ideal 'If' node
 298 bool InstructForm::is_ideal_if() const {
 299   if( _matrule == NULL ) return false;
 300 
 301   return _matrule->is_ideal_if();
 302 }
 303 
 304 // Return 'true' if this instruction matches an ideal 'FastLock' node
 305 bool InstructForm::is_ideal_fastlock() const {
 306   if( _matrule == NULL ) return false;
 307 
 308   return _matrule->is_ideal_fastlock();
 309 }
 310 
 311 // Return 'true' if this instruction matches an ideal 'MemBarXXX' node
 312 bool InstructForm::is_ideal_membar() const {
 313   if( _matrule == NULL ) return false;
 314 
 315   return _matrule->is_ideal_membar();
 316 }
 317 
 318 // Return 'true' if this instruction matches an ideal 'LoadPC' node
 319 bool InstructForm::is_ideal_loadPC() const {
 320   if( _matrule == NULL ) return false;
 321 
 322   return _matrule->is_ideal_loadPC();
 323 }
 324 
 325 // Return 'true' if this instruction matches an ideal 'Box' node
 326 bool InstructForm::is_ideal_box() const {
 327   if( _matrule == NULL ) return false;
 328 
 329   return _matrule->is_ideal_box();
 330 }
 331 
 332 // Return 'true' if this instruction matches an ideal 'Goto' node
 333 bool InstructForm::is_ideal_goto() const {
 334   if( _matrule == NULL ) return false;
 335 
 336   return _matrule->is_ideal_goto();
 337 }
 338 
 339 // Return 'true' if this instruction matches an ideal 'Jump' node
 340 bool InstructForm::is_ideal_jump() const {
 341   if( _matrule == NULL ) return false;
 342 
 343   return _matrule->is_ideal_jump();
 344 }
 345 
 346 // Return 'true' if instruction matches ideal 'If' | 'Goto' |
 347 //                    'CountedLoopEnd' | 'Jump'
 348 bool InstructForm::is_ideal_branch() const {
 349   if( _matrule == NULL ) return false;
 350 
 351   return _matrule->is_ideal_if() || _matrule->is_ideal_goto() || _matrule->is_ideal_jump();
 352 }
 353 
 354 
 355 // Return 'true' if this instruction matches an ideal 'Return' node
 356 bool InstructForm::is_ideal_return() const {
 357   if( _matrule == NULL ) return false;
 358 
 359   // Check MatchRule to see if the first entry is the ideal "Return" node
 360   int  index   = 0;
 361   if (_matrule->find_type("Return",index)) return true;
 362   if (_matrule->find_type("Rethrow",index)) return true;
 363   if (_matrule->find_type("TailCall",index)) return true;
 364   if (_matrule->find_type("TailJump",index)) return true;
 365 
 366   return false;
 367 }
 368 
 369 // Return 'true' if this instruction matches an ideal 'Halt' node
 370 bool InstructForm::is_ideal_halt() const {
 371   int  index   = 0;
 372   return _matrule && _matrule->find_type("Halt",index);
 373 }
 374 
 375 // Return 'true' if this instruction matches an ideal 'SafePoint' node
 376 bool InstructForm::is_ideal_safepoint() const {
 377   int  index   = 0;
 378   return _matrule && _matrule->find_type("SafePoint",index);
 379 }
 380 
 381 // Return 'true' if this instruction matches an ideal 'Nop' node
 382 bool InstructForm::is_ideal_nop() const {
 383   return _ident && _ident[0] == 'N' && _ident[1] == 'o' && _ident[2] == 'p' && _ident[3] == '_';
 384 }
 385 
 386 bool InstructForm::is_ideal_control() const {
 387   if ( ! _matrule)  return false;
 388 
 389   return is_ideal_return() || is_ideal_branch() || is_ideal_halt();
 390 }
 391 
 392 // Return 'true' if this instruction matches an ideal 'Call' node
 393 Form::CallType InstructForm::is_ideal_call() const {
 394   if( _matrule == NULL ) return Form::invalid_type;
 395 
 396   // Check MatchRule to see if the first entry is the ideal "Call" node
 397   int  idx   = 0;
 398   if(_matrule->find_type("CallStaticJava",idx))   return Form::JAVA_STATIC;
 399   idx = 0;
 400   if(_matrule->find_type("Lock",idx))             return Form::JAVA_STATIC;
 401   idx = 0;
 402   if(_matrule->find_type("Unlock",idx))           return Form::JAVA_STATIC;
 403   idx = 0;
 404   if(_matrule->find_type("CallDynamicJava",idx))  return Form::JAVA_DYNAMIC;
 405   idx = 0;
 406   if(_matrule->find_type("CallRuntime",idx))      return Form::JAVA_RUNTIME;
 407   idx = 0;
 408   if(_matrule->find_type("CallLeaf",idx))         return Form::JAVA_LEAF;
 409   idx = 0;
 410   if(_matrule->find_type("CallLeafNoFP",idx))     return Form::JAVA_LEAF;
 411   idx = 0;
 412 
 413   return Form::invalid_type;
 414 }
 415 
 416 // Return 'true' if this instruction matches an ideal 'Load?' node
 417 Form::DataType InstructForm::is_ideal_load() const {
 418   if( _matrule == NULL ) return Form::none;
 419 
 420   return  _matrule->is_ideal_load();
 421 }
 422 
 423 // Return 'true' if this instruction matches an ideal 'Load?' node
 424 Form::DataType InstructForm::is_ideal_store() const {
 425   if( _matrule == NULL ) return Form::none;
 426 
 427   return  _matrule->is_ideal_store();
 428 }
 429 
 430 // Return the input register that must match the output register
 431 // If this is not required, return 0
 432 uint InstructForm::two_address(FormDict &globals) {
 433   uint  matching_input = 0;
 434   if(_components.count() == 0) return 0;
 435 
 436   _components.reset();
 437   Component *comp = _components.iter();
 438   // Check if there is a DEF
 439   if( comp->isa(Component::DEF) ) {
 440     // Check that this is a register
 441     const char  *def_type = comp->_type;
 442     const Form  *form     = globals[def_type];
 443     OperandForm *op       = form->is_operand();
 444     if( op ) {
 445       if( op->constrained_reg_class() != NULL &&
 446           op->interface_type(globals) == Form::register_interface ) {
 447         // Remember the local name for equality test later
 448         const char *def_name = comp->_name;
 449         // Check if a component has the same name and is a USE
 450         do {
 451           if( comp->isa(Component::USE) && strcmp(comp->_name,def_name)==0 ) {
 452             return operand_position_format(def_name);
 453           }
 454         } while( (comp = _components.iter()) != NULL);
 455       }
 456     }
 457   }
 458 
 459   return 0;
 460 }
 461 
 462 
 463 // when chaining a constant to an instruction, returns 'true' and sets opType
 464 Form::DataType InstructForm::is_chain_of_constant(FormDict &globals) {
 465   const char *dummy  = NULL;
 466   const char *dummy2 = NULL;
 467   return is_chain_of_constant(globals, dummy, dummy2);
 468 }
 469 Form::DataType InstructForm::is_chain_of_constant(FormDict &globals,
 470                 const char * &opTypeParam) {
 471   const char *result = NULL;
 472 
 473   return is_chain_of_constant(globals, opTypeParam, result);
 474 }
 475 
 476 Form::DataType InstructForm::is_chain_of_constant(FormDict &globals,
 477                 const char * &opTypeParam, const char * &resultParam) {
 478   Form::DataType  data_type = Form::none;
 479   if ( ! _matrule)  return data_type;
 480 
 481   // !!!!!
 482   // The source of the chain rule is 'position = 1'
 483   uint         position = 1;
 484   const char  *result   = NULL;
 485   const char  *name     = NULL;
 486   const char  *opType   = NULL;
 487   // Here base_operand is looking for an ideal type to be returned (opType).
 488   if ( _matrule->is_chain_rule(globals)
 489        && _matrule->base_operand(position, globals, result, name, opType) ) {
 490     data_type = ideal_to_const_type(opType);
 491 
 492     // if it isn't an ideal constant type, just return
 493     if ( data_type == Form::none ) return data_type;
 494 
 495     // Ideal constant types also adjust the opType parameter.
 496     resultParam = result;
 497     opTypeParam = opType;
 498     return data_type;
 499   }
 500 
 501   return data_type;
 502 }
 503 
 504 // Check if a simple chain rule
 505 bool InstructForm::is_simple_chain_rule(FormDict &globals) const {
 506   if( _matrule && _matrule->sets_result()
 507       && _matrule->_rChild->_lChild == NULL
 508       && globals[_matrule->_rChild->_opType]
 509       && globals[_matrule->_rChild->_opType]->is_opclass() ) {
 510     return true;
 511   }
 512   return false;
 513 }
 514 
 515 // check for structural rematerialization
 516 bool InstructForm::rematerialize(FormDict &globals, RegisterForm *registers ) {
 517   bool   rematerialize = false;
 518 
 519   Form::DataType data_type = is_chain_of_constant(globals);
 520   if( data_type != Form::none )
 521     rematerialize = true;
 522 
 523   // Constants
 524   if( _components.count() == 1 && _components[0]->is(Component::USE_DEF) )
 525     rematerialize = true;
 526 
 527   // Pseudo-constants (values easily available to the runtime)
 528   if (is_empty_encoding() && is_tls_instruction())
 529     rematerialize = true;
 530 
 531   // 1-input, 1-output, such as copies or increments.
 532   if( _components.count() == 2 &&
 533       _components[0]->is(Component::DEF) &&
 534       _components[1]->isa(Component::USE) )
 535     rematerialize = true;
 536 
 537   // Check for an ideal 'Load?' and eliminate rematerialize option
 538   if ( is_ideal_load() != Form::none || // Ideal load?  Do not rematerialize
 539        is_ideal_copy() != Form::none || // Ideal copy?  Do not rematerialize
 540        is_expensive()  != Form::none) { // Expensive?   Do not rematerialize
 541     rematerialize = false;
 542   }
 543 
 544   // Always rematerialize the flags.  They are more expensive to save &
 545   // restore than to recompute (and possibly spill the compare's inputs).
 546   if( _components.count() >= 1 ) {
 547     Component *c = _components[0];
 548     const Form *form = globals[c->_type];
 549     OperandForm *opform = form->is_operand();
 550     if( opform ) {
 551       // Avoid the special stack_slots register classes
 552       const char *rc_name = opform->constrained_reg_class();
 553       if( rc_name ) {
 554         if( strcmp(rc_name,"stack_slots") ) {
 555           // Check for ideal_type of RegFlags
 556           const char *type = opform->ideal_type( globals, registers );
 557           if( !strcmp(type,"RegFlags") )
 558             rematerialize = true;
 559         } else
 560           rematerialize = false; // Do not rematerialize things target stk
 561       }
 562     }
 563   }
 564 
 565   return rematerialize;
 566 }
 567 
 568 // loads from memory, so must check for anti-dependence
 569 bool InstructForm::needs_anti_dependence_check(FormDict &globals) const {
 570   // Machine independent loads must be checked for anti-dependences
 571   if( is_ideal_load() != Form::none )  return true;
 572 
 573   // !!!!! !!!!! !!!!!
 574   // TEMPORARY
 575   // if( is_simple_chain_rule(globals) )  return false;
 576 
 577   // String-compare uses many memorys edges, but writes none
 578   if( _matrule && _matrule->_rChild &&
 579       strcmp(_matrule->_rChild->_opType,"StrComp")==0 )
 580     return true;
 581 
 582   // Check if instruction has a USE of a memory operand class, but no defs
 583   bool USE_of_memory  = false;
 584   bool DEF_of_memory  = false;
 585   Component     *comp = NULL;
 586   ComponentList &components = (ComponentList &)_components;
 587 
 588   components.reset();
 589   while( (comp = components.iter()) != NULL ) {
 590     const Form  *form = globals[comp->_type];
 591     if( !form ) continue;
 592     OpClassForm *op   = form->is_opclass();
 593     if( !op ) continue;
 594     if( form->interface_type(globals) == Form::memory_interface ) {
 595       if( comp->isa(Component::USE) ) USE_of_memory = true;
 596       if( comp->isa(Component::DEF) ) {
 597         OperandForm *oper = form->is_operand();
 598         if( oper && oper->is_user_name_for_sReg() ) {
 599           // Stack slots are unaliased memory handled by allocator
 600           oper = oper;  // debug stopping point !!!!!
 601         } else {
 602           DEF_of_memory = true;
 603         }
 604       }
 605     }
 606   }
 607   return (USE_of_memory && !DEF_of_memory);
 608 }
 609 
 610 
 611 bool InstructForm::is_wide_memory_kill(FormDict &globals) const {
 612   if( _matrule == NULL ) return false;
 613   if( !_matrule->_opType ) return false;
 614 
 615   if( strcmp(_matrule->_opType,"MemBarRelease") == 0 ) return true;
 616   if( strcmp(_matrule->_opType,"MemBarAcquire") == 0 ) return true;
 617 
 618   return false;
 619 }
 620 
 621 int InstructForm::memory_operand(FormDict &globals) const {
 622   // Machine independent loads must be checked for anti-dependences
 623   // Check if instruction has a USE of a memory operand class, or a def.
 624   int USE_of_memory  = 0;
 625   int DEF_of_memory  = 0;
 626   const char*    last_memory_DEF = NULL; // to test DEF/USE pairing in asserts
 627   Component     *unique          = NULL;
 628   Component     *comp            = NULL;
 629   ComponentList &components      = (ComponentList &)_components;
 630 
 631   components.reset();
 632   while( (comp = components.iter()) != NULL ) {
 633     const Form  *form = globals[comp->_type];
 634     if( !form ) continue;
 635     OpClassForm *op   = form->is_opclass();
 636     if( !op ) continue;
 637     if( op->stack_slots_only(globals) )  continue;
 638     if( form->interface_type(globals) == Form::memory_interface ) {
 639       if( comp->isa(Component::DEF) ) {
 640         last_memory_DEF = comp->_name;
 641         DEF_of_memory++;
 642         unique = comp;
 643       } else if( comp->isa(Component::USE) ) {
 644         if( last_memory_DEF != NULL ) {
 645           assert(0 == strcmp(last_memory_DEF, comp->_name), "every memory DEF is followed by a USE of the same name");
 646           last_memory_DEF = NULL;
 647         }
 648         USE_of_memory++;
 649         if (DEF_of_memory == 0)  // defs take precedence
 650           unique = comp;
 651       } else {
 652         assert(last_memory_DEF == NULL, "unpaired memory DEF");
 653       }
 654     }
 655   }
 656   assert(last_memory_DEF == NULL, "unpaired memory DEF");
 657   assert(USE_of_memory >= DEF_of_memory, "unpaired memory DEF");
 658   USE_of_memory -= DEF_of_memory;   // treat paired DEF/USE as one occurrence
 659   if( (USE_of_memory + DEF_of_memory) > 0 ) {
 660     if( is_simple_chain_rule(globals) ) {
 661       //fprintf(stderr, "Warning: chain rule is not really a memory user.\n");
 662       //((InstructForm*)this)->dump();
 663       // Preceding code prints nothing on sparc and these insns on intel:
 664       // leaP8 leaP32 leaPIdxOff leaPIdxScale leaPIdxScaleOff leaP8 leaP32
 665       // leaPIdxOff leaPIdxScale leaPIdxScaleOff
 666       return NO_MEMORY_OPERAND;
 667     }
 668 
 669     if( DEF_of_memory == 1 ) {
 670       assert(unique != NULL, "");
 671       if( USE_of_memory == 0 ) {
 672         // unique def, no uses
 673       } else {
 674         // // unique def, some uses
 675         // // must return bottom unless all uses match def
 676         // unique = NULL;
 677       }
 678     } else if( DEF_of_memory > 0 ) {
 679       // multiple defs, don't care about uses
 680       unique = NULL;
 681     } else if( USE_of_memory == 1) {
 682       // unique use, no defs
 683       assert(unique != NULL, "");
 684     } else if( USE_of_memory > 0 ) {
 685       // multiple uses, no defs
 686       unique = NULL;
 687     } else {
 688       assert(false, "bad case analysis");
 689     }
 690     // process the unique DEF or USE, if there is one
 691     if( unique == NULL ) {
 692       return MANY_MEMORY_OPERANDS;
 693     } else {
 694       int pos = components.operand_position(unique->_name);
 695       if( unique->isa(Component::DEF) ) {
 696         pos += 1;                // get corresponding USE from DEF
 697       }
 698       assert(pos >= 1, "I was just looking at it!");
 699       return pos;
 700     }
 701   }
 702 
 703   // missed the memory op??
 704   if( true ) {  // %%% should not be necessary
 705     if( is_ideal_store() != Form::none ) {
 706       fprintf(stderr, "Warning: cannot find memory opnd in instr.\n");
 707       ((InstructForm*)this)->dump();
 708       // pretend it has multiple defs and uses
 709       return MANY_MEMORY_OPERANDS;
 710     }
 711     if( is_ideal_load()  != Form::none ) {
 712       fprintf(stderr, "Warning: cannot find memory opnd in instr.\n");
 713       ((InstructForm*)this)->dump();
 714       // pretend it has multiple uses and no defs
 715       return MANY_MEMORY_OPERANDS;
 716     }
 717   }
 718 
 719   return NO_MEMORY_OPERAND;
 720 }
 721 
 722 
 723 // This instruction captures the machine-independent bottom_type
 724 // Expected use is for pointer vs oop determination for LoadP
 725 bool InstructForm::captures_bottom_type() const {
 726   if( _matrule && _matrule->_rChild &&
 727        (!strcmp(_matrule->_rChild->_opType,"CastPP")     ||  // new result type
 728         !strcmp(_matrule->_rChild->_opType,"CastX2P")    ||  // new result type
 729         !strcmp(_matrule->_rChild->_opType,"DecodeN")    ||
 730         !strcmp(_matrule->_rChild->_opType,"EncodeP")    ||
 731         !strcmp(_matrule->_rChild->_opType,"LoadN")      ||
 732         !strcmp(_matrule->_rChild->_opType,"LoadNKlass") ||
 733         !strcmp(_matrule->_rChild->_opType,"CreateEx")   ||  // type of exception
 734         !strcmp(_matrule->_rChild->_opType,"CheckCastPP")) ) return true;
 735   else if ( is_ideal_load() == Form::idealP )                return true;
 736   else if ( is_ideal_store() != Form::none  )                return true;
 737 
 738   return  false;
 739 }
 740 
 741 
 742 // Access instr_cost attribute or return NULL.
 743 const char* InstructForm::cost() {
 744   for (Attribute* cur = _attribs; cur != NULL; cur = (Attribute*)cur->_next) {
 745     if( strcmp(cur->_ident,AttributeForm::_ins_cost) == 0 ) {
 746       return cur->_val;
 747     }
 748   }
 749   return NULL;
 750 }
 751 
 752 // Return count of top-level operands.
 753 uint InstructForm::num_opnds() {
 754   int  num_opnds = _components.num_operands();
 755 
 756   // Need special handling for matching some ideal nodes
 757   // i.e. Matching a return node
 758   /*
 759   if( _matrule ) {
 760     if( strcmp(_matrule->_opType,"Return"   )==0 ||
 761         strcmp(_matrule->_opType,"Halt"     )==0 )
 762       return 3;
 763   }
 764     */
 765   return num_opnds;
 766 }
 767 
 768 // Return count of unmatched operands.
 769 uint InstructForm::num_post_match_opnds() {
 770   uint  num_post_match_opnds = _components.count();
 771   uint  num_match_opnds = _components.match_count();
 772   num_post_match_opnds = num_post_match_opnds - num_match_opnds;
 773 
 774   return num_post_match_opnds;
 775 }
 776 
 777 // Return the number of leaves below this complex operand
 778 uint InstructForm::num_consts(FormDict &globals) const {
 779   if ( ! _matrule) return 0;
 780 
 781   // This is a recursive invocation on all operands in the matchrule
 782   return _matrule->num_consts(globals);
 783 }
 784 
 785 // Constants in match rule with specified type
 786 uint InstructForm::num_consts(FormDict &globals, Form::DataType type) const {
 787   if ( ! _matrule) return 0;
 788 
 789   // This is a recursive invocation on all operands in the matchrule
 790   return _matrule->num_consts(globals, type);
 791 }
 792 
 793 
 794 // Return the register class associated with 'leaf'.
 795 const char *InstructForm::out_reg_class(FormDict &globals) {
 796   assert( false, "InstructForm::out_reg_class(FormDict &globals); Not Implemented");
 797 
 798   return NULL;
 799 }
 800 
 801 
 802 
 803 // Lookup the starting position of inputs we are interested in wrt. ideal nodes
 804 uint InstructForm::oper_input_base(FormDict &globals) {
 805   if( !_matrule ) return 1;     // Skip control for most nodes
 806 
 807   // Need special handling for matching some ideal nodes
 808   // i.e. Matching a return node
 809   if( strcmp(_matrule->_opType,"Return"    )==0 ||
 810       strcmp(_matrule->_opType,"Rethrow"   )==0 ||
 811       strcmp(_matrule->_opType,"TailCall"  )==0 ||
 812       strcmp(_matrule->_opType,"TailJump"  )==0 ||
 813       strcmp(_matrule->_opType,"SafePoint" )==0 ||
 814       strcmp(_matrule->_opType,"Halt"      )==0 )
 815     return AdlcVMDeps::Parms;   // Skip the machine-state edges
 816 
 817   if( _matrule->_rChild &&
 818           strcmp(_matrule->_rChild->_opType,"StrComp")==0 ) {
 819         // String compare takes 1 control and 4 memory edges.
 820     return 5;
 821   }
 822 
 823   // Check for handling of 'Memory' input/edge in the ideal world.
 824   // The AD file writer is shielded from knowledge of these edges.
 825   int base = 1;                 // Skip control
 826   base += _matrule->needs_ideal_memory_edge(globals);
 827 
 828   // Also skip the base-oop value for uses of derived oops.
 829   // The AD file writer is shielded from knowledge of these edges.
 830   base += needs_base_oop_edge(globals);
 831 
 832   return base;
 833 }
 834 
 835 // Implementation does not modify state of internal structures
 836 void InstructForm::build_components() {
 837   // Add top-level operands to the components
 838   if (_matrule)  _matrule->append_components(_localNames, _components);
 839 
 840   // Add parameters that "do not appear in match rule".
 841   bool has_temp = false;
 842   const char *name;
 843   const char *kill_name = NULL;
 844   for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
 845     OperandForm *opForm = (OperandForm*)_localNames[name];
 846 
 847     const Form *form = _effects[name];
 848     Effect     *e    = form ? form->is_effect() : NULL;
 849     if (e != NULL) {
 850       has_temp |= e->is(Component::TEMP);
 851 
 852       // KILLs must be declared after any TEMPs because TEMPs are real
 853       // uses so their operand numbering must directly follow the real
 854       // inputs from the match rule.  Fixing the numbering seems
 855       // complex so simply enforce the restriction during parse.
 856       if (kill_name != NULL &&
 857           e->isa(Component::TEMP) && !e->isa(Component::DEF)) {
 858         OperandForm* kill = (OperandForm*)_localNames[kill_name];
 859         globalAD->syntax_err(_linenum, "%s: %s %s must be at the end of the argument list\n",
 860                              _ident, kill->_ident, kill_name);
 861       } else if (e->isa(Component::KILL)) {
 862         kill_name = name;
 863       }
 864 
 865       // TEMPs are real uses and need to be among the first parameters
 866       // listed, otherwise the numbering of operands and inputs gets
 867       // screwy, so enforce this restriction during parse.
 868       if (kill_name != NULL &&
 869           e->isa(Component::TEMP) && !e->isa(Component::DEF)) {
 870         OperandForm* kill = (OperandForm*)_localNames[kill_name];
 871         globalAD->syntax_err(_linenum, "%s: %s %s must follow %s %s in the argument list\n",
 872                              _ident, kill->_ident, kill_name, opForm->_ident, name);
 873       } else if (e->isa(Component::KILL)) {
 874         kill_name = name;
 875       }
 876     }
 877 
 878     const Component *component  = _components.search(name);
 879     if ( component  == NULL ) {
 880       if (e) {
 881         _components.insert(name, opForm->_ident, e->_use_def, false);
 882         component = _components.search(name);
 883         if (component->isa(Component::USE) && !component->isa(Component::TEMP) && _matrule) {
 884           const Form *form = globalAD->globalNames()[component->_type];
 885           assert( form, "component type must be a defined form");
 886           OperandForm *op   = form->is_operand();
 887           if (op->_interface && op->_interface->is_RegInterface()) {
 888             globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
 889                                  _ident, opForm->_ident, name);
 890           }
 891         }
 892       } else {
 893         // This would be a nice warning but it triggers in a few places in a benign way
 894         // if (_matrule != NULL && !expands()) {
 895         //   globalAD->syntax_err(_linenum, "%s: %s %s not mentioned in effect or match rule\n",
 896         //                        _ident, opForm->_ident, name);
 897         // }
 898         _components.insert(name, opForm->_ident, Component::INVALID, false);
 899       }
 900     }
 901     else if (e) {
 902       // Component was found in the list
 903       // Check if there is a new effect that requires an extra component.
 904       // This happens when adding 'USE' to a component that is not yet one.
 905       if ((!component->isa( Component::USE) && ((e->_use_def & Component::USE) != 0))) {
 906         if (component->isa(Component::USE) && _matrule) {
 907           const Form *form = globalAD->globalNames()[component->_type];
 908           assert( form, "component type must be a defined form");
 909           OperandForm *op   = form->is_operand();
 910           if (op->_interface && op->_interface->is_RegInterface()) {
 911             globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
 912                                  _ident, opForm->_ident, name);
 913           }
 914         }
 915         _components.insert(name, opForm->_ident, e->_use_def, false);
 916       } else {
 917         Component  *comp = (Component*)component;
 918         comp->promote_use_def_info(e->_use_def);
 919       }
 920       // Component positions are zero based.
 921       int  pos  = _components.operand_position(name);
 922       assert( ! (component->isa(Component::DEF) && (pos >= 1)),
 923               "Component::DEF can only occur in the first position");
 924     }
 925   }
 926 
 927   // Resolving the interactions between expand rules and TEMPs would
 928   // be complex so simply disallow it.
 929   if (_matrule == NULL && has_temp) {
 930     globalAD->syntax_err(_linenum, "%s: TEMPs without match rule isn't supported\n", _ident);
 931   }
 932 
 933   return;
 934 }
 935 
 936 // Return zero-based position in component list;  -1 if not in list.
 937 int   InstructForm::operand_position(const char *name, int usedef) {
 938   return unique_opnds_idx(_components.operand_position(name, usedef));
 939 }
 940 
 941 int   InstructForm::operand_position_format(const char *name) {
 942   return unique_opnds_idx(_components.operand_position_format(name));
 943 }
 944 
 945 // Return zero-based position in component list; -1 if not in list.
 946 int   InstructForm::label_position() {
 947   return unique_opnds_idx(_components.label_position());
 948 }
 949 
 950 int   InstructForm::method_position() {
 951   return unique_opnds_idx(_components.method_position());
 952 }
 953 
 954 // Return number of relocation entries needed for this instruction.
 955 uint  InstructForm::reloc(FormDict &globals) {
 956   uint reloc_entries  = 0;
 957   // Check for "Call" nodes
 958   if ( is_ideal_call() )      ++reloc_entries;
 959   if ( is_ideal_return() )    ++reloc_entries;
 960   if ( is_ideal_safepoint() ) ++reloc_entries;
 961 
 962 
 963   // Check if operands MAYBE oop pointers, by checking for ConP elements
 964   // Proceed through the leaves of the match-tree and check for ConPs
 965   if ( _matrule != NULL ) {
 966     uint         position = 0;
 967     const char  *result   = NULL;
 968     const char  *name     = NULL;
 969     const char  *opType   = NULL;
 970     while (_matrule->base_operand(position, globals, result, name, opType)) {
 971       if ( strcmp(opType,"ConP") == 0 ) {
 972 #ifdef SPARC
 973         reloc_entries += 2; // 1 for sethi + 1 for setlo
 974 #else
 975         ++reloc_entries;
 976 #endif
 977       }
 978       ++position;
 979     }
 980   }
 981 
 982   // Above is only a conservative estimate
 983   // because it did not check contents of operand classes.
 984   // !!!!! !!!!!
 985   // Add 1 to reloc info for each operand class in the component list.
 986   Component  *comp;
 987   _components.reset();
 988   while ( (comp = _components.iter()) != NULL ) {
 989     const Form        *form = globals[comp->_type];
 990     assert( form, "Did not find component's type in global names");
 991     const OpClassForm *opc  = form->is_opclass();
 992     const OperandForm *oper = form->is_operand();
 993     if ( opc && (oper == NULL) ) {
 994       ++reloc_entries;
 995     } else if ( oper ) {
 996       // floats and doubles loaded out of method's constant pool require reloc info
 997       Form::DataType type = oper->is_base_constant(globals);
 998       if ( (type == Form::idealF) || (type == Form::idealD) ) {
 999         ++reloc_entries;
1000       }
1001     }
1002   }
1003 
1004   // Float and Double constants may come from the CodeBuffer table
1005   // and require relocatable addresses for access
1006   // !!!!!
1007   // Check for any component being an immediate float or double.
1008   Form::DataType data_type = is_chain_of_constant(globals);
1009   if( data_type==idealD || data_type==idealF ) {
1010 #ifdef SPARC
1011     // sparc required more relocation entries for floating constants
1012     // (expires 9/98)
1013     reloc_entries += 6;
1014 #else
1015     reloc_entries++;
1016 #endif
1017   }
1018 
1019   return reloc_entries;
1020 }
1021 
1022 // Utility function defined in archDesc.cpp
1023 extern bool is_def(int usedef);
1024 
1025 // Return the result of reducing an instruction
1026 const char *InstructForm::reduce_result() {
1027   const char* result = "Universe";  // default
1028   _components.reset();
1029   Component *comp = _components.iter();
1030   if (comp != NULL && comp->isa(Component::DEF)) {
1031     result = comp->_type;
1032     // Override this if the rule is a store operation:
1033     if (_matrule && _matrule->_rChild &&
1034         is_store_to_memory(_matrule->_rChild->_opType))
1035       result = "Universe";
1036   }
1037   return result;
1038 }
1039 
1040 // Return the name of the operand on the right hand side of the binary match
1041 // Return NULL if there is no right hand side
1042 const char *InstructForm::reduce_right(FormDict &globals)  const {
1043   if( _matrule == NULL ) return NULL;
1044   return  _matrule->reduce_right(globals);
1045 }
1046 
1047 // Similar for left
1048 const char *InstructForm::reduce_left(FormDict &globals)   const {
1049   if( _matrule == NULL ) return NULL;
1050   return  _matrule->reduce_left(globals);
1051 }
1052 
1053 
1054 // Base class for this instruction, MachNode except for calls
1055 const char *InstructForm::mach_base_class()  const {
1056   if( is_ideal_call() == Form::JAVA_STATIC ) {
1057     return "MachCallStaticJavaNode";
1058   }
1059   else if( is_ideal_call() == Form::JAVA_DYNAMIC ) {
1060     return "MachCallDynamicJavaNode";
1061   }
1062   else if( is_ideal_call() == Form::JAVA_RUNTIME ) {
1063     return "MachCallRuntimeNode";
1064   }
1065   else if( is_ideal_call() == Form::JAVA_LEAF ) {
1066     return "MachCallLeafNode";
1067   }
1068   else if (is_ideal_return()) {
1069     return "MachReturnNode";
1070   }
1071   else if (is_ideal_halt()) {
1072     return "MachHaltNode";
1073   }
1074   else if (is_ideal_safepoint()) {
1075     return "MachSafePointNode";
1076   }
1077   else if (is_ideal_if()) {
1078     return "MachIfNode";
1079   }
1080   else if (is_ideal_fastlock()) {
1081     return "MachFastLockNode";
1082   }
1083   else if (is_ideal_nop()) {
1084     return "MachNopNode";
1085   }
1086   else if (captures_bottom_type()) {
1087     return "MachTypeNode";
1088   } else {
1089     return "MachNode";
1090   }
1091   assert( false, "ShouldNotReachHere()");
1092   return NULL;
1093 }
1094 
1095 // Compare the instruction predicates for textual equality
1096 bool equivalent_predicates( const InstructForm *instr1, const InstructForm *instr2 ) {
1097   const Predicate *pred1  = instr1->_predicate;
1098   const Predicate *pred2  = instr2->_predicate;
1099   if( pred1 == NULL && pred2 == NULL ) {
1100     // no predicates means they are identical
1101     return true;
1102   }
1103   if( pred1 != NULL && pred2 != NULL ) {
1104     // compare the predicates
1105     if (ADLParser::equivalent_expressions(pred1->_pred, pred2->_pred)) {
1106       return true;
1107     }
1108   }
1109 
1110   return false;
1111 }
1112 
1113 // Check if this instruction can cisc-spill to 'alternate'
1114 bool InstructForm::cisc_spills_to(ArchDesc &AD, InstructForm *instr) {
1115   assert( _matrule != NULL && instr->_matrule != NULL, "must have match rules");
1116   // Do not replace if a cisc-version has been found.
1117   if( cisc_spill_operand() != Not_cisc_spillable ) return false;
1118 
1119   int         cisc_spill_operand = Maybe_cisc_spillable;
1120   char       *result             = NULL;
1121   char       *result2            = NULL;
1122   const char *op_name            = NULL;
1123   const char *reg_type           = NULL;
1124   FormDict   &globals            = AD.globalNames();
1125   cisc_spill_operand = _matrule->cisc_spill_match(globals, AD.get_registers(), instr->_matrule, op_name, reg_type);
1126   if( (cisc_spill_operand != Not_cisc_spillable) && (op_name != NULL) && equivalent_predicates(this, instr) ) {
1127     cisc_spill_operand = operand_position(op_name, Component::USE);
1128     int def_oper  = operand_position(op_name, Component::DEF);
1129     if( def_oper == NameList::Not_in_list && instr->num_opnds() == num_opnds()) {
1130       // Do not support cisc-spilling for destination operands and
1131       // make sure they have the same number of operands.
1132       _cisc_spill_alternate = instr;
1133       instr->set_cisc_alternate(true);
1134       if( AD._cisc_spill_debug ) {
1135         fprintf(stderr, "Instruction %s cisc-spills-to %s\n", _ident, instr->_ident);
1136         fprintf(stderr, "   using operand %s %s at index %d\n", reg_type, op_name, cisc_spill_operand);
1137       }
1138       // Record that a stack-version of the reg_mask is needed
1139       // !!!!!
1140       OperandForm *oper = (OperandForm*)(globals[reg_type]->is_operand());
1141       assert( oper != NULL, "cisc-spilling non operand");
1142       const char *reg_class_name = oper->constrained_reg_class();
1143       AD.set_stack_or_reg(reg_class_name);
1144       const char *reg_mask_name  = AD.reg_mask(*oper);
1145       set_cisc_reg_mask_name(reg_mask_name);
1146       const char *stack_or_reg_mask_name = AD.stack_or_reg_mask(*oper);
1147     } else {
1148       cisc_spill_operand = Not_cisc_spillable;
1149     }
1150   } else {
1151     cisc_spill_operand = Not_cisc_spillable;
1152   }
1153 
1154   set_cisc_spill_operand(cisc_spill_operand);
1155   return (cisc_spill_operand != Not_cisc_spillable);
1156 }
1157 
1158 // Check to see if this instruction can be replaced with the short branch
1159 // instruction `short-branch'
1160 bool InstructForm::check_branch_variant(ArchDesc &AD, InstructForm *short_branch) {
1161   if (_matrule != NULL &&
1162       this != short_branch &&   // Don't match myself
1163       !is_short_branch() &&     // Don't match another short branch variant
1164       reduce_result() != NULL &&
1165       strcmp(reduce_result(), short_branch->reduce_result()) == 0 &&
1166       _matrule->equivalent(AD.globalNames(), short_branch->_matrule)) {
1167     // The instructions are equivalent.
1168     if (AD._short_branch_debug) {
1169       fprintf(stderr, "Instruction %s has short form %s\n", _ident, short_branch->_ident);
1170     }
1171     _short_branch_form = short_branch;
1172     return true;
1173   }
1174   return false;
1175 }
1176 
1177 
1178 // --------------------------- FILE *output_routines
1179 //
1180 // Generate the format call for the replacement variable
1181 void InstructForm::rep_var_format(FILE *fp, const char *rep_var) {
1182   // Find replacement variable's type
1183   const Form *form   = _localNames[rep_var];
1184   if (form == NULL) {
1185     fprintf(stderr, "unknown replacement variable in format statement: '%s'\n", rep_var);
1186     assert(false, "ShouldNotReachHere()");
1187   }
1188   OpClassForm *opc   = form->is_opclass();
1189   assert( opc, "replacement variable was not found in local names");
1190   // Lookup the index position of the replacement variable
1191   int idx  = operand_position_format(rep_var);
1192   if ( idx == -1 ) {
1193     assert( strcmp(opc->_ident,"label")==0, "Unimplemented");
1194     assert( false, "ShouldNotReachHere()");
1195   }
1196 
1197   if (is_noninput_operand(idx)) {
1198     // This component isn't in the input array.  Print out the static
1199     // name of the register.
1200     OperandForm* oper = form->is_operand();
1201     if (oper != NULL && oper->is_bound_register()) {
1202       const RegDef* first = oper->get_RegClass()->find_first_elem();
1203       fprintf(fp, "    tty->print(\"%s\");\n", first->_regname);
1204     } else {
1205       globalAD->syntax_err(_linenum, "In %s can't find format for %s %s", _ident, opc->_ident, rep_var);
1206     }
1207   } else {
1208     // Output the format call for this operand
1209     fprintf(fp,"opnd_array(%d)->",idx);
1210     if (idx == 0)
1211       fprintf(fp,"int_format(ra, this, st); // %s\n", rep_var);
1212     else
1213       fprintf(fp,"ext_format(ra, this,idx%d, st); // %s\n", idx, rep_var );
1214   }
1215 }
1216 
1217 // Seach through operands to determine parameters unique positions.
1218 void InstructForm::set_unique_opnds() {
1219   uint* uniq_idx = NULL;
1220   uint  nopnds = num_opnds();
1221   uint  num_uniq = nopnds;
1222   uint i;
1223   if ( nopnds > 0 ) {
1224     // Allocate index array with reserve.
1225     uniq_idx = (uint*) malloc(sizeof(uint)*(nopnds + 2));
1226     for( i = 0; i < nopnds+2; i++ ) {
1227       uniq_idx[i] = i;
1228     }
1229   }
1230   // Do it only if there is a match rule and no expand rule.  With an
1231   // expand rule it is done by creating new mach node in Expand()
1232   // method.
1233   if ( nopnds > 0 && _matrule != NULL && _exprule == NULL ) {
1234     const char *name;
1235     uint count;
1236     bool has_dupl_use = false;
1237 
1238     _parameters.reset();
1239     while( (name = _parameters.iter()) != NULL ) {
1240       count = 0;
1241       uint position = 0;
1242       uint uniq_position = 0;
1243       _components.reset();
1244       Component *comp = NULL;
1245       if( sets_result() ) {
1246         comp = _components.iter();
1247         position++;
1248       }
1249       // The next code is copied from the method operand_position().
1250       for (; (comp = _components.iter()) != NULL; ++position) {
1251         // When the first component is not a DEF,
1252         // leave space for the result operand!
1253         if ( position==0 && (! comp->isa(Component::DEF)) ) {
1254           ++position;
1255         }
1256         if( strcmp(name, comp->_name)==0 ) {
1257           if( ++count > 1 ) {
1258             uniq_idx[position] = uniq_position;
1259             has_dupl_use = true;
1260           } else {
1261             uniq_position = position;
1262           }
1263         }
1264         if( comp->isa(Component::DEF)
1265             && comp->isa(Component::USE) ) {
1266           ++position;
1267           if( position != 1 )
1268             --position;   // only use two slots for the 1st USE_DEF
1269         }
1270       }
1271     }
1272     if( has_dupl_use ) {
1273       for( i = 1; i < nopnds; i++ )
1274         if( i != uniq_idx[i] )
1275           break;
1276       int  j = i;
1277       for( ; i < nopnds; i++ )
1278         if( i == uniq_idx[i] )
1279           uniq_idx[i] = j++;
1280       num_uniq = j;
1281     }
1282   }
1283   _uniq_idx = uniq_idx;
1284   _num_uniq = num_uniq;
1285 }
1286 
1287 // Generate index values needed for determing the operand position
1288 void InstructForm::index_temps(FILE *fp, FormDict &globals, const char *prefix, const char *receiver) {
1289   uint  idx = 0;                  // position of operand in match rule
1290   int   cur_num_opnds = num_opnds();
1291 
1292   // Compute the index into vector of operand pointers:
1293   // idx0=0 is used to indicate that info comes from this same node, not from input edge.
1294   // idx1 starts at oper_input_base()
1295   if ( cur_num_opnds >= 1 ) {
1296     fprintf(fp,"    // Start at oper_input_base() and count operands\n");
1297     fprintf(fp,"    unsigned %sidx0 = %d;\n", prefix, oper_input_base(globals));
1298     fprintf(fp,"    unsigned %sidx1 = %d;\n", prefix, oper_input_base(globals));
1299 
1300     // Generate starting points for other unique operands if they exist
1301     for ( idx = 2; idx < num_unique_opnds(); ++idx ) {
1302       if( *receiver == 0 ) {
1303         fprintf(fp,"    unsigned %sidx%d = %sidx%d + opnd_array(%d)->num_edges();\n",
1304                 prefix, idx, prefix, idx-1, idx-1 );
1305       } else {
1306         fprintf(fp,"    unsigned %sidx%d = %sidx%d + %s_opnds[%d]->num_edges();\n",
1307                 prefix, idx, prefix, idx-1, receiver, idx-1 );
1308       }
1309     }
1310   }
1311   if( *receiver != 0 ) {
1312     // This value is used by generate_peepreplace when copying a node.
1313     // Don't emit it in other cases since it can hide bugs with the
1314     // use invalid idx's.
1315     fprintf(fp,"    unsigned %sidx%d = %sreq(); \n", prefix, idx, receiver);
1316   }
1317 
1318 }
1319 
1320 // ---------------------------
1321 bool InstructForm::verify() {
1322   // !!!!! !!!!!
1323   // Check that a "label" operand occurs last in the operand list, if present
1324   return true;
1325 }
1326 
1327 void InstructForm::dump() {
1328   output(stderr);
1329 }
1330 
1331 void InstructForm::output(FILE *fp) {
1332   fprintf(fp,"\nInstruction: %s\n", (_ident?_ident:""));
1333   if (_matrule)   _matrule->output(fp);
1334   if (_insencode) _insencode->output(fp);
1335   if (_opcode)    _opcode->output(fp);
1336   if (_attribs)   _attribs->output(fp);
1337   if (_predicate) _predicate->output(fp);
1338   if (_effects.Size()) {
1339     fprintf(fp,"Effects\n");
1340     _effects.dump();
1341   }
1342   if (_exprule)   _exprule->output(fp);
1343   if (_rewrule)   _rewrule->output(fp);
1344   if (_format)    _format->output(fp);
1345   if (_peephole)  _peephole->output(fp);
1346 }
1347 
1348 void MachNodeForm::dump() {
1349   output(stderr);
1350 }
1351 
1352 void MachNodeForm::output(FILE *fp) {
1353   fprintf(fp,"\nMachNode: %s\n", (_ident?_ident:""));
1354 }
1355 
1356 //------------------------------build_predicate--------------------------------
1357 // Build instruction predicates.  If the user uses the same operand name
1358 // twice, we need to check that the operands are pointer-eequivalent in
1359 // the DFA during the labeling process.
1360 Predicate *InstructForm::build_predicate() {
1361   char buf[1024], *s=buf;
1362   Dict names(cmpstr,hashstr,Form::arena);       // Map Names to counts
1363 
1364   MatchNode *mnode =
1365     strcmp(_matrule->_opType, "Set") ? _matrule : _matrule->_rChild;
1366   mnode->count_instr_names(names);
1367 
1368   uint first = 1;
1369   // Start with the predicate supplied in the .ad file.
1370   if( _predicate ) {
1371     if( first ) first=0;
1372     strcpy(s,"("); s += strlen(s);
1373     strcpy(s,_predicate->_pred);
1374     s += strlen(s);
1375     strcpy(s,")"); s += strlen(s);
1376   }
1377   for( DictI i(&names); i.test(); ++i ) {
1378     uintptr_t cnt = (uintptr_t)i._value;
1379     if( cnt > 1 ) {             // Need a predicate at all?
1380       assert( cnt == 2, "Unimplemented" );
1381       // Handle many pairs
1382       if( first ) first=0;
1383       else {                    // All tests must pass, so use '&&'
1384         strcpy(s," && ");
1385         s += strlen(s);
1386       }
1387       // Add predicate to working buffer
1388       sprintf(s,"/*%s*/(",(char*)i._key);
1389       s += strlen(s);
1390       mnode->build_instr_pred(s,(char*)i._key,0);
1391       s += strlen(s);
1392       strcpy(s," == "); s += strlen(s);
1393       mnode->build_instr_pred(s,(char*)i._key,1);
1394       s += strlen(s);
1395       strcpy(s,")"); s += strlen(s);
1396     }
1397   }
1398   if( s == buf ) s = NULL;
1399   else {
1400     assert( strlen(buf) < sizeof(buf), "String buffer overflow" );
1401     s = strdup(buf);
1402   }
1403   return new Predicate(s);
1404 }
1405 
1406 //------------------------------EncodeForm-------------------------------------
1407 // Constructor
1408 EncodeForm::EncodeForm()
1409   : _encClass(cmpstr,hashstr, Form::arena) {
1410 }
1411 EncodeForm::~EncodeForm() {
1412 }
1413 
1414 // record a new register class
1415 EncClass *EncodeForm::add_EncClass(const char *className) {
1416   EncClass *encClass = new EncClass(className);
1417   _eclasses.addName(className);
1418   _encClass.Insert(className,encClass);
1419   return encClass;
1420 }
1421 
1422 // Lookup the function body for an encoding class
1423 EncClass  *EncodeForm::encClass(const char *className) {
1424   assert( className != NULL, "Must provide a defined encoding name");
1425 
1426   EncClass *encClass = (EncClass*)_encClass[className];
1427   return encClass;
1428 }
1429 
1430 // Lookup the function body for an encoding class
1431 const char *EncodeForm::encClassBody(const char *className) {
1432   if( className == NULL ) return NULL;
1433 
1434   EncClass *encClass = (EncClass*)_encClass[className];
1435   assert( encClass != NULL, "Encode Class is missing.");
1436   encClass->_code.reset();
1437   const char *code = (const char*)encClass->_code.iter();
1438   assert( code != NULL, "Found an empty encode class body.");
1439 
1440   return code;
1441 }
1442 
1443 // Lookup the function body for an encoding class
1444 const char *EncodeForm::encClassPrototype(const char *className) {
1445   assert( className != NULL, "Encode class name must be non NULL.");
1446 
1447   return className;
1448 }
1449 
1450 void EncodeForm::dump() {                  // Debug printer
1451   output(stderr);
1452 }
1453 
1454 void EncodeForm::output(FILE *fp) {          // Write info to output files
1455   const char *name;
1456   fprintf(fp,"\n");
1457   fprintf(fp,"-------------------- Dump EncodeForm --------------------\n");
1458   for (_eclasses.reset(); (name = _eclasses.iter()) != NULL;) {
1459     ((EncClass*)_encClass[name])->output(fp);
1460   }
1461   fprintf(fp,"-------------------- end  EncodeForm --------------------\n");
1462 }
1463 //------------------------------EncClass---------------------------------------
1464 EncClass::EncClass(const char *name)
1465   : _localNames(cmpstr,hashstr, Form::arena), _name(name) {
1466 }
1467 EncClass::~EncClass() {
1468 }
1469 
1470 // Add a parameter <type,name> pair
1471 void EncClass::add_parameter(const char *parameter_type, const char *parameter_name) {
1472   _parameter_type.addName( parameter_type );
1473   _parameter_name.addName( parameter_name );
1474 }
1475 
1476 // Verify operand types in parameter list
1477 bool EncClass::check_parameter_types(FormDict &globals) {
1478   // !!!!!
1479   return false;
1480 }
1481 
1482 // Add the decomposed "code" sections of an encoding's code-block
1483 void EncClass::add_code(const char *code) {
1484   _code.addName(code);
1485 }
1486 
1487 // Add the decomposed "replacement variables" of an encoding's code-block
1488 void EncClass::add_rep_var(char *replacement_var) {
1489   _code.addName(NameList::_signal);
1490   _rep_vars.addName(replacement_var);
1491 }
1492 
1493 // Lookup the function body for an encoding class
1494 int EncClass::rep_var_index(const char *rep_var) {
1495   uint        position = 0;
1496   const char *name     = NULL;
1497 
1498   _parameter_name.reset();
1499   while ( (name = _parameter_name.iter()) != NULL ) {
1500     if ( strcmp(rep_var,name) == 0 ) return position;
1501     ++position;
1502   }
1503 
1504   return -1;
1505 }
1506 
1507 // Check after parsing
1508 bool EncClass::verify() {
1509   // 1!!!!
1510   // Check that each replacement variable, '$name' in architecture description
1511   // is actually a local variable for this encode class, or a reserved name
1512   // "primary, secondary, tertiary"
1513   return true;
1514 }
1515 
1516 void EncClass::dump() {
1517   output(stderr);
1518 }
1519 
1520 // Write info to output files
1521 void EncClass::output(FILE *fp) {
1522   fprintf(fp,"EncClass: %s", (_name ? _name : ""));
1523 
1524   // Output the parameter list
1525   _parameter_type.reset();
1526   _parameter_name.reset();
1527   const char *type = _parameter_type.iter();
1528   const char *name = _parameter_name.iter();
1529   fprintf(fp, " ( ");
1530   for ( ; (type != NULL) && (name != NULL);
1531         (type = _parameter_type.iter()), (name = _parameter_name.iter()) ) {
1532     fprintf(fp, " %s %s,", type, name);
1533   }
1534   fprintf(fp, " ) ");
1535 
1536   // Output the code block
1537   _code.reset();
1538   _rep_vars.reset();
1539   const char *code;
1540   while ( (code = _code.iter()) != NULL ) {
1541     if ( _code.is_signal(code) ) {
1542       // A replacement variable
1543       const char *rep_var = _rep_vars.iter();
1544       fprintf(fp,"($%s)", rep_var);
1545     } else {
1546       // A section of code
1547       fprintf(fp,"%s", code);
1548     }
1549   }
1550 
1551 }
1552 
1553 //------------------------------Opcode-----------------------------------------
1554 Opcode::Opcode(char *primary, char *secondary, char *tertiary)
1555   : _primary(primary), _secondary(secondary), _tertiary(tertiary) {
1556 }
1557 
1558 Opcode::~Opcode() {
1559 }
1560 
1561 Opcode::opcode_type Opcode::as_opcode_type(const char *param) {
1562   if( strcmp(param,"primary") == 0 ) {
1563     return Opcode::PRIMARY;
1564   }
1565   else if( strcmp(param,"secondary") == 0 ) {
1566     return Opcode::SECONDARY;
1567   }
1568   else if( strcmp(param,"tertiary") == 0 ) {
1569     return Opcode::TERTIARY;
1570   }
1571   return Opcode::NOT_AN_OPCODE;
1572 }
1573 
1574 bool Opcode::print_opcode(FILE *fp, Opcode::opcode_type desired_opcode) {
1575   // Default values previously provided by MachNode::primary()...
1576   const char *description = NULL;
1577   const char *value       = NULL;
1578   // Check if user provided any opcode definitions
1579   if( this != NULL ) {
1580     // Update 'value' if user provided a definition in the instruction
1581     switch (desired_opcode) {
1582     case PRIMARY:
1583       description = "primary()";
1584       if( _primary   != NULL)  { value = _primary;     }
1585       break;
1586     case SECONDARY:
1587       description = "secondary()";
1588       if( _secondary != NULL ) { value = _secondary;   }
1589       break;
1590     case TERTIARY:
1591       description = "tertiary()";
1592       if( _tertiary  != NULL ) { value = _tertiary;    }
1593       break;
1594     default:
1595       assert( false, "ShouldNotReachHere();");
1596       break;
1597     }
1598   }
1599   if (value != NULL) {
1600     fprintf(fp, "(%s /*%s*/)", value, description);
1601   }
1602   return value != NULL;
1603 }
1604 
1605 void Opcode::dump() {
1606   output(stderr);
1607 }
1608 
1609 // Write info to output files
1610 void Opcode::output(FILE *fp) {
1611   if (_primary   != NULL) fprintf(fp,"Primary   opcode: %s\n", _primary);
1612   if (_secondary != NULL) fprintf(fp,"Secondary opcode: %s\n", _secondary);
1613   if (_tertiary  != NULL) fprintf(fp,"Tertiary  opcode: %s\n", _tertiary);
1614 }
1615 
1616 //------------------------------InsEncode--------------------------------------
1617 InsEncode::InsEncode() {
1618 }
1619 InsEncode::~InsEncode() {
1620 }
1621 
1622 // Add "encode class name" and its parameters
1623 NameAndList *InsEncode::add_encode(char *encoding) {
1624   assert( encoding != NULL, "Must provide name for encoding");
1625 
1626   // add_parameter(NameList::_signal);
1627   NameAndList *encode = new NameAndList(encoding);
1628   _encoding.addName((char*)encode);
1629 
1630   return encode;
1631 }
1632 
1633 // Access the list of encodings
1634 void InsEncode::reset() {
1635   _encoding.reset();
1636   // _parameter.reset();
1637 }
1638 const char* InsEncode::encode_class_iter() {
1639   NameAndList  *encode_class = (NameAndList*)_encoding.iter();
1640   return  ( encode_class != NULL ? encode_class->name() : NULL );
1641 }
1642 // Obtain parameter name from zero based index
1643 const char *InsEncode::rep_var_name(InstructForm &inst, uint param_no) {
1644   NameAndList *params = (NameAndList*)_encoding.current();
1645   assert( params != NULL, "Internal Error");
1646   const char *param = (*params)[param_no];
1647 
1648   // Remove '$' if parser placed it there.
1649   return ( param != NULL && *param == '$') ? (param+1) : param;
1650 }
1651 
1652 void InsEncode::dump() {
1653   output(stderr);
1654 }
1655 
1656 // Write info to output files
1657 void InsEncode::output(FILE *fp) {
1658   NameAndList *encoding  = NULL;
1659   const char  *parameter = NULL;
1660 
1661   fprintf(fp,"InsEncode: ");
1662   _encoding.reset();
1663 
1664   while ( (encoding = (NameAndList*)_encoding.iter()) != 0 ) {
1665     // Output the encoding being used
1666     fprintf(fp,"%s(", encoding->name() );
1667 
1668     // Output its parameter list, if any
1669     bool first_param = true;
1670     encoding->reset();
1671     while (  (parameter = encoding->iter()) != 0 ) {
1672       // Output the ',' between parameters
1673       if ( ! first_param )  fprintf(fp,", ");
1674       first_param = false;
1675       // Output the parameter
1676       fprintf(fp,"%s", parameter);
1677     } // done with parameters
1678     fprintf(fp,")  ");
1679   } // done with encodings
1680 
1681   fprintf(fp,"\n");
1682 }
1683 
1684 //------------------------------Effect-----------------------------------------
1685 static int effect_lookup(const char *name) {
1686   if(!strcmp(name, "USE")) return Component::USE;
1687   if(!strcmp(name, "DEF")) return Component::DEF;
1688   if(!strcmp(name, "USE_DEF")) return Component::USE_DEF;
1689   if(!strcmp(name, "KILL")) return Component::KILL;
1690   if(!strcmp(name, "USE_KILL")) return Component::USE_KILL;
1691   if(!strcmp(name, "TEMP")) return Component::TEMP;
1692   if(!strcmp(name, "INVALID")) return Component::INVALID;
1693   assert( false,"Invalid effect name specified\n");
1694   return Component::INVALID;
1695 }
1696 
1697 Effect::Effect(const char *name) : _name(name), _use_def(effect_lookup(name)) {
1698   _ftype = Form::EFF;
1699 }
1700 Effect::~Effect() {
1701 }
1702 
1703 // Dynamic type check
1704 Effect *Effect::is_effect() const {
1705   return (Effect*)this;
1706 }
1707 
1708 
1709 // True if this component is equal to the parameter.
1710 bool Effect::is(int use_def_kill_enum) const {
1711   return (_use_def == use_def_kill_enum ? true : false);
1712 }
1713 // True if this component is used/def'd/kill'd as the parameter suggests.
1714 bool Effect::isa(int use_def_kill_enum) const {
1715   return (_use_def & use_def_kill_enum) == use_def_kill_enum;
1716 }
1717 
1718 void Effect::dump() {
1719   output(stderr);
1720 }
1721 
1722 void Effect::output(FILE *fp) {          // Write info to output files
1723   fprintf(fp,"Effect: %s\n", (_name?_name:""));
1724 }
1725 
1726 //------------------------------ExpandRule-------------------------------------
1727 ExpandRule::ExpandRule() : _expand_instrs(),
1728                            _newopconst(cmpstr, hashstr, Form::arena) {
1729   _ftype = Form::EXP;
1730 }
1731 
1732 ExpandRule::~ExpandRule() {                  // Destructor
1733 }
1734 
1735 void ExpandRule::add_instruction(NameAndList *instruction_name_and_operand_list) {
1736   _expand_instrs.addName((char*)instruction_name_and_operand_list);
1737 }
1738 
1739 void ExpandRule::reset_instructions() {
1740   _expand_instrs.reset();
1741 }
1742 
1743 NameAndList* ExpandRule::iter_instructions() {
1744   return (NameAndList*)_expand_instrs.iter();
1745 }
1746 
1747 
1748 void ExpandRule::dump() {
1749   output(stderr);
1750 }
1751 
1752 void ExpandRule::output(FILE *fp) {         // Write info to output files
1753   NameAndList *expand_instr = NULL;
1754   const char *opid = NULL;
1755 
1756   fprintf(fp,"\nExpand Rule:\n");
1757 
1758   // Iterate over the instructions 'node' expands into
1759   for(reset_instructions(); (expand_instr = iter_instructions()) != NULL; ) {
1760     fprintf(fp,"%s(", expand_instr->name());
1761 
1762     // iterate over the operand list
1763     for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
1764       fprintf(fp,"%s ", opid);
1765     }
1766     fprintf(fp,");\n");
1767   }
1768 }
1769 
1770 //------------------------------RewriteRule------------------------------------
1771 RewriteRule::RewriteRule(char* params, char* block)
1772   : _tempParams(params), _tempBlock(block) { };  // Constructor
1773 RewriteRule::~RewriteRule() {                 // Destructor
1774 }
1775 
1776 void RewriteRule::dump() {
1777   output(stderr);
1778 }
1779 
1780 void RewriteRule::output(FILE *fp) {         // Write info to output files
1781   fprintf(fp,"\nRewrite Rule:\n%s\n%s\n",
1782           (_tempParams?_tempParams:""),
1783           (_tempBlock?_tempBlock:""));
1784 }
1785 
1786 
1787 //==============================MachNodes======================================
1788 //------------------------------MachNodeForm-----------------------------------
1789 MachNodeForm::MachNodeForm(char *id)
1790   : _ident(id) {
1791 }
1792 
1793 MachNodeForm::~MachNodeForm() {
1794 }
1795 
1796 MachNodeForm *MachNodeForm::is_machnode() const {
1797   return (MachNodeForm*)this;
1798 }
1799 
1800 //==============================Operand Classes================================
1801 //------------------------------OpClassForm------------------------------------
1802 OpClassForm::OpClassForm(const char* id) : _ident(id) {
1803   _ftype = Form::OPCLASS;
1804 }
1805 
1806 OpClassForm::~OpClassForm() {
1807 }
1808 
1809 bool OpClassForm::ideal_only() const { return 0; }
1810 
1811 OpClassForm *OpClassForm::is_opclass() const {
1812   return (OpClassForm*)this;
1813 }
1814 
1815 Form::InterfaceType OpClassForm::interface_type(FormDict &globals) const {
1816   if( _oplst.count() == 0 ) return Form::no_interface;
1817 
1818   // Check that my operands have the same interface type
1819   Form::InterfaceType  interface;
1820   bool  first = true;
1821   NameList &op_list = (NameList &)_oplst;
1822   op_list.reset();
1823   const char *op_name;
1824   while( (op_name = op_list.iter()) != NULL ) {
1825     const Form  *form    = globals[op_name];
1826     OperandForm *operand = form->is_operand();
1827     assert( operand, "Entry in operand class that is not an operand");
1828     if( first ) {
1829       first     = false;
1830       interface = operand->interface_type(globals);
1831     } else {
1832       interface = (interface == operand->interface_type(globals) ? interface : Form::no_interface);
1833     }
1834   }
1835   return interface;
1836 }
1837 
1838 bool OpClassForm::stack_slots_only(FormDict &globals) const {
1839   if( _oplst.count() == 0 ) return false;  // how?
1840 
1841   NameList &op_list = (NameList &)_oplst;
1842   op_list.reset();
1843   const char *op_name;
1844   while( (op_name = op_list.iter()) != NULL ) {
1845     const Form  *form    = globals[op_name];
1846     OperandForm *operand = form->is_operand();
1847     assert( operand, "Entry in operand class that is not an operand");
1848     if( !operand->stack_slots_only(globals) )  return false;
1849   }
1850   return true;
1851 }
1852 
1853 
1854 void OpClassForm::dump() {
1855   output(stderr);
1856 }
1857 
1858 void OpClassForm::output(FILE *fp) {
1859   const char *name;
1860   fprintf(fp,"\nOperand Class: %s\n", (_ident?_ident:""));
1861   fprintf(fp,"\nCount = %d\n", _oplst.count());
1862   for(_oplst.reset(); (name = _oplst.iter()) != NULL;) {
1863     fprintf(fp,"%s, ",name);
1864   }
1865   fprintf(fp,"\n");
1866 }
1867 
1868 
1869 //==============================Operands=======================================
1870 //------------------------------OperandForm------------------------------------
1871 OperandForm::OperandForm(const char* id)
1872   : OpClassForm(id), _ideal_only(false),
1873     _localNames(cmpstr, hashstr, Form::arena) {
1874       _ftype = Form::OPER;
1875 
1876       _matrule   = NULL;
1877       _interface = NULL;
1878       _attribs   = NULL;
1879       _predicate = NULL;
1880       _constraint= NULL;
1881       _construct = NULL;
1882       _format    = NULL;
1883 }
1884 OperandForm::OperandForm(const char* id, bool ideal_only)
1885   : OpClassForm(id), _ideal_only(ideal_only),
1886     _localNames(cmpstr, hashstr, Form::arena) {
1887       _ftype = Form::OPER;
1888 
1889       _matrule   = NULL;
1890       _interface = NULL;
1891       _attribs   = NULL;
1892       _predicate = NULL;
1893       _constraint= NULL;
1894       _construct = NULL;
1895       _format    = NULL;
1896 }
1897 OperandForm::~OperandForm() {
1898 }
1899 
1900 
1901 OperandForm *OperandForm::is_operand() const {
1902   return (OperandForm*)this;
1903 }
1904 
1905 bool OperandForm::ideal_only() const {
1906   return _ideal_only;
1907 }
1908 
1909 Form::InterfaceType OperandForm::interface_type(FormDict &globals) const {
1910   if( _interface == NULL )  return Form::no_interface;
1911 
1912   return _interface->interface_type(globals);
1913 }
1914 
1915 
1916 bool OperandForm::stack_slots_only(FormDict &globals) const {
1917   if( _constraint == NULL )  return false;
1918   return _constraint->stack_slots_only();
1919 }
1920 
1921 
1922 // Access op_cost attribute or return NULL.
1923 const char* OperandForm::cost() {
1924   for (Attribute* cur = _attribs; cur != NULL; cur = (Attribute*)cur->_next) {
1925     if( strcmp(cur->_ident,AttributeForm::_op_cost) == 0 ) {
1926       return cur->_val;
1927     }
1928   }
1929   return NULL;
1930 }
1931 
1932 // Return the number of leaves below this complex operand
1933 uint OperandForm::num_leaves() const {
1934   if ( ! _matrule) return 0;
1935 
1936   int num_leaves = _matrule->_numleaves;
1937   return num_leaves;
1938 }
1939 
1940 // Return the number of constants contained within this complex operand
1941 uint OperandForm::num_consts(FormDict &globals) const {
1942   if ( ! _matrule) return 0;
1943 
1944   // This is a recursive invocation on all operands in the matchrule
1945   return _matrule->num_consts(globals);
1946 }
1947 
1948 // Return the number of constants in match rule with specified type
1949 uint OperandForm::num_consts(FormDict &globals, Form::DataType type) const {
1950   if ( ! _matrule) return 0;
1951 
1952   // This is a recursive invocation on all operands in the matchrule
1953   return _matrule->num_consts(globals, type);
1954 }
1955 
1956 // Return the number of pointer constants contained within this complex operand
1957 uint OperandForm::num_const_ptrs(FormDict &globals) const {
1958   if ( ! _matrule) return 0;
1959 
1960   // This is a recursive invocation on all operands in the matchrule
1961   return _matrule->num_const_ptrs(globals);
1962 }
1963 
1964 uint OperandForm::num_edges(FormDict &globals) const {
1965   uint edges  = 0;
1966   uint leaves = num_leaves();
1967   uint consts = num_consts(globals);
1968 
1969   // If we are matching a constant directly, there are no leaves.
1970   edges = ( leaves > consts ) ? leaves - consts : 0;
1971 
1972   // !!!!!
1973   // Special case operands that do not have a corresponding ideal node.
1974   if( (edges == 0) && (consts == 0) ) {
1975     if( constrained_reg_class() != NULL ) {
1976       edges = 1;
1977     } else {
1978       if( _matrule
1979           && (_matrule->_lChild == NULL) && (_matrule->_rChild == NULL) ) {
1980         const Form *form = globals[_matrule->_opType];
1981         OperandForm *oper = form ? form->is_operand() : NULL;
1982         if( oper ) {
1983           return oper->num_edges(globals);
1984         }
1985       }
1986     }
1987   }
1988 
1989   return edges;
1990 }
1991 
1992 
1993 // Check if this operand is usable for cisc-spilling
1994 bool  OperandForm::is_cisc_reg(FormDict &globals) const {
1995   const char *ideal = ideal_type(globals);
1996   bool is_cisc_reg = (ideal && (ideal_to_Reg_type(ideal) != none));
1997   return is_cisc_reg;
1998 }
1999 
2000 bool  OpClassForm::is_cisc_mem(FormDict &globals) const {
2001   Form::InterfaceType my_interface = interface_type(globals);
2002   return (my_interface == memory_interface);
2003 }
2004 
2005 
2006 // node matches ideal 'Bool'
2007 bool OperandForm::is_ideal_bool() const {
2008   if( _matrule == NULL ) return false;
2009 
2010   return _matrule->is_ideal_bool();
2011 }
2012 
2013 // Require user's name for an sRegX to be stackSlotX
2014 Form::DataType OperandForm::is_user_name_for_sReg() const {
2015   DataType data_type = none;
2016   if( _ident != NULL ) {
2017     if(      strcmp(_ident,"stackSlotI") == 0 ) data_type = Form::idealI;
2018     else if( strcmp(_ident,"stackSlotP") == 0 ) data_type = Form::idealP;
2019     else if( strcmp(_ident,"stackSlotD") == 0 ) data_type = Form::idealD;
2020     else if( strcmp(_ident,"stackSlotF") == 0 ) data_type = Form::idealF;
2021     else if( strcmp(_ident,"stackSlotL") == 0 ) data_type = Form::idealL;
2022   }
2023   assert((data_type == none) || (_matrule == NULL), "No match-rule for stackSlotX");
2024 
2025   return data_type;
2026 }
2027 
2028 
2029 // Return ideal type, if there is a single ideal type for this operand
2030 const char *OperandForm::ideal_type(FormDict &globals, RegisterForm *registers) const {
2031   const char *type = NULL;
2032   if (ideal_only()) type = _ident;
2033   else if( _matrule == NULL ) {
2034     // Check for condition code register
2035     const char *rc_name = constrained_reg_class();
2036     // !!!!!
2037     if (rc_name == NULL) return NULL;
2038     // !!!!! !!!!!
2039     // Check constraints on result's register class
2040     if( registers ) {
2041       RegClass *reg_class  = registers->getRegClass(rc_name);
2042       assert( reg_class != NULL, "Register class is not defined");
2043 
2044       // Check for ideal type of entries in register class, all are the same type
2045       reg_class->reset();
2046       RegDef *reg_def = reg_class->RegDef_iter();
2047       assert( reg_def != NULL, "No entries in register class");
2048       assert( reg_def->_idealtype != NULL, "Did not define ideal type for register");
2049       // Return substring that names the register's ideal type
2050       type = reg_def->_idealtype + 3;
2051       assert( *(reg_def->_idealtype + 0) == 'O', "Expect Op_ prefix");
2052       assert( *(reg_def->_idealtype + 1) == 'p', "Expect Op_ prefix");
2053       assert( *(reg_def->_idealtype + 2) == '_', "Expect Op_ prefix");
2054     }
2055   }
2056   else if( _matrule->_lChild == NULL && _matrule->_rChild == NULL ) {
2057     // This operand matches a single type, at the top level.
2058     // Check for ideal type
2059     type = _matrule->_opType;
2060     if( strcmp(type,"Bool") == 0 )
2061       return "Bool";
2062     // transitive lookup
2063     const Form *frm = globals[type];
2064     OperandForm *op = frm->is_operand();
2065     type = op->ideal_type(globals, registers);
2066   }
2067   return type;
2068 }
2069 
2070 
2071 // If there is a single ideal type for this interface field, return it.
2072 const char *OperandForm::interface_ideal_type(FormDict &globals,
2073                                               const char *field) const {
2074   const char  *ideal_type = NULL;
2075   const char  *value      = NULL;
2076 
2077   // Check if "field" is valid for this operand's interface
2078   if ( ! is_interface_field(field, value) )   return ideal_type;
2079 
2080   // !!!!! !!!!! !!!!!
2081   // If a valid field has a constant value, identify "ConI" or "ConP" or ...
2082 
2083   // Else, lookup type of field's replacement variable
2084 
2085   return ideal_type;
2086 }
2087 
2088 
2089 RegClass* OperandForm::get_RegClass() const {
2090   if (_interface && !_interface->is_RegInterface()) return NULL;
2091   return globalAD->get_registers()->getRegClass(constrained_reg_class());
2092 }
2093 
2094 
2095 bool OperandForm::is_bound_register() const {
2096   RegClass *reg_class  = get_RegClass();
2097   if (reg_class == NULL) return false;
2098 
2099   const char * name = ideal_type(globalAD->globalNames());
2100   if (name == NULL) return false;
2101 
2102   int size = 0;
2103   if (strcmp(name,"RegFlags")==0) size =  1;
2104   if (strcmp(name,"RegI")==0) size =  1;
2105   if (strcmp(name,"RegF")==0) size =  1;
2106   if (strcmp(name,"RegD")==0) size =  2;
2107   if (strcmp(name,"RegL")==0) size =  2;
2108   if (strcmp(name,"RegN")==0) size =  1;
2109   if (strcmp(name,"RegP")==0) size =  globalAD->get_preproc_def("_LP64") ? 2 : 1;
2110   if (size == 0) return false;
2111   return size == reg_class->size();
2112 }
2113 
2114 
2115 // Check if this is a valid field for this operand,
2116 // Return 'true' if valid, and set the value to the string the user provided.
2117 bool  OperandForm::is_interface_field(const char *field,
2118                                       const char * &value) const {
2119   return false;
2120 }
2121 
2122 
2123 // Return register class name if a constraint specifies the register class.
2124 const char *OperandForm::constrained_reg_class() const {
2125   const char *reg_class  = NULL;
2126   if ( _constraint ) {
2127     // !!!!!
2128     Constraint *constraint = _constraint;
2129     if ( strcmp(_constraint->_func,"ALLOC_IN_RC") == 0 ) {
2130       reg_class = _constraint->_arg;
2131     }
2132   }
2133 
2134   return reg_class;
2135 }
2136 
2137 
2138 // Return the register class associated with 'leaf'.
2139 const char *OperandForm::in_reg_class(uint leaf, FormDict &globals) {
2140   const char *reg_class = NULL; // "RegMask::Empty";
2141 
2142   if((_matrule == NULL) || (_matrule->is_chain_rule(globals))) {
2143     reg_class = constrained_reg_class();
2144     return reg_class;
2145   }
2146   const char *result   = NULL;
2147   const char *name     = NULL;
2148   const char *type     = NULL;
2149   // iterate through all base operands
2150   // until we reach the register that corresponds to "leaf"
2151   // This function is not looking for an ideal type.  It needs the first
2152   // level user type associated with the leaf.
2153   for(uint idx = 0;_matrule->base_operand(idx,globals,result,name,type);++idx) {
2154     const Form *form = (_localNames[name] ? _localNames[name] : globals[result]);
2155     OperandForm *oper = form ? form->is_operand() : NULL;
2156     if( oper ) {
2157       reg_class = oper->constrained_reg_class();
2158       if( reg_class ) {
2159         reg_class = reg_class;
2160       } else {
2161         // ShouldNotReachHere();
2162       }
2163     } else {
2164       // ShouldNotReachHere();
2165     }
2166 
2167     // Increment our target leaf position if current leaf is not a candidate.
2168     if( reg_class == NULL)    ++leaf;
2169     // Exit the loop with the value of reg_class when at the correct index
2170     if( idx == leaf )         break;
2171     // May iterate through all base operands if reg_class for 'leaf' is NULL
2172   }
2173   return reg_class;
2174 }
2175 
2176 
2177 // Recursive call to construct list of top-level operands.
2178 // Implementation does not modify state of internal structures
2179 void OperandForm::build_components() {
2180   if (_matrule)  _matrule->append_components(_localNames, _components);
2181 
2182   // Add parameters that "do not appear in match rule".
2183   const char *name;
2184   for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
2185     OperandForm *opForm = (OperandForm*)_localNames[name];
2186 
2187     if ( _components.operand_position(name) == -1 ) {
2188       _components.insert(name, opForm->_ident, Component::INVALID, false);
2189     }
2190   }
2191 
2192   return;
2193 }
2194 
2195 int OperandForm::operand_position(const char *name, int usedef) {
2196   return _components.operand_position(name, usedef);
2197 }
2198 
2199 
2200 // Return zero-based position in component list, only counting constants;
2201 // Return -1 if not in list.
2202 int OperandForm::constant_position(FormDict &globals, const Component *last) {
2203   // Iterate through components and count constants preceeding 'constant'
2204   uint  position = 0;
2205   Component *comp;
2206   _components.reset();
2207   while( (comp = _components.iter()) != NULL  && (comp != last) ) {
2208     // Special case for operands that take a single user-defined operand
2209     // Skip the initial definition in the component list.
2210     if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2211 
2212     const char *type = comp->_type;
2213     // Lookup operand form for replacement variable's type
2214     const Form *form = globals[type];
2215     assert( form != NULL, "Component's type not found");
2216     OperandForm *oper = form ? form->is_operand() : NULL;
2217     if( oper ) {
2218       if( oper->_matrule->is_base_constant(globals) != Form::none ) {
2219         ++position;
2220       }
2221     }
2222   }
2223 
2224   // Check for being passed a component that was not in the list
2225   if( comp != last )  position = -1;
2226 
2227   return position;
2228 }
2229 // Provide position of constant by "name"
2230 int OperandForm::constant_position(FormDict &globals, const char *name) {
2231   const Component *comp = _components.search(name);
2232   int idx = constant_position( globals, comp );
2233 
2234   return idx;
2235 }
2236 
2237 
2238 // Return zero-based position in component list, only counting constants;
2239 // Return -1 if not in list.
2240 int OperandForm::register_position(FormDict &globals, const char *reg_name) {
2241   // Iterate through components and count registers preceeding 'last'
2242   uint  position = 0;
2243   Component *comp;
2244   _components.reset();
2245   while( (comp = _components.iter()) != NULL
2246          && (strcmp(comp->_name,reg_name) != 0) ) {
2247     // Special case for operands that take a single user-defined operand
2248     // Skip the initial definition in the component list.
2249     if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2250 
2251     const char *type = comp->_type;
2252     // Lookup operand form for component's type
2253     const Form *form = globals[type];
2254     assert( form != NULL, "Component's type not found");
2255     OperandForm *oper = form ? form->is_operand() : NULL;
2256     if( oper ) {
2257       if( oper->_matrule->is_base_register(globals) ) {
2258         ++position;
2259       }
2260     }
2261   }
2262 
2263   return position;
2264 }
2265 
2266 
2267 const char *OperandForm::reduce_result()  const {
2268   return _ident;
2269 }
2270 // Return the name of the operand on the right hand side of the binary match
2271 // Return NULL if there is no right hand side
2272 const char *OperandForm::reduce_right(FormDict &globals)  const {
2273   return  ( _matrule ? _matrule->reduce_right(globals) : NULL );
2274 }
2275 
2276 // Similar for left
2277 const char *OperandForm::reduce_left(FormDict &globals)   const {
2278   return  ( _matrule ? _matrule->reduce_left(globals) : NULL );
2279 }
2280 
2281 
2282 // --------------------------- FILE *output_routines
2283 //
2284 // Output code for disp_is_oop, if true.
2285 void OperandForm::disp_is_oop(FILE *fp, FormDict &globals) {
2286   //  Check it is a memory interface with a non-user-constant disp field
2287   if ( this->_interface == NULL ) return;
2288   MemInterface *mem_interface = this->_interface->is_MemInterface();
2289   if ( mem_interface == NULL )    return;
2290   const char   *disp  = mem_interface->_disp;
2291   if ( *disp != '$' )             return;
2292 
2293   // Lookup replacement variable in operand's component list
2294   const char   *rep_var = disp + 1;
2295   const Component *comp = this->_components.search(rep_var);
2296   assert( comp != NULL, "Replacement variable not found in components");
2297   // Lookup operand form for replacement variable's type
2298   const char      *type = comp->_type;
2299   Form            *form = (Form*)globals[type];
2300   assert( form != NULL, "Replacement variable's type not found");
2301   OperandForm     *op   = form->is_operand();
2302   assert( op, "Memory Interface 'disp' can only emit an operand form");
2303   // Check if this is a ConP, which may require relocation
2304   if ( op->is_base_constant(globals) == Form::idealP ) {
2305     // Find the constant's index:  _c0, _c1, _c2, ... , _cN
2306     uint idx  = op->constant_position( globals, rep_var);
2307     fprintf(fp,"  virtual bool disp_is_oop() const {", _ident);
2308     fprintf(fp,  "  return _c%d->isa_oop_ptr();", idx);
2309     fprintf(fp, " }\n");
2310   }
2311 }
2312 
2313 // Generate code for internal and external format methods
2314 //
2315 // internal access to reg# node->_idx
2316 // access to subsumed constant _c0, _c1,
2317 void  OperandForm::int_format(FILE *fp, FormDict &globals, uint index) {
2318   Form::DataType dtype;
2319   if (_matrule && (_matrule->is_base_register(globals) ||
2320                    strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2321     // !!!!! !!!!!
2322     fprintf(fp,    "{ char reg_str[128];\n");
2323     fprintf(fp,"      ra->dump_register(node,reg_str);\n");
2324     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2325     fprintf(fp,"    }\n");
2326   } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2327     format_constant( fp, index, dtype );
2328   } else if (ideal_to_sReg_type(_ident) != Form::none) {
2329     // Special format for Stack Slot Register
2330     fprintf(fp,    "{ char reg_str[128];\n");
2331     fprintf(fp,"      ra->dump_register(node,reg_str);\n");
2332     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2333     fprintf(fp,"    }\n");
2334   } else {
2335     fprintf(fp,"tty->print(\"No format defined for %s\n\");\n", _ident);
2336     fflush(fp);
2337     fprintf(stderr,"No format defined for %s\n", _ident);
2338     dump();
2339     assert( false,"Internal error:\n  output_internal_operand() attempting to output other than a Register or Constant");
2340   }
2341 }
2342 
2343 // Similar to "int_format" but for cases where data is external to operand
2344 // external access to reg# node->in(idx)->_idx,
2345 void  OperandForm::ext_format(FILE *fp, FormDict &globals, uint index) {
2346   Form::DataType dtype;
2347   if (_matrule && (_matrule->is_base_register(globals) ||
2348                    strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2349     fprintf(fp,    "{ char reg_str[128];\n");
2350     fprintf(fp,"      ra->dump_register(node->in(idx");
2351     if ( index != 0 ) fprintf(fp,                  "+%d",index);
2352     fprintf(fp,                                       "),reg_str);\n");
2353     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2354     fprintf(fp,"    }\n");
2355   } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2356     format_constant( fp, index, dtype );
2357   } else if (ideal_to_sReg_type(_ident) != Form::none) {
2358     // Special format for Stack Slot Register
2359     fprintf(fp,    "{ char reg_str[128];\n");
2360     fprintf(fp,"      ra->dump_register(node->in(idx");
2361     if ( index != 0 ) fprintf(fp,                  "+%d",index);
2362     fprintf(fp,                                       "),reg_str);\n");
2363     fprintf(fp,"      tty->print(\"%cs\",reg_str);\n",'%');
2364     fprintf(fp,"    }\n");
2365   } else {
2366     fprintf(fp,"tty->print(\"No format defined for %s\n\");\n", _ident);
2367     assert( false,"Internal error:\n  output_external_operand() attempting to output other than a Register or Constant");
2368   }
2369 }
2370 
2371 void OperandForm::format_constant(FILE *fp, uint const_index, uint const_type) {
2372   switch(const_type) {
2373   case Form::idealI:  fprintf(fp,"st->print(\"#%%d\", _c%d);\n", const_index); break;
2374   case Form::idealP:  fprintf(fp,"_c%d->dump_on(st);\n",         const_index); break;
2375   case Form::idealN:  fprintf(fp,"_c%d->dump_on(st);\n",         const_index); break;
2376   case Form::idealL:  fprintf(fp,"st->print(\"#%%lld\", _c%d);\n", const_index); break;
2377   case Form::idealF:  fprintf(fp,"st->print(\"#%%f\", _c%d);\n", const_index); break;
2378   case Form::idealD:  fprintf(fp,"st->print(\"#%%f\", _c%d);\n", const_index); break;
2379   default:
2380     assert( false, "ShouldNotReachHere()");
2381   }
2382 }
2383 
2384 // Return the operand form corresponding to the given index, else NULL.
2385 OperandForm *OperandForm::constant_operand(FormDict &globals,
2386                                            uint      index) {
2387   // !!!!!
2388   // Check behavior on complex operands
2389   uint n_consts = num_consts(globals);
2390   if( n_consts > 0 ) {
2391     uint i = 0;
2392     const char *type;
2393     Component  *comp;
2394     _components.reset();
2395     if ((comp = _components.iter()) == NULL) {
2396       assert(n_consts == 1, "Bad component list detected.\n");
2397       // Current operand is THE operand
2398       if ( index == 0 ) {
2399         return this;
2400       }
2401     } // end if NULL
2402     else {
2403       // Skip the first component, it can not be a DEF of a constant
2404       do {
2405         type = comp->base_type(globals);
2406         // Check that "type" is a 'ConI', 'ConP', ...
2407         if ( ideal_to_const_type(type) != Form::none ) {
2408           // When at correct component, get corresponding Operand
2409           if ( index == 0 ) {
2410             return globals[comp->_type]->is_operand();
2411           }
2412           // Decrement number of constants to go
2413           --index;
2414         }
2415       } while((comp = _components.iter()) != NULL);
2416     }
2417   }
2418 
2419   // Did not find a constant for this index.
2420   return NULL;
2421 }
2422 
2423 // If this operand has a single ideal type, return its type
2424 Form::DataType OperandForm::simple_type(FormDict &globals) const {
2425   const char *type_name = ideal_type(globals);
2426   Form::DataType type   = type_name ? ideal_to_const_type( type_name )
2427                                     : Form::none;
2428   return type;
2429 }
2430 
2431 Form::DataType OperandForm::is_base_constant(FormDict &globals) const {
2432   if ( _matrule == NULL )    return Form::none;
2433 
2434   return _matrule->is_base_constant(globals);
2435 }
2436 
2437 // "true" if this operand is a simple type that is swallowed
2438 bool  OperandForm::swallowed(FormDict &globals) const {
2439   Form::DataType type   = simple_type(globals);
2440   if( type != Form::none ) {
2441     return true;
2442   }
2443 
2444   return false;
2445 }
2446 
2447 // Output code to access the value of the index'th constant
2448 void OperandForm::access_constant(FILE *fp, FormDict &globals,
2449                                   uint const_index) {
2450   OperandForm *oper = constant_operand(globals, const_index);
2451   assert( oper, "Index exceeds number of constants in operand");
2452   Form::DataType dtype = oper->is_base_constant(globals);
2453 
2454   switch(dtype) {
2455   case idealI: fprintf(fp,"_c%d",           const_index); break;
2456   case idealP: fprintf(fp,"_c%d->get_con()",const_index); break;
2457   case idealL: fprintf(fp,"_c%d",           const_index); break;
2458   case idealF: fprintf(fp,"_c%d",           const_index); break;
2459   case idealD: fprintf(fp,"_c%d",           const_index); break;
2460   default:
2461     assert( false, "ShouldNotReachHere()");
2462   }
2463 }
2464 
2465 
2466 void OperandForm::dump() {
2467   output(stderr);
2468 }
2469 
2470 void OperandForm::output(FILE *fp) {
2471   fprintf(fp,"\nOperand: %s\n", (_ident?_ident:""));
2472   if (_matrule)    _matrule->dump();
2473   if (_interface)  _interface->dump();
2474   if (_attribs)    _attribs->dump();
2475   if (_predicate)  _predicate->dump();
2476   if (_constraint) _constraint->dump();
2477   if (_construct)  _construct->dump();
2478   if (_format)     _format->dump();
2479 }
2480 
2481 //------------------------------Constraint-------------------------------------
2482 Constraint::Constraint(const char *func, const char *arg)
2483   : _func(func), _arg(arg) {
2484 }
2485 Constraint::~Constraint() { /* not owner of char* */
2486 }
2487 
2488 bool Constraint::stack_slots_only() const {
2489   return strcmp(_func, "ALLOC_IN_RC") == 0
2490       && strcmp(_arg,  "stack_slots") == 0;
2491 }
2492 
2493 void Constraint::dump() {
2494   output(stderr);
2495 }
2496 
2497 void Constraint::output(FILE *fp) {           // Write info to output files
2498   assert((_func != NULL && _arg != NULL),"missing constraint function or arg");
2499   fprintf(fp,"Constraint: %s ( %s )\n", _func, _arg);
2500 }
2501 
2502 //------------------------------Predicate--------------------------------------
2503 Predicate::Predicate(char *pr)
2504   : _pred(pr) {
2505 }
2506 Predicate::~Predicate() {
2507 }
2508 
2509 void Predicate::dump() {
2510   output(stderr);
2511 }
2512 
2513 void Predicate::output(FILE *fp) {
2514   fprintf(fp,"Predicate");  // Write to output files
2515 }
2516 //------------------------------Interface--------------------------------------
2517 Interface::Interface(const char *name) : _name(name) {
2518 }
2519 Interface::~Interface() {
2520 }
2521 
2522 Form::InterfaceType Interface::interface_type(FormDict &globals) const {
2523   Interface *thsi = (Interface*)this;
2524   if ( thsi->is_RegInterface()   ) return Form::register_interface;
2525   if ( thsi->is_MemInterface()   ) return Form::memory_interface;
2526   if ( thsi->is_ConstInterface() ) return Form::constant_interface;
2527   if ( thsi->is_CondInterface()  ) return Form::conditional_interface;
2528 
2529   return Form::no_interface;
2530 }
2531 
2532 RegInterface   *Interface::is_RegInterface() {
2533   if ( strcmp(_name,"REG_INTER") != 0 )
2534     return NULL;
2535   return (RegInterface*)this;
2536 }
2537 MemInterface   *Interface::is_MemInterface() {
2538   if ( strcmp(_name,"MEMORY_INTER") != 0 )  return NULL;
2539   return (MemInterface*)this;
2540 }
2541 ConstInterface *Interface::is_ConstInterface() {
2542   if ( strcmp(_name,"CONST_INTER") != 0 )  return NULL;
2543   return (ConstInterface*)this;
2544 }
2545 CondInterface  *Interface::is_CondInterface() {
2546   if ( strcmp(_name,"COND_INTER") != 0 )  return NULL;
2547   return (CondInterface*)this;
2548 }
2549 
2550 
2551 void Interface::dump() {
2552   output(stderr);
2553 }
2554 
2555 // Write info to output files
2556 void Interface::output(FILE *fp) {
2557   fprintf(fp,"Interface: %s\n", (_name ? _name : "") );
2558 }
2559 
2560 //------------------------------RegInterface-----------------------------------
2561 RegInterface::RegInterface() : Interface("REG_INTER") {
2562 }
2563 RegInterface::~RegInterface() {
2564 }
2565 
2566 void RegInterface::dump() {
2567   output(stderr);
2568 }
2569 
2570 // Write info to output files
2571 void RegInterface::output(FILE *fp) {
2572   Interface::output(fp);
2573 }
2574 
2575 //------------------------------ConstInterface---------------------------------
2576 ConstInterface::ConstInterface() : Interface("CONST_INTER") {
2577 }
2578 ConstInterface::~ConstInterface() {
2579 }
2580 
2581 void ConstInterface::dump() {
2582   output(stderr);
2583 }
2584 
2585 // Write info to output files
2586 void ConstInterface::output(FILE *fp) {
2587   Interface::output(fp);
2588 }
2589 
2590 //------------------------------MemInterface-----------------------------------
2591 MemInterface::MemInterface(char *base, char *index, char *scale, char *disp)
2592   : Interface("MEMORY_INTER"), _base(base), _index(index), _scale(scale), _disp(disp) {
2593 }
2594 MemInterface::~MemInterface() {
2595   // not owner of any character arrays
2596 }
2597 
2598 void MemInterface::dump() {
2599   output(stderr);
2600 }
2601 
2602 // Write info to output files
2603 void MemInterface::output(FILE *fp) {
2604   Interface::output(fp);
2605   if ( _base  != NULL ) fprintf(fp,"  base  == %s\n", _base);
2606   if ( _index != NULL ) fprintf(fp,"  index == %s\n", _index);
2607   if ( _scale != NULL ) fprintf(fp,"  scale == %s\n", _scale);
2608   if ( _disp  != NULL ) fprintf(fp,"  disp  == %s\n", _disp);
2609   // fprintf(fp,"\n");
2610 }
2611 
2612 //------------------------------CondInterface----------------------------------
2613 CondInterface::CondInterface(const char* equal,         const char* equal_format,
2614                              const char* not_equal,     const char* not_equal_format,
2615                              const char* less,          const char* less_format,
2616                              const char* greater_equal, const char* greater_equal_format,
2617                              const char* less_equal,    const char* less_equal_format,
2618                              const char* greater,       const char* greater_format)
2619   : Interface("COND_INTER"),
2620     _equal(equal),                 _equal_format(equal_format),
2621     _not_equal(not_equal),         _not_equal_format(not_equal_format),
2622     _less(less),                   _less_format(less_format),
2623     _greater_equal(greater_equal), _greater_equal_format(greater_equal_format),
2624     _less_equal(less_equal),       _less_equal_format(less_equal_format),
2625     _greater(greater),             _greater_format(greater_format) {
2626 }
2627 CondInterface::~CondInterface() {
2628   // not owner of any character arrays
2629 }
2630 
2631 void CondInterface::dump() {
2632   output(stderr);
2633 }
2634 
2635 // Write info to output files
2636 void CondInterface::output(FILE *fp) {
2637   Interface::output(fp);
2638   if ( _equal  != NULL )     fprintf(fp," equal       == %s\n", _equal);
2639   if ( _not_equal  != NULL ) fprintf(fp," not_equal   == %s\n", _not_equal);
2640   if ( _less  != NULL )      fprintf(fp," less        == %s\n", _less);
2641   if ( _greater_equal  != NULL ) fprintf(fp," greater_equal   == %s\n", _greater_equal);
2642   if ( _less_equal  != NULL ) fprintf(fp," less_equal  == %s\n", _less_equal);
2643   if ( _greater  != NULL )    fprintf(fp," greater     == %s\n", _greater);
2644   // fprintf(fp,"\n");
2645 }
2646 
2647 //------------------------------ConstructRule----------------------------------
2648 ConstructRule::ConstructRule(char *cnstr)
2649   : _construct(cnstr) {
2650 }
2651 ConstructRule::~ConstructRule() {
2652 }
2653 
2654 void ConstructRule::dump() {
2655   output(stderr);
2656 }
2657 
2658 void ConstructRule::output(FILE *fp) {
2659   fprintf(fp,"\nConstruct Rule\n");  // Write to output files
2660 }
2661 
2662 
2663 //==============================Shared Forms===================================
2664 //------------------------------AttributeForm----------------------------------
2665 int         AttributeForm::_insId   = 0;           // start counter at 0
2666 int         AttributeForm::_opId    = 0;           // start counter at 0
2667 const char* AttributeForm::_ins_cost = "ins_cost"; // required name
2668 const char* AttributeForm::_ins_pc_relative = "ins_pc_relative";
2669 const char* AttributeForm::_op_cost  = "op_cost";  // required name
2670 
2671 AttributeForm::AttributeForm(char *attr, int type, char *attrdef)
2672   : Form(Form::ATTR), _attrname(attr), _atype(type), _attrdef(attrdef) {
2673     if (type==OP_ATTR) {
2674       id = ++_opId;
2675     }
2676     else if (type==INS_ATTR) {
2677       id = ++_insId;
2678     }
2679     else assert( false,"");
2680 }
2681 AttributeForm::~AttributeForm() {
2682 }
2683 
2684 // Dynamic type check
2685 AttributeForm *AttributeForm::is_attribute() const {
2686   return (AttributeForm*)this;
2687 }
2688 
2689 
2690 // inlined  // int  AttributeForm::type() { return id;}
2691 
2692 void AttributeForm::dump() {
2693   output(stderr);
2694 }
2695 
2696 void AttributeForm::output(FILE *fp) {
2697   if( _attrname && _attrdef ) {
2698     fprintf(fp,"\n// AttributeForm \nstatic const int %s = %s;\n",
2699             _attrname, _attrdef);
2700   }
2701   else {
2702     fprintf(fp,"\n// AttributeForm missing name %s or definition %s\n",
2703             (_attrname?_attrname:""), (_attrdef?_attrdef:"") );
2704   }
2705 }
2706 
2707 //------------------------------Component--------------------------------------
2708 Component::Component(const char *name, const char *type, int usedef)
2709   : _name(name), _type(type), _usedef(usedef) {
2710     _ftype = Form::COMP;
2711 }
2712 Component::~Component() {
2713 }
2714 
2715 // True if this component is equal to the parameter.
2716 bool Component::is(int use_def_kill_enum) const {
2717   return (_usedef == use_def_kill_enum ? true : false);
2718 }
2719 // True if this component is used/def'd/kill'd as the parameter suggests.
2720 bool Component::isa(int use_def_kill_enum) const {
2721   return (_usedef & use_def_kill_enum) == use_def_kill_enum;
2722 }
2723 
2724 // Extend this component with additional use/def/kill behavior
2725 int Component::promote_use_def_info(int new_use_def) {
2726   _usedef |= new_use_def;
2727 
2728   return _usedef;
2729 }
2730 
2731 // Check the base type of this component, if it has one
2732 const char *Component::base_type(FormDict &globals) {
2733   const Form *frm = globals[_type];
2734   if (frm == NULL) return NULL;
2735   OperandForm *op = frm->is_operand();
2736   if (op == NULL) return NULL;
2737   if (op->ideal_only()) return op->_ident;
2738   return (char *)op->ideal_type(globals);
2739 }
2740 
2741 void Component::dump() {
2742   output(stderr);
2743 }
2744 
2745 void Component::output(FILE *fp) {
2746   fprintf(fp,"Component:");  // Write to output files
2747   fprintf(fp, "  name = %s", _name);
2748   fprintf(fp, ", type = %s", _type);
2749   const char * usedef = "Undefined Use/Def info";
2750   switch (_usedef) {
2751     case USE:      usedef = "USE";      break;
2752     case USE_DEF:  usedef = "USE_DEF";  break;
2753     case USE_KILL: usedef = "USE_KILL"; break;
2754     case KILL:     usedef = "KILL";     break;
2755     case TEMP:     usedef = "TEMP";     break;
2756     case DEF:      usedef = "DEF";      break;
2757     default: assert(false, "unknown effect");
2758   }
2759   fprintf(fp, ", use/def = %s\n", usedef);
2760 }
2761 
2762 
2763 //------------------------------ComponentList---------------------------------
2764 ComponentList::ComponentList() : NameList(), _matchcnt(0) {
2765 }
2766 ComponentList::~ComponentList() {
2767   // // This list may not own its elements if copied via assignment
2768   // Component *component;
2769   // for (reset(); (component = iter()) != NULL;) {
2770   //   delete component;
2771   // }
2772 }
2773 
2774 void   ComponentList::insert(Component *component, bool mflag) {
2775   NameList::addName((char *)component);
2776   if(mflag) _matchcnt++;
2777 }
2778 void   ComponentList::insert(const char *name, const char *opType, int usedef,
2779                              bool mflag) {
2780   Component * component = new Component(name, opType, usedef);
2781   insert(component, mflag);
2782 }
2783 Component *ComponentList::current() { return (Component*)NameList::current(); }
2784 Component *ComponentList::iter()    { return (Component*)NameList::iter(); }
2785 Component *ComponentList::match_iter() {
2786   if(_iter < _matchcnt) return (Component*)NameList::iter();
2787   return NULL;
2788 }
2789 Component *ComponentList::post_match_iter() {
2790   Component *comp = iter();
2791   // At end of list?
2792   if ( comp == NULL ) {
2793     return comp;
2794   }
2795   // In post-match components?
2796   if (_iter > match_count()-1) {
2797     return comp;
2798   }
2799 
2800   return post_match_iter();
2801 }
2802 
2803 void       ComponentList::reset()   { NameList::reset(); }
2804 int        ComponentList::count()   { return NameList::count(); }
2805 
2806 Component *ComponentList::operator[](int position) {
2807   // Shortcut complete iteration if there are not enough entries
2808   if (position >= count()) return NULL;
2809 
2810   int        index     = 0;
2811   Component *component = NULL;
2812   for (reset(); (component = iter()) != NULL;) {
2813     if (index == position) {
2814       return component;
2815     }
2816     ++index;
2817   }
2818 
2819   return NULL;
2820 }
2821 
2822 const Component *ComponentList::search(const char *name) {
2823   PreserveIter pi(this);
2824   reset();
2825   for( Component *comp = NULL; ((comp = iter()) != NULL); ) {
2826     if( strcmp(comp->_name,name) == 0 ) return comp;
2827   }
2828 
2829   return NULL;
2830 }
2831 
2832 // Return number of USEs + number of DEFs
2833 // When there are no components, or the first component is a USE,
2834 // then we add '1' to hold a space for the 'result' operand.
2835 int ComponentList::num_operands() {
2836   PreserveIter pi(this);
2837   uint       count = 1;           // result operand
2838   uint       position = 0;
2839 
2840   Component *component  = NULL;
2841   for( reset(); (component = iter()) != NULL; ++position ) {
2842     if( component->isa(Component::USE) ||
2843         ( position == 0 && (! component->isa(Component::DEF))) ) {
2844       ++count;
2845     }
2846   }
2847 
2848   return count;
2849 }
2850 
2851 // Return zero-based position in list;  -1 if not in list.
2852 // if parameter 'usedef' is ::USE, it will match USE, USE_DEF, ...
2853 int ComponentList::operand_position(const char *name, int usedef) {
2854   PreserveIter pi(this);
2855   int position = 0;
2856   int num_opnds = num_operands();
2857   Component *component;
2858   Component* preceding_non_use = NULL;
2859   Component* first_def = NULL;
2860   for (reset(); (component = iter()) != NULL; ++position) {
2861     // When the first component is not a DEF,
2862     // leave space for the result operand!
2863     if ( position==0 && (! component->isa(Component::DEF)) ) {
2864       ++position;
2865       ++num_opnds;
2866     }
2867     if (strcmp(name, component->_name)==0 && (component->isa(usedef))) {
2868       // When the first entry in the component list is a DEF and a USE
2869       // Treat them as being separate, a DEF first, then a USE
2870       if( position==0
2871           && usedef==Component::USE && component->isa(Component::DEF) ) {
2872         assert(position+1 < num_opnds, "advertised index in bounds");
2873         return position+1;
2874       } else {
2875         if( preceding_non_use && strcmp(component->_name, preceding_non_use->_name) ) {
2876           fprintf(stderr, "the name '%s' should not precede the name '%s'\n", preceding_non_use->_name, name);
2877         }
2878         if( position >= num_opnds ) {
2879           fprintf(stderr, "the name '%s' is too late in its name list\n", name);
2880         }
2881         assert(position < num_opnds, "advertised index in bounds");
2882         return position;
2883       }
2884     }
2885     if( component->isa(Component::DEF)
2886         && component->isa(Component::USE) ) {
2887       ++position;
2888       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2889     }
2890     if( component->isa(Component::DEF) && !first_def ) {
2891       first_def = component;
2892     }
2893     if( !component->isa(Component::USE) && component != first_def ) {
2894       preceding_non_use = component;
2895     } else if( preceding_non_use && !strcmp(component->_name, preceding_non_use->_name) ) {
2896       preceding_non_use = NULL;
2897     }
2898   }
2899   return Not_in_list;
2900 }
2901 
2902 // Find position for this name, regardless of use/def information
2903 int ComponentList::operand_position(const char *name) {
2904   PreserveIter pi(this);
2905   int position = 0;
2906   Component *component;
2907   for (reset(); (component = iter()) != NULL; ++position) {
2908     // When the first component is not a DEF,
2909     // leave space for the result operand!
2910     if ( position==0 && (! component->isa(Component::DEF)) ) {
2911       ++position;
2912     }
2913     if (strcmp(name, component->_name)==0) {
2914       return position;
2915     }
2916     if( component->isa(Component::DEF)
2917         && component->isa(Component::USE) ) {
2918       ++position;
2919       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2920     }
2921   }
2922   return Not_in_list;
2923 }
2924 
2925 int ComponentList::operand_position_format(const char *name) {
2926   PreserveIter pi(this);
2927   int  first_position = operand_position(name);
2928   int  use_position   = operand_position(name, Component::USE);
2929 
2930   return ((first_position < use_position) ? use_position : first_position);
2931 }
2932 
2933 int ComponentList::label_position() {
2934   PreserveIter pi(this);
2935   int position = 0;
2936   reset();
2937   for( Component *comp; (comp = iter()) != NULL; ++position) {
2938     // When the first component is not a DEF,
2939     // leave space for the result operand!
2940     if ( position==0 && (! comp->isa(Component::DEF)) ) {
2941       ++position;
2942     }
2943     if (strcmp(comp->_type, "label")==0) {
2944       return position;
2945     }
2946     if( comp->isa(Component::DEF)
2947         && comp->isa(Component::USE) ) {
2948       ++position;
2949       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2950     }
2951   }
2952 
2953   return -1;
2954 }
2955 
2956 int ComponentList::method_position() {
2957   PreserveIter pi(this);
2958   int position = 0;
2959   reset();
2960   for( Component *comp; (comp = iter()) != NULL; ++position) {
2961     // When the first component is not a DEF,
2962     // leave space for the result operand!
2963     if ( position==0 && (! comp->isa(Component::DEF)) ) {
2964       ++position;
2965     }
2966     if (strcmp(comp->_type, "method")==0) {
2967       return position;
2968     }
2969     if( comp->isa(Component::DEF)
2970         && comp->isa(Component::USE) ) {
2971       ++position;
2972       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
2973     }
2974   }
2975 
2976   return -1;
2977 }
2978 
2979 void ComponentList::dump() { output(stderr); }
2980 
2981 void ComponentList::output(FILE *fp) {
2982   PreserveIter pi(this);
2983   fprintf(fp, "\n");
2984   Component *component;
2985   for (reset(); (component = iter()) != NULL;) {
2986     component->output(fp);
2987   }
2988   fprintf(fp, "\n");
2989 }
2990 
2991 //------------------------------MatchNode--------------------------------------
2992 MatchNode::MatchNode(ArchDesc &ad, const char *result, const char *mexpr,
2993                      const char *opType, MatchNode *lChild, MatchNode *rChild)
2994   : _AD(ad), _result(result), _name(mexpr), _opType(opType),
2995     _lChild(lChild), _rChild(rChild), _internalop(0), _numleaves(0),
2996     _commutative_id(0) {
2997   _numleaves = (lChild ? lChild->_numleaves : 0)
2998                + (rChild ? rChild->_numleaves : 0);
2999 }
3000 
3001 MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode)
3002   : _AD(ad), _result(mnode._result), _name(mnode._name),
3003     _opType(mnode._opType), _lChild(mnode._lChild), _rChild(mnode._rChild),
3004     _internalop(0), _numleaves(mnode._numleaves),
3005     _commutative_id(mnode._commutative_id) {
3006 }
3007 
3008 MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode, int clone)
3009   : _AD(ad), _result(mnode._result), _name(mnode._name),
3010     _opType(mnode._opType),
3011     _internalop(0), _numleaves(mnode._numleaves),
3012     _commutative_id(mnode._commutative_id) {
3013   if (mnode._lChild) {
3014     _lChild = new MatchNode(ad, *mnode._lChild, clone);
3015   } else {
3016     _lChild = NULL;
3017   }
3018   if (mnode._rChild) {
3019     _rChild = new MatchNode(ad, *mnode._rChild, clone);
3020   } else {
3021     _rChild = NULL;
3022   }
3023 }
3024 
3025 MatchNode::~MatchNode() {
3026   // // This node may not own its children if copied via assignment
3027   // if( _lChild ) delete _lChild;
3028   // if( _rChild ) delete _rChild;
3029 }
3030 
3031 bool  MatchNode::find_type(const char *type, int &position) const {
3032   if ( (_lChild != NULL) && (_lChild->find_type(type, position)) ) return true;
3033   if ( (_rChild != NULL) && (_rChild->find_type(type, position)) ) return true;
3034 
3035   if (strcmp(type,_opType)==0)  {
3036     return true;
3037   } else {
3038     ++position;
3039   }
3040   return false;
3041 }
3042 
3043 // Recursive call collecting info on top-level operands, not transitive.
3044 // Implementation does not modify state of internal structures.
3045 void MatchNode::append_components(FormDict &locals, ComponentList &components,
3046                                   bool deflag) const {
3047   int   usedef = deflag ? Component::DEF : Component::USE;
3048   FormDict &globals = _AD.globalNames();
3049 
3050   assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
3051   // Base case
3052   if (_lChild==NULL && _rChild==NULL) {
3053     // If _opType is not an operation, do not build a component for it #####
3054     const Form *f = globals[_opType];
3055     if( f != NULL ) {
3056       // Add non-ideals that are operands, operand-classes,
3057       if( ! f->ideal_only()
3058           && (f->is_opclass() || f->is_operand()) ) {
3059         components.insert(_name, _opType, usedef, true);
3060       }
3061     }
3062     return;
3063   }
3064   // Promote results of "Set" to DEF
3065   bool def_flag = (!strcmp(_opType, "Set")) ? true : false;
3066   if (_lChild) _lChild->append_components(locals, components, def_flag);
3067   def_flag = false;   // only applies to component immediately following 'Set'
3068   if (_rChild) _rChild->append_components(locals, components, def_flag);
3069 }
3070 
3071 // Find the n'th base-operand in the match node,
3072 // recursively investigates match rules of user-defined operands.
3073 //
3074 // Implementation does not modify state of internal structures since they
3075 // can be shared.
3076 bool MatchNode::base_operand(uint &position, FormDict &globals,
3077                              const char * &result, const char * &name,
3078                              const char * &opType) const {
3079   assert (_name != NULL, "MatchNode::base_operand encountered empty node\n");
3080   // Base case
3081   if (_lChild==NULL && _rChild==NULL) {
3082     // Check for special case: "Universe", "label"
3083     if (strcmp(_opType,"Universe") == 0 || strcmp(_opType,"label")==0 ) {
3084       if (position == 0) {
3085         result = _result;
3086         name   = _name;
3087         opType = _opType;
3088         return 1;
3089       } else {
3090         -- position;
3091         return 0;
3092       }
3093     }
3094 
3095     const Form *form = globals[_opType];
3096     MatchNode *matchNode = NULL;
3097     // Check for user-defined type
3098     if (form) {
3099       // User operand or instruction?
3100       OperandForm  *opForm = form->is_operand();
3101       InstructForm *inForm = form->is_instruction();
3102       if ( opForm ) {
3103         matchNode = (MatchNode*)opForm->_matrule;
3104       } else if ( inForm ) {
3105         matchNode = (MatchNode*)inForm->_matrule;
3106       }
3107     }
3108     // if this is user-defined, recurse on match rule
3109     // User-defined operand and instruction forms have a match-rule.
3110     if (matchNode) {
3111       return (matchNode->base_operand(position,globals,result,name,opType));
3112     } else {
3113       // Either not a form, or a system-defined form (no match rule).
3114       if (position==0) {
3115         result = _result;
3116         name   = _name;
3117         opType = _opType;
3118         return 1;
3119       } else {
3120         --position;
3121         return 0;
3122       }
3123     }
3124 
3125   } else {
3126     // Examine the left child and right child as well
3127     if (_lChild) {
3128       if (_lChild->base_operand(position, globals, result, name, opType))
3129         return 1;
3130     }
3131 
3132     if (_rChild) {
3133       if (_rChild->base_operand(position, globals, result, name, opType))
3134         return 1;
3135     }
3136   }
3137 
3138   return 0;
3139 }
3140 
3141 // Recursive call on all operands' match rules in my match rule.
3142 uint  MatchNode::num_consts(FormDict &globals) const {
3143   uint        index      = 0;
3144   uint        num_consts = 0;
3145   const char *result;
3146   const char *name;
3147   const char *opType;
3148 
3149   for (uint position = index;
3150        base_operand(position,globals,result,name,opType); position = index) {
3151     ++index;
3152     if( ideal_to_const_type(opType) )        num_consts++;
3153   }
3154 
3155   return num_consts;
3156 }
3157 
3158 // Recursive call on all operands' match rules in my match rule.
3159 // Constants in match rule subtree with specified type
3160 uint  MatchNode::num_consts(FormDict &globals, Form::DataType type) const {
3161   uint        index      = 0;
3162   uint        num_consts = 0;
3163   const char *result;
3164   const char *name;
3165   const char *opType;
3166 
3167   for (uint position = index;
3168        base_operand(position,globals,result,name,opType); position = index) {
3169     ++index;
3170     if( ideal_to_const_type(opType) == type ) num_consts++;
3171   }
3172 
3173   return num_consts;
3174 }
3175 
3176 // Recursive call on all operands' match rules in my match rule.
3177 uint  MatchNode::num_const_ptrs(FormDict &globals) const {
3178   return  num_consts( globals, Form::idealP );
3179 }
3180 
3181 bool  MatchNode::sets_result() const {
3182   return   ( (strcmp(_name,"Set") == 0) ? true : false );
3183 }
3184 
3185 const char *MatchNode::reduce_right(FormDict &globals) const {
3186   // If there is no right reduction, return NULL.
3187   const char      *rightStr    = NULL;
3188 
3189   // If we are a "Set", start from the right child.
3190   const MatchNode *const mnode = sets_result() ?
3191     (const MatchNode *const)this->_rChild :
3192     (const MatchNode *const)this;
3193 
3194   // If our right child exists, it is the right reduction
3195   if ( mnode->_rChild ) {
3196     rightStr = mnode->_rChild->_internalop ? mnode->_rChild->_internalop
3197       : mnode->_rChild->_opType;
3198   }
3199   // Else, May be simple chain rule: (Set dst operand_form), rightStr=NULL;
3200   return rightStr;
3201 }
3202 
3203 const char *MatchNode::reduce_left(FormDict &globals) const {
3204   // If there is no left reduction, return NULL.
3205   const char  *leftStr  = NULL;
3206 
3207   // If we are a "Set", start from the right child.
3208   const MatchNode *const mnode = sets_result() ?
3209     (const MatchNode *const)this->_rChild :
3210     (const MatchNode *const)this;
3211 
3212   // If our left child exists, it is the left reduction
3213   if ( mnode->_lChild ) {
3214     leftStr = mnode->_lChild->_internalop ? mnode->_lChild->_internalop
3215       : mnode->_lChild->_opType;
3216   } else {
3217     // May be simple chain rule: (Set dst operand_form_source)
3218     if ( sets_result() ) {
3219       OperandForm *oper = globals[mnode->_opType]->is_operand();
3220       if( oper ) {
3221         leftStr = mnode->_opType;
3222       }
3223     }
3224   }
3225   return leftStr;
3226 }
3227 
3228 //------------------------------count_instr_names------------------------------
3229 // Count occurrences of operands names in the leaves of the instruction
3230 // match rule.
3231 void MatchNode::count_instr_names( Dict &names ) {
3232   if( !this ) return;
3233   if( _lChild ) _lChild->count_instr_names(names);
3234   if( _rChild ) _rChild->count_instr_names(names);
3235   if( !_lChild && !_rChild ) {
3236     uintptr_t cnt = (uintptr_t)names[_name];
3237     cnt++;                      // One more name found
3238     names.Insert(_name,(void*)cnt);
3239   }
3240 }
3241 
3242 //------------------------------build_instr_pred-------------------------------
3243 // Build a path to 'name' in buf.  Actually only build if cnt is zero, so we
3244 // can skip some leading instances of 'name'.
3245 int MatchNode::build_instr_pred( char *buf, const char *name, int cnt ) {
3246   if( _lChild ) {
3247     if( !cnt ) strcpy( buf, "_kids[0]->" );
3248     cnt = _lChild->build_instr_pred( buf+strlen(buf), name, cnt );
3249     if( cnt < 0 ) return cnt;   // Found it, all done
3250   }
3251   if( _rChild ) {
3252     if( !cnt ) strcpy( buf, "_kids[1]->" );
3253     cnt = _rChild->build_instr_pred( buf+strlen(buf), name, cnt );
3254     if( cnt < 0 ) return cnt;   // Found it, all done
3255   }
3256   if( !_lChild && !_rChild ) {  // Found a leaf
3257     // Wrong name?  Give up...
3258     if( strcmp(name,_name) ) return cnt;
3259     if( !cnt ) strcpy(buf,"_leaf");
3260     return cnt-1;
3261   }
3262   return cnt;
3263 }
3264 
3265 
3266 //------------------------------build_internalop-------------------------------
3267 // Build string representation of subtree
3268 void MatchNode::build_internalop( ) {
3269   char *iop, *subtree;
3270   const char *lstr, *rstr;
3271   // Build string representation of subtree
3272   // Operation lchildType rchildType
3273   int len = (int)strlen(_opType) + 4;
3274   lstr = (_lChild) ? ((_lChild->_internalop) ?
3275                        _lChild->_internalop : _lChild->_opType) : "";
3276   rstr = (_rChild) ? ((_rChild->_internalop) ?
3277                        _rChild->_internalop : _rChild->_opType) : "";
3278   len += (int)strlen(lstr) + (int)strlen(rstr);
3279   subtree = (char *)malloc(len);
3280   sprintf(subtree,"_%s_%s_%s", _opType, lstr, rstr);
3281   // Hash the subtree string in _internalOps; if a name exists, use it
3282   iop = (char *)_AD._internalOps[subtree];
3283   // Else create a unique name, and add it to the hash table
3284   if (iop == NULL) {
3285     iop = subtree;
3286     _AD._internalOps.Insert(subtree, iop);
3287     _AD._internalOpNames.addName(iop);
3288     _AD._internalMatch.Insert(iop, this);
3289   }
3290   // Add the internal operand name to the MatchNode
3291   _internalop = iop;
3292   _result = iop;
3293 }
3294 
3295 
3296 void MatchNode::dump() {
3297   output(stderr);
3298 }
3299 
3300 void MatchNode::output(FILE *fp) {
3301   if (_lChild==0 && _rChild==0) {
3302     fprintf(fp," %s",_name);    // operand
3303   }
3304   else {
3305     fprintf(fp," (%s ",_name);  // " (opcodeName "
3306     if(_lChild) _lChild->output(fp); //               left operand
3307     if(_rChild) _rChild->output(fp); //                    right operand
3308     fprintf(fp,")");                 //                                 ")"
3309   }
3310 }
3311 
3312 int MatchNode::needs_ideal_memory_edge(FormDict &globals) const {
3313   static const char *needs_ideal_memory_list[] = {
3314     "StoreI","StoreL","StoreP","StoreN","StoreD","StoreF" ,
3315     "StoreB","StoreC","Store" ,"StoreFP",
3316     "LoadI" ,"LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF"  ,
3317     "LoadB" ,"LoadUS" ,"LoadS" ,"Load"   ,
3318     "Store4I","Store2I","Store2L","Store2D","Store4F","Store2F","Store16B",
3319     "Store8B","Store4B","Store8C","Store4C","Store2C",
3320     "Load4I" ,"Load2I" ,"Load2L" ,"Load2D" ,"Load4F" ,"Load2F" ,"Load16B" ,
3321     "Load8B" ,"Load4B" ,"Load8C" ,"Load4C" ,"Load2C" ,"Load8S", "Load4S","Load2S",
3322     "LoadRange", "LoadKlass", "LoadNKlass", "LoadL_unaligned", "LoadD_unaligned",
3323     "LoadPLocked", "LoadLLocked",
3324     "StorePConditional", "StoreIConditional", "StoreLConditional",
3325     "CompareAndSwapI", "CompareAndSwapL", "CompareAndSwapP", "CompareAndSwapN",
3326     "StoreCM",
3327     "ClearArray"
3328   };
3329   int cnt = sizeof(needs_ideal_memory_list)/sizeof(char*);
3330   if( strcmp(_opType,"PrefetchRead")==0 || strcmp(_opType,"PrefetchWrite")==0 )
3331     return 1;
3332   if( _lChild ) {
3333     const char *opType = _lChild->_opType;
3334     for( int i=0; i<cnt; i++ )
3335       if( strcmp(opType,needs_ideal_memory_list[i]) == 0 )
3336         return 1;
3337     if( _lChild->needs_ideal_memory_edge(globals) )
3338       return 1;
3339   }
3340   if( _rChild ) {
3341     const char *opType = _rChild->_opType;
3342     for( int i=0; i<cnt; i++ )
3343       if( strcmp(opType,needs_ideal_memory_list[i]) == 0 )
3344         return 1;
3345     if( _rChild->needs_ideal_memory_edge(globals) )
3346       return 1;
3347   }
3348 
3349   return 0;
3350 }
3351 
3352 // TRUE if defines a derived oop, and so needs a base oop edge present
3353 // post-matching.
3354 int MatchNode::needs_base_oop_edge() const {
3355   if( !strcmp(_opType,"AddP") ) return 1;
3356   if( strcmp(_opType,"Set") ) return 0;
3357   return !strcmp(_rChild->_opType,"AddP");
3358 }
3359 
3360 int InstructForm::needs_base_oop_edge(FormDict &globals) const {
3361   if( is_simple_chain_rule(globals) ) {
3362     const char *src = _matrule->_rChild->_opType;
3363     OperandForm *src_op = globals[src]->is_operand();
3364     assert( src_op, "Not operand class of chain rule" );
3365     return src_op->_matrule ? src_op->_matrule->needs_base_oop_edge() : 0;
3366   }                             // Else check instruction
3367 
3368   return _matrule ? _matrule->needs_base_oop_edge() : 0;
3369 }
3370 
3371 
3372 //-------------------------cisc spilling methods-------------------------------
3373 // helper routines and methods for detecting cisc-spilling instructions
3374 //-------------------------cisc_spill_merge------------------------------------
3375 int MatchNode::cisc_spill_merge(int left_spillable, int right_spillable) {
3376   int cisc_spillable  = Maybe_cisc_spillable;
3377 
3378   // Combine results of left and right checks
3379   if( (left_spillable == Maybe_cisc_spillable) && (right_spillable == Maybe_cisc_spillable) ) {
3380     // neither side is spillable, nor prevents cisc spilling
3381     cisc_spillable = Maybe_cisc_spillable;
3382   }
3383   else if( (left_spillable == Maybe_cisc_spillable) && (right_spillable > Maybe_cisc_spillable) ) {
3384     // right side is spillable
3385     cisc_spillable = right_spillable;
3386   }
3387   else if( (right_spillable == Maybe_cisc_spillable) && (left_spillable > Maybe_cisc_spillable) ) {
3388     // left side is spillable
3389     cisc_spillable = left_spillable;
3390   }
3391   else if( (left_spillable == Not_cisc_spillable) || (right_spillable == Not_cisc_spillable) ) {
3392     // left or right prevents cisc spilling this instruction
3393     cisc_spillable = Not_cisc_spillable;
3394   }
3395   else {
3396     // Only allow one to spill
3397     cisc_spillable = Not_cisc_spillable;
3398   }
3399 
3400   return cisc_spillable;
3401 }
3402 
3403 //-------------------------root_ops_match--------------------------------------
3404 bool static root_ops_match(FormDict &globals, const char *op1, const char *op2) {
3405   // Base Case: check that the current operands/operations match
3406   assert( op1, "Must have op's name");
3407   assert( op2, "Must have op's name");
3408   const Form *form1 = globals[op1];
3409   const Form *form2 = globals[op2];
3410 
3411   return (form1 == form2);
3412 }
3413 
3414 //-------------------------cisc_spill_match------------------------------------
3415 // Recursively check two MatchRules for legal conversion via cisc-spilling
3416 int  MatchNode::cisc_spill_match(FormDict &globals, RegisterForm *registers, MatchNode *mRule2, const char * &operand, const char * &reg_type) {
3417   int cisc_spillable  = Maybe_cisc_spillable;
3418   int left_spillable  = Maybe_cisc_spillable;
3419   int right_spillable = Maybe_cisc_spillable;
3420 
3421   // Check that each has same number of operands at this level
3422   if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) )
3423     return Not_cisc_spillable;
3424 
3425   // Base Case: check that the current operands/operations match
3426   // or are CISC spillable
3427   assert( _opType, "Must have _opType");
3428   assert( mRule2->_opType, "Must have _opType");
3429   const Form *form  = globals[_opType];
3430   const Form *form2 = globals[mRule2->_opType];
3431   if( form == form2 ) {
3432     cisc_spillable = Maybe_cisc_spillable;
3433   } else {
3434     const InstructForm *form2_inst = form2 ? form2->is_instruction() : NULL;
3435     const char *name_left  = mRule2->_lChild ? mRule2->_lChild->_opType : NULL;
3436     const char *name_right = mRule2->_rChild ? mRule2->_rChild->_opType : NULL;
3437     // Detect reg vs (loadX memory)
3438     if( form->is_cisc_reg(globals)
3439         && form2_inst
3440         && (is_load_from_memory(mRule2->_opType) != Form::none) // reg vs. (load memory)
3441         && (name_left != NULL)       // NOT (load)
3442         && (name_right == NULL) ) {  // NOT (load memory foo)
3443       const Form *form2_left = name_left ? globals[name_left] : NULL;
3444       if( form2_left && form2_left->is_cisc_mem(globals) ) {
3445         cisc_spillable = Is_cisc_spillable;
3446         operand        = _name;
3447         reg_type       = _result;
3448         return Is_cisc_spillable;
3449       } else {
3450         cisc_spillable = Not_cisc_spillable;
3451       }
3452     }
3453     // Detect reg vs memory
3454     else if( form->is_cisc_reg(globals) && form2->is_cisc_mem(globals) ) {
3455       cisc_spillable = Is_cisc_spillable;
3456       operand        = _name;
3457       reg_type       = _result;
3458       return Is_cisc_spillable;
3459     } else {
3460       cisc_spillable = Not_cisc_spillable;
3461     }
3462   }
3463 
3464   // If cisc is still possible, check rest of tree
3465   if( cisc_spillable == Maybe_cisc_spillable ) {
3466     // Check that each has same number of operands at this level
3467     if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) ) return Not_cisc_spillable;
3468 
3469     // Check left operands
3470     if( (_lChild == NULL) && (mRule2->_lChild == NULL) ) {
3471       left_spillable = Maybe_cisc_spillable;
3472     } else {
3473       left_spillable = _lChild->cisc_spill_match(globals, registers, mRule2->_lChild, operand, reg_type);
3474     }
3475 
3476     // Check right operands
3477     if( (_rChild == NULL) && (mRule2->_rChild == NULL) ) {
3478       right_spillable =  Maybe_cisc_spillable;
3479     } else {
3480       right_spillable = _rChild->cisc_spill_match(globals, registers, mRule2->_rChild, operand, reg_type);
3481     }
3482 
3483     // Combine results of left and right checks
3484     cisc_spillable = cisc_spill_merge(left_spillable, right_spillable);
3485   }
3486 
3487   return cisc_spillable;
3488 }
3489 
3490 //---------------------------cisc_spill_match----------------------------------
3491 // Recursively check two MatchRules for legal conversion via cisc-spilling
3492 // This method handles the root of Match tree,
3493 // general recursive checks done in MatchNode
3494 int  MatchRule::cisc_spill_match(FormDict &globals, RegisterForm *registers,
3495                                  MatchRule *mRule2, const char * &operand,
3496                                  const char * &reg_type) {
3497   int cisc_spillable  = Maybe_cisc_spillable;
3498   int left_spillable  = Maybe_cisc_spillable;
3499   int right_spillable = Maybe_cisc_spillable;
3500 
3501   // Check that each sets a result
3502   if( !(sets_result() && mRule2->sets_result()) ) return Not_cisc_spillable;
3503   // Check that each has same number of operands at this level
3504   if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) ) return Not_cisc_spillable;
3505 
3506   // Check left operands: at root, must be target of 'Set'
3507   if( (_lChild == NULL) || (mRule2->_lChild == NULL) ) {
3508     left_spillable = Not_cisc_spillable;
3509   } else {
3510     // Do not support cisc-spilling instruction's target location
3511     if( root_ops_match(globals, _lChild->_opType, mRule2->_lChild->_opType) ) {
3512       left_spillable = Maybe_cisc_spillable;
3513     } else {
3514       left_spillable = Not_cisc_spillable;
3515     }
3516   }
3517 
3518   // Check right operands: recursive walk to identify reg->mem operand
3519   if( (_rChild == NULL) && (mRule2->_rChild == NULL) ) {
3520     right_spillable =  Maybe_cisc_spillable;
3521   } else {
3522     right_spillable = _rChild->cisc_spill_match(globals, registers, mRule2->_rChild, operand, reg_type);
3523   }
3524 
3525   // Combine results of left and right checks
3526   cisc_spillable = cisc_spill_merge(left_spillable, right_spillable);
3527 
3528   return cisc_spillable;
3529 }
3530 
3531 //----------------------------- equivalent ------------------------------------
3532 // Recursively check to see if two match rules are equivalent.
3533 // This rule handles the root.
3534 bool MatchRule::equivalent(FormDict &globals, MatchRule *mRule2) {
3535   // Check that each sets a result
3536   if (sets_result() != mRule2->sets_result()) {
3537     return false;
3538   }
3539 
3540   // Check that the current operands/operations match
3541   assert( _opType, "Must have _opType");
3542   assert( mRule2->_opType, "Must have _opType");
3543   const Form *form  = globals[_opType];
3544   const Form *form2 = globals[mRule2->_opType];
3545   if( form != form2 ) {
3546     return false;
3547   }
3548 
3549   if (_lChild ) {
3550     if( !_lChild->equivalent(globals, mRule2->_lChild) )
3551       return false;
3552   } else if (mRule2->_lChild) {
3553     return false; // I have NULL left child, mRule2 has non-NULL left child.
3554   }
3555 
3556   if (_rChild ) {
3557     if( !_rChild->equivalent(globals, mRule2->_rChild) )
3558       return false;
3559   } else if (mRule2->_rChild) {
3560     return false; // I have NULL right child, mRule2 has non-NULL right child.
3561   }
3562 
3563   // We've made it through the gauntlet.
3564   return true;
3565 }
3566 
3567 //----------------------------- equivalent ------------------------------------
3568 // Recursively check to see if two match rules are equivalent.
3569 // This rule handles the operands.
3570 bool MatchNode::equivalent(FormDict &globals, MatchNode *mNode2) {
3571   if( !mNode2 )
3572     return false;
3573 
3574   // Check that the current operands/operations match
3575   assert( _opType, "Must have _opType");
3576   assert( mNode2->_opType, "Must have _opType");
3577   const Form *form  = globals[_opType];
3578   const Form *form2 = globals[mNode2->_opType];
3579   return (form == form2);
3580 }
3581 
3582 //-------------------------- has_commutative_op -------------------------------
3583 // Recursively check for commutative operations with subtree operands
3584 // which could be swapped.
3585 void MatchNode::count_commutative_op(int& count) {
3586   static const char *commut_op_list[] = {
3587     "AddI","AddL","AddF","AddD",
3588     "AndI","AndL",
3589     "MaxI","MinI",
3590     "MulI","MulL","MulF","MulD",
3591     "OrI" ,"OrL" ,
3592     "XorI","XorL"
3593   };
3594   int cnt = sizeof(commut_op_list)/sizeof(char*);
3595 
3596   if( _lChild && _rChild && (_lChild->_lChild || _rChild->_lChild) ) {
3597     // Don't swap if right operand is an immediate constant.
3598     bool is_const = false;
3599     if( _rChild->_lChild == NULL && _rChild->_rChild == NULL ) {
3600       FormDict &globals = _AD.globalNames();
3601       const Form *form = globals[_rChild->_opType];
3602       if ( form ) {
3603         OperandForm  *oper = form->is_operand();
3604         if( oper && oper->interface_type(globals) == Form::constant_interface )
3605           is_const = true;
3606       }
3607     }
3608     if( !is_const ) {
3609       for( int i=0; i<cnt; i++ ) {
3610         if( strcmp(_opType, commut_op_list[i]) == 0 ) {
3611           count++;
3612           _commutative_id = count; // id should be > 0
3613           break;
3614         }
3615       }
3616     }
3617   }
3618   if( _lChild )
3619     _lChild->count_commutative_op(count);
3620   if( _rChild )
3621     _rChild->count_commutative_op(count);
3622 }
3623 
3624 //-------------------------- swap_commutative_op ------------------------------
3625 // Recursively swap specified commutative operation with subtree operands.
3626 void MatchNode::swap_commutative_op(bool atroot, int id) {
3627   if( _commutative_id == id ) { // id should be > 0
3628     assert(_lChild && _rChild && (_lChild->_lChild || _rChild->_lChild ),
3629             "not swappable operation");
3630     MatchNode* tmp = _lChild;
3631     _lChild = _rChild;
3632     _rChild = tmp;
3633     // Don't exit here since we need to build internalop.
3634   }
3635 
3636   bool is_set = ( strcmp(_opType, "Set") == 0 );
3637   if( _lChild )
3638     _lChild->swap_commutative_op(is_set, id);
3639   if( _rChild )
3640     _rChild->swap_commutative_op(is_set, id);
3641 
3642   // If not the root, reduce this subtree to an internal operand
3643   if( !atroot && (_lChild || _rChild) ) {
3644     build_internalop();
3645   }
3646 }
3647 
3648 //-------------------------- swap_commutative_op ------------------------------
3649 // Recursively swap specified commutative operation with subtree operands.
3650 void MatchRule::swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt) {
3651   assert(match_rules_cnt < 100," too many match rule clones");
3652   // Clone
3653   MatchRule* clone = new MatchRule(_AD, this);
3654   // Swap operands of commutative operation
3655   ((MatchNode*)clone)->swap_commutative_op(true, count);
3656   char* buf = (char*) malloc(strlen(instr_ident) + 4);
3657   sprintf(buf, "%s_%d", instr_ident, match_rules_cnt++);
3658   clone->_result = buf;
3659 
3660   clone->_next = this->_next;
3661   this-> _next = clone;
3662   if( (--count) > 0 ) {
3663     this-> swap_commutative_op(instr_ident, count, match_rules_cnt);
3664     clone->swap_commutative_op(instr_ident, count, match_rules_cnt);
3665   }
3666 }
3667 
3668 //------------------------------MatchRule--------------------------------------
3669 MatchRule::MatchRule(ArchDesc &ad)
3670   : MatchNode(ad), _depth(0), _construct(NULL), _numchilds(0) {
3671     _next = NULL;
3672 }
3673 
3674 MatchRule::MatchRule(ArchDesc &ad, MatchRule* mRule)
3675   : MatchNode(ad, *mRule, 0), _depth(mRule->_depth),
3676     _construct(mRule->_construct), _numchilds(mRule->_numchilds) {
3677     _next = NULL;
3678 }
3679 
3680 MatchRule::MatchRule(ArchDesc &ad, MatchNode* mroot, int depth, char *cnstr,
3681                      int numleaves)
3682   : MatchNode(ad,*mroot), _depth(depth), _construct(cnstr),
3683     _numchilds(0) {
3684       _next = NULL;
3685       mroot->_lChild = NULL;
3686       mroot->_rChild = NULL;
3687       delete mroot;
3688       _numleaves = numleaves;
3689       _numchilds = (_lChild ? 1 : 0) + (_rChild ? 1 : 0);
3690 }
3691 MatchRule::~MatchRule() {
3692 }
3693 
3694 // Recursive call collecting info on top-level operands, not transitive.
3695 // Implementation does not modify state of internal structures.
3696 void MatchRule::append_components(FormDict &locals, ComponentList &components) const {
3697   assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
3698 
3699   MatchNode::append_components(locals, components,
3700                                false /* not necessarily a def */);
3701 }
3702 
3703 // Recursive call on all operands' match rules in my match rule.
3704 // Implementation does not modify state of internal structures  since they
3705 // can be shared.
3706 // The MatchNode that is called first treats its
3707 bool MatchRule::base_operand(uint &position0, FormDict &globals,
3708                              const char *&result, const char * &name,
3709                              const char * &opType)const{
3710   uint position = position0;
3711 
3712   return (MatchNode::base_operand( position, globals, result, name, opType));
3713 }
3714 
3715 
3716 bool MatchRule::is_base_register(FormDict &globals) const {
3717   uint   position = 1;
3718   const char  *result   = NULL;
3719   const char  *name     = NULL;
3720   const char  *opType   = NULL;
3721   if (!base_operand(position, globals, result, name, opType)) {
3722     position = 0;
3723     if( base_operand(position, globals, result, name, opType) &&
3724         (strcmp(opType,"RegI")==0 ||
3725          strcmp(opType,"RegP")==0 ||
3726          strcmp(opType,"RegN")==0 ||
3727          strcmp(opType,"RegL")==0 ||
3728          strcmp(opType,"RegF")==0 ||
3729          strcmp(opType,"RegD")==0 ||
3730          strcmp(opType,"Reg" )==0) ) {
3731       return 1;
3732     }
3733   }
3734   return 0;
3735 }
3736 
3737 Form::DataType MatchRule::is_base_constant(FormDict &globals) const {
3738   uint         position = 1;
3739   const char  *result   = NULL;
3740   const char  *name     = NULL;
3741   const char  *opType   = NULL;
3742   if (!base_operand(position, globals, result, name, opType)) {
3743     position = 0;
3744     if (base_operand(position, globals, result, name, opType)) {
3745       return ideal_to_const_type(opType);
3746     }
3747   }
3748   return Form::none;
3749 }
3750 
3751 bool MatchRule::is_chain_rule(FormDict &globals) const {
3752 
3753   // Check for chain rule, and do not generate a match list for it
3754   if ((_lChild == NULL) && (_rChild == NULL) ) {
3755     const Form *form = globals[_opType];
3756     // If this is ideal, then it is a base match, not a chain rule.
3757     if ( form && form->is_operand() && (!form->ideal_only())) {
3758       return true;
3759     }
3760   }
3761   // Check for "Set" form of chain rule, and do not generate a match list
3762   if (_rChild) {
3763     const char *rch = _rChild->_opType;
3764     const Form *form = globals[rch];
3765     if ((!strcmp(_opType,"Set") &&
3766          ((form) && form->is_operand()))) {
3767       return true;
3768     }
3769   }
3770   return false;
3771 }
3772 
3773 int MatchRule::is_ideal_copy() const {
3774   if( _rChild ) {
3775     const char  *opType = _rChild->_opType;
3776 #if 1
3777     if( strcmp(opType,"CastIP")==0 )
3778       return 1;
3779 #else
3780     if( strcmp(opType,"CastII")==0 )
3781       return 1;
3782     // Do not treat *CastPP this way, because it
3783     // may transfer a raw pointer to an oop.
3784     // If the register allocator were to coalesce this
3785     // into a single LRG, the GC maps would be incorrect.
3786     //if( strcmp(opType,"CastPP")==0 )
3787     //  return 1;
3788     //if( strcmp(opType,"CheckCastPP")==0 )
3789     //  return 1;
3790     //
3791     // Do not treat CastX2P or CastP2X this way, because
3792     // raw pointers and int types are treated differently
3793     // when saving local & stack info for safepoints in
3794     // Output().
3795     //if( strcmp(opType,"CastX2P")==0 )
3796     //  return 1;
3797     //if( strcmp(opType,"CastP2X")==0 )
3798     //  return 1;
3799 #endif
3800   }
3801   if( is_chain_rule(_AD.globalNames()) &&
3802       _lChild && strncmp(_lChild->_opType,"stackSlot",9)==0 )
3803     return 1;
3804   return 0;
3805 }
3806 
3807 
3808 int MatchRule::is_expensive() const {
3809   if( _rChild ) {
3810     const char  *opType = _rChild->_opType;
3811     if( strcmp(opType,"AtanD")==0 ||
3812         strcmp(opType,"CosD")==0 ||
3813         strcmp(opType,"DivD")==0 ||
3814         strcmp(opType,"DivF")==0 ||
3815         strcmp(opType,"DivI")==0 ||
3816         strcmp(opType,"ExpD")==0 ||
3817         strcmp(opType,"LogD")==0 ||
3818         strcmp(opType,"Log10D")==0 ||
3819         strcmp(opType,"ModD")==0 ||
3820         strcmp(opType,"ModF")==0 ||
3821         strcmp(opType,"ModI")==0 ||
3822         strcmp(opType,"PowD")==0 ||
3823         strcmp(opType,"SinD")==0 ||
3824         strcmp(opType,"SqrtD")==0 ||
3825         strcmp(opType,"TanD")==0 ||
3826         strcmp(opType,"ConvD2F")==0 ||
3827         strcmp(opType,"ConvD2I")==0 ||
3828         strcmp(opType,"ConvD2L")==0 ||
3829         strcmp(opType,"ConvF2D")==0 ||
3830         strcmp(opType,"ConvF2I")==0 ||
3831         strcmp(opType,"ConvF2L")==0 ||
3832         strcmp(opType,"ConvI2D")==0 ||
3833         strcmp(opType,"ConvI2F")==0 ||
3834         strcmp(opType,"ConvI2L")==0 ||
3835         strcmp(opType,"ConvL2D")==0 ||
3836         strcmp(opType,"ConvL2F")==0 ||
3837         strcmp(opType,"ConvL2I")==0 ||
3838         strcmp(opType,"DecodeN")==0 ||
3839         strcmp(opType,"EncodeP")==0 ||
3840         strcmp(opType,"RoundDouble")==0 ||
3841         strcmp(opType,"RoundFloat")==0 ||
3842         strcmp(opType,"ReverseBytesI")==0 ||
3843         strcmp(opType,"ReverseBytesL")==0 ||
3844         strcmp(opType,"Replicate16B")==0 ||
3845         strcmp(opType,"Replicate8B")==0 ||
3846         strcmp(opType,"Replicate4B")==0 ||
3847         strcmp(opType,"Replicate8C")==0 ||
3848         strcmp(opType,"Replicate4C")==0 ||
3849         strcmp(opType,"Replicate8S")==0 ||
3850         strcmp(opType,"Replicate4S")==0 ||
3851         strcmp(opType,"Replicate4I")==0 ||
3852         strcmp(opType,"Replicate2I")==0 ||
3853         strcmp(opType,"Replicate2L")==0 ||
3854         strcmp(opType,"Replicate4F")==0 ||
3855         strcmp(opType,"Replicate2F")==0 ||
3856         strcmp(opType,"Replicate2D")==0 ||
3857         0 /* 0 to line up columns nicely */ )
3858       return 1;
3859   }
3860   return 0;
3861 }
3862 
3863 bool MatchRule::is_ideal_unlock() const {
3864   if( !_opType ) return false;
3865   return !strcmp(_opType,"Unlock") || !strcmp(_opType,"FastUnlock");
3866 }
3867 
3868 
3869 bool MatchRule::is_ideal_call_leaf() const {
3870   if( !_opType ) return false;
3871   return !strcmp(_opType,"CallLeaf")     ||
3872          !strcmp(_opType,"CallLeafNoFP");
3873 }
3874 
3875 
3876 bool MatchRule::is_ideal_if() const {
3877   if( !_opType ) return false;
3878   return
3879     !strcmp(_opType,"If"            ) ||
3880     !strcmp(_opType,"CountedLoopEnd");
3881 }
3882 
3883 bool MatchRule::is_ideal_fastlock() const {
3884   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3885     return (strcmp(_rChild->_opType,"FastLock") == 0);
3886   }
3887   return false;
3888 }
3889 
3890 bool MatchRule::is_ideal_membar() const {
3891   if( !_opType ) return false;
3892   return
3893     !strcmp(_opType,"MemBarAcquire"  ) ||
3894     !strcmp(_opType,"MemBarRelease"  ) ||
3895     !strcmp(_opType,"MemBarVolatile" ) ||
3896     !strcmp(_opType,"MemBarCPUOrder" ) ;
3897 }
3898 
3899 bool MatchRule::is_ideal_loadPC() const {
3900   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3901     return (strcmp(_rChild->_opType,"LoadPC") == 0);
3902   }
3903   return false;
3904 }
3905 
3906 bool MatchRule::is_ideal_box() const {
3907   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3908     return (strcmp(_rChild->_opType,"Box") == 0);
3909   }
3910   return false;
3911 }
3912 
3913 bool MatchRule::is_ideal_goto() const {
3914   bool   ideal_goto = false;
3915 
3916   if( _opType && (strcmp(_opType,"Goto") == 0) ) {
3917     ideal_goto = true;
3918   }
3919   return ideal_goto;
3920 }
3921 
3922 bool MatchRule::is_ideal_jump() const {
3923   if( _opType ) {
3924     if( !strcmp(_opType,"Jump") )
3925       return true;
3926   }
3927   return false;
3928 }
3929 
3930 bool MatchRule::is_ideal_bool() const {
3931   if( _opType ) {
3932     if( !strcmp(_opType,"Bool") )
3933       return true;
3934   }
3935   return false;
3936 }
3937 
3938 
3939 Form::DataType MatchRule::is_ideal_load() const {
3940   Form::DataType ideal_load = Form::none;
3941 
3942   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3943     const char *opType = _rChild->_opType;
3944     ideal_load = is_load_from_memory(opType);
3945   }
3946 
3947   return ideal_load;
3948 }
3949 
3950 
3951 Form::DataType MatchRule::is_ideal_store() const {
3952   Form::DataType ideal_store = Form::none;
3953 
3954   if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
3955     const char *opType = _rChild->_opType;
3956     ideal_store = is_store_to_memory(opType);
3957   }
3958 
3959   return ideal_store;
3960 }
3961 
3962 
3963 void MatchRule::dump() {
3964   output(stderr);
3965 }
3966 
3967 void MatchRule::output(FILE *fp) {
3968   fprintf(fp,"MatchRule: ( %s",_name);
3969   if (_lChild) _lChild->output(fp);
3970   if (_rChild) _rChild->output(fp);
3971   fprintf(fp," )\n");
3972   fprintf(fp,"   nesting depth = %d\n", _depth);
3973   if (_result) fprintf(fp,"   Result Type = %s", _result);
3974   fprintf(fp,"\n");
3975 }
3976 
3977 //------------------------------Attribute--------------------------------------
3978 Attribute::Attribute(char *id, char* val, int type)
3979   : _ident(id), _val(val), _atype(type) {
3980 }
3981 Attribute::~Attribute() {
3982 }
3983 
3984 int Attribute::int_val(ArchDesc &ad) {
3985   // Make sure it is an integer constant:
3986   int result = 0;
3987   if (!_val || !ADLParser::is_int_token(_val, result)) {
3988     ad.syntax_err(0, "Attribute %s must have an integer value: %s",
3989                   _ident, _val ? _val : "");
3990   }
3991   return result;
3992 }
3993 
3994 void Attribute::dump() {
3995   output(stderr);
3996 } // Debug printer
3997 
3998 // Write to output files
3999 void Attribute::output(FILE *fp) {
4000   fprintf(fp,"Attribute: %s  %s\n", (_ident?_ident:""), (_val?_val:""));
4001 }
4002 
4003 //------------------------------FormatRule----------------------------------
4004 FormatRule::FormatRule(char *temp)
4005   : _temp(temp) {
4006 }
4007 FormatRule::~FormatRule() {
4008 }
4009 
4010 void FormatRule::dump() {
4011   output(stderr);
4012 }
4013 
4014 // Write to output files
4015 void FormatRule::output(FILE *fp) {
4016   fprintf(fp,"\nFormat Rule: \n%s", (_temp?_temp:""));
4017   fprintf(fp,"\n");
4018 }