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