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