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