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