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