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,"CastI2N")      ||
 782        !strcmp(_matrule->_rChild->_opType,"DecodeN")      ||
 783        !strcmp(_matrule->_rChild->_opType,"EncodeP")      ||
 784        !strcmp(_matrule->_rChild->_opType,"DecodeNKlass") ||
 785        !strcmp(_matrule->_rChild->_opType,"EncodePKlass") ||
 786        !strcmp(_matrule->_rChild->_opType,"LoadN")        ||
 787        !strcmp(_matrule->_rChild->_opType,"LoadNKlass")   ||
 788        !strcmp(_matrule->_rChild->_opType,"CreateEx")     ||  // type of exception
 789        !strcmp(_matrule->_rChild->_opType,"CheckCastPP")  ||
 790        !strcmp(_matrule->_rChild->_opType,"GetAndSetP")   ||
 791        !strcmp(_matrule->_rChild->_opType,"GetAndSetN")   ||
 792        !strcmp(_matrule->_rChild->_opType,"RotateLeft")   ||
 793        !strcmp(_matrule->_rChild->_opType,"RotateRight")   ||
 794 #if INCLUDE_SHENANDOAHGC
 795        !strcmp(_matrule->_rChild->_opType,"ShenandoahCompareAndExchangeP") ||
 796        !strcmp(_matrule->_rChild->_opType,"ShenandoahCompareAndExchangeN") ||
 797 #endif
 798        !strcmp(_matrule->_rChild->_opType,"StrInflatedCopy") ||
 799        !strcmp(_matrule->_rChild->_opType,"VectorCmpMasked")||
 800        !strcmp(_matrule->_rChild->_opType,"VectorMaskGen")||
 801        !strcmp(_matrule->_rChild->_opType,"VerifyVectorAlignment")||
 802        !strcmp(_matrule->_rChild->_opType,"CompareAndExchangeP") ||
 803        !strcmp(_matrule->_rChild->_opType,"CompareAndExchangeN"))) return true;
 804   else if ( is_ideal_load() == Form::idealP )                return true;
 805   else if ( is_ideal_store() != Form::none  )                return true;
 806 
 807   if (needs_base_oop_edge(globals)) return true;
 808 
 809   if (is_vector()) return true;
 810   if (is_mach_constant()) return true;
 811 
 812   return false;
 813 }
 814 
 815 
 816 // Access instr_cost attribute or return null.
 817 const char* InstructForm::cost() {
 818   for (Attribute* cur = _attribs; cur != nullptr; cur = (Attribute*)cur->_next) {
 819     if( strcmp(cur->_ident,AttributeForm::_ins_cost) == 0 ) {
 820       return cur->_val;
 821     }
 822   }
 823   return nullptr;
 824 }
 825 
 826 // Return count of top-level operands.
 827 uint InstructForm::num_opnds() {
 828   int  num_opnds = _components.num_operands();
 829 
 830   // Need special handling for matching some ideal nodes
 831   // i.e. Matching a return node
 832   /*
 833   if( _matrule ) {
 834     if( strcmp(_matrule->_opType,"Return"   )==0 ||
 835         strcmp(_matrule->_opType,"Halt"     )==0 )
 836       return 3;
 837   }
 838     */
 839   return num_opnds;
 840 }
 841 
 842 const char* InstructForm::opnd_ident(int idx) {
 843   return _components.at(idx)->_name;
 844 }
 845 
 846 const char* InstructForm::unique_opnd_ident(uint idx) {
 847   uint i;
 848   for (i = 1; i < num_opnds(); ++i) {
 849     if (unique_opnds_idx(i) == idx) {
 850       break;
 851     }
 852   }
 853   return (_components.at(i) != nullptr) ? _components.at(i)->_name : "";
 854 }
 855 
 856 // Return count of unmatched operands.
 857 uint InstructForm::num_post_match_opnds() {
 858   uint  num_post_match_opnds = _components.count();
 859   uint  num_match_opnds = _components.match_count();
 860   num_post_match_opnds = num_post_match_opnds - num_match_opnds;
 861 
 862   return num_post_match_opnds;
 863 }
 864 
 865 // Return the number of leaves below this complex operand
 866 uint InstructForm::num_consts(FormDict &globals) const {
 867   if ( ! _matrule) return 0;
 868 
 869   // This is a recursive invocation on all operands in the matchrule
 870   return _matrule->num_consts(globals);
 871 }
 872 
 873 // Constants in match rule with specified type
 874 uint InstructForm::num_consts(FormDict &globals, Form::DataType type) const {
 875   if ( ! _matrule) return 0;
 876 
 877   // This is a recursive invocation on all operands in the matchrule
 878   return _matrule->num_consts(globals, type);
 879 }
 880 
 881 
 882 // Return the register class associated with 'leaf'.
 883 const char *InstructForm::out_reg_class(FormDict &globals) {
 884   assert( false, "InstructForm::out_reg_class(FormDict &globals); Not Implemented");
 885 
 886   return nullptr;
 887 }
 888 
 889 
 890 
 891 // Lookup the starting position of inputs we are interested in wrt. ideal nodes
 892 uint InstructForm::oper_input_base(FormDict &globals) {
 893   if( !_matrule ) return 1;     // Skip control for most nodes
 894 
 895   // Need special handling for matching some ideal nodes
 896   // i.e. Matching a return node
 897   if( strcmp(_matrule->_opType,"Return"    )==0 ||
 898       strcmp(_matrule->_opType,"Rethrow"   )==0 ||
 899       strcmp(_matrule->_opType,"TailCall"  )==0 ||
 900       strcmp(_matrule->_opType,"TailJump"  )==0 ||
 901       strcmp(_matrule->_opType,"ForwardException")==0 ||
 902       strcmp(_matrule->_opType,"SafePoint" )==0 ||
 903       strcmp(_matrule->_opType,"Halt"      )==0 ||
 904       strcmp(_matrule->_opType,"CallLeafNoFP")==0)
 905     return AdlcVMDeps::Parms;   // Skip the machine-state edges
 906 
 907   if( _matrule->_rChild &&
 908       ( strcmp(_matrule->_rChild->_opType,"AryEq"     )==0 ||
 909         strcmp(_matrule->_rChild->_opType,"VectorizedHashCode")==0 ||
 910         strcmp(_matrule->_rChild->_opType,"StrComp"   )==0 ||
 911         strcmp(_matrule->_rChild->_opType,"StrEquals" )==0 ||
 912         strcmp(_matrule->_rChild->_opType,"StrInflatedCopy"   )==0 ||
 913         strcmp(_matrule->_rChild->_opType,"StrCompressedCopy" )==0 ||
 914         strcmp(_matrule->_rChild->_opType,"StrIndexOf")==0 ||
 915         strcmp(_matrule->_rChild->_opType,"StrIndexOfChar")==0 ||
 916         strcmp(_matrule->_rChild->_opType,"CountPositives")==0 ||
 917         strcmp(_matrule->_rChild->_opType,"EncodeISOArray")==0)) {
 918         // String.(compareTo/equals/indexOf/hashCode) and Arrays.equals
 919         // and sun.nio.cs.iso8859_1$Encoder.EncodeISOArray
 920         // take 1 control and 1 memory edges.
 921         // Also String.(compressedCopy/inflatedCopy).
 922     return 2;
 923   }
 924 
 925   // Check for handling of 'Memory' input/edge in the ideal world.
 926   // The AD file writer is shielded from knowledge of these edges.
 927   int base = 1;                 // Skip control
 928   base += _matrule->needs_ideal_memory_edge(globals);
 929 
 930   // Also skip the base-oop value for uses of derived oops.
 931   // The AD file writer is shielded from knowledge of these edges.
 932   base += needs_base_oop_edge(globals);
 933 
 934   return base;
 935 }
 936 
 937 // This function determines the order of the MachOper in _opnds[]
 938 // by writing the operand names into the _components list.
 939 //
 940 // Implementation does not modify state of internal structures
 941 void InstructForm::build_components() {
 942   // Add top-level operands to the components
 943   if (_matrule)  _matrule->append_components(_localNames, _components);
 944 
 945   // Add parameters that "do not appear in match rule".
 946   bool has_temp = false;
 947   const char *name;
 948   const char *kill_name = nullptr;
 949   for (_parameters.reset(); (name = _parameters.iter()) != nullptr;) {
 950     OpClassForm *opForm = _localNames[name]->is_opclass();
 951     assert(opForm != nullptr, "sanity");
 952 
 953     Effect* e = nullptr;
 954     {
 955       const Form* form = _effects[name];
 956       e = form ? form->is_effect() : nullptr;
 957     }
 958 
 959     if (e != nullptr) {
 960       has_temp |= e->is(Component::TEMP);
 961 
 962       // KILLs must be declared after any TEMPs because TEMPs are real
 963       // uses so their operand numbering must directly follow the real
 964       // inputs from the match rule.  Fixing the numbering seems
 965       // complex so simply enforce the restriction during parse.
 966       if (kill_name != nullptr &&
 967           e->isa(Component::TEMP) && !e->isa(Component::DEF)) {
 968         OpClassForm* kill = _localNames[kill_name]->is_opclass();
 969         assert(kill != nullptr, "sanity");
 970         globalAD->syntax_err(_linenum, "%s: %s %s must be at the end of the argument list\n",
 971                              _ident, kill->_ident, kill_name);
 972       } else if (e->isa(Component::KILL) && !e->isa(Component::USE)) {
 973         kill_name = name;
 974       }
 975     }
 976 
 977     const Component *component  = _components.search(name);
 978     if ( component  == nullptr ) {
 979       if (e) {
 980         _components.insert(name, opForm->_ident, e->_use_def, false);
 981         component = _components.search(name);
 982         if (component->isa(Component::USE) && !component->isa(Component::TEMP) && _matrule) {
 983           const Form *form = globalAD->globalNames()[component->_type];
 984           assert( form, "component type must be a defined form");
 985           OperandForm *op   = form->is_operand();
 986           if (op->_interface && op->_interface->is_RegInterface()) {
 987             globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
 988                                  _ident, opForm->_ident, name);
 989           }
 990         }
 991       } else {
 992         // This would be a nice warning but it triggers in a few places in a benign way
 993         // if (_matrule != nullptr && !expands()) {
 994         //   globalAD->syntax_err(_linenum, "%s: %s %s not mentioned in effect or match rule\n",
 995         //                        _ident, opForm->_ident, name);
 996         // }
 997         _components.insert(name, opForm->_ident, Component::INVALID, false);
 998       }
 999     }
1000     else if (e) {
1001       // Component was found in the list
1002       // Check if there is a new effect that requires an extra component.
1003       // This happens when adding 'USE' to a component that is not yet one.
1004       if ((!component->isa( Component::USE) && ((e->_use_def & Component::USE) != 0))) {
1005         if (component->isa(Component::USE) && _matrule) {
1006           const Form *form = globalAD->globalNames()[component->_type];
1007           assert( form, "component type must be a defined form");
1008           OperandForm *op   = form->is_operand();
1009           if (op->_interface && op->_interface->is_RegInterface()) {
1010             globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
1011                                  _ident, opForm->_ident, name);
1012           }
1013         }
1014         _components.insert(name, opForm->_ident, e->_use_def, false);
1015       } else {
1016         Component  *comp = (Component*)component;
1017         comp->promote_use_def_info(e->_use_def);
1018       }
1019       // Component positions are zero based.
1020       int  pos  = _components.operand_position(name);
1021       assert( ! (component->isa(Component::DEF) && (pos >= 1)),
1022               "Component::DEF can only occur in the first position");
1023     }
1024   }
1025 
1026   // Resolving the interactions between expand rules and TEMPs would
1027   // be complex so simply disallow it.
1028   if (_matrule == nullptr && has_temp) {
1029     globalAD->syntax_err(_linenum, "%s: TEMPs without match rule isn't supported\n", _ident);
1030   }
1031 
1032   return;
1033 }
1034 
1035 // Return zero-based position in component list;  -1 if not in list.
1036 int   InstructForm::operand_position(const char *name, int usedef) {
1037   return unique_opnds_idx(_components.operand_position(name, usedef, this));
1038 }
1039 
1040 int   InstructForm::operand_position_format(const char *name) {
1041   return unique_opnds_idx(_components.operand_position_format(name, this));
1042 }
1043 
1044 // Return zero-based position in component list; -1 if not in list.
1045 int   InstructForm::label_position() {
1046   return unique_opnds_idx(_components.label_position());
1047 }
1048 
1049 int   InstructForm::method_position() {
1050   return unique_opnds_idx(_components.method_position());
1051 }
1052 
1053 // Return number of relocation entries needed for this instruction.
1054 uint  InstructForm::reloc(FormDict &globals) {
1055   uint reloc_entries  = 0;
1056   // Check for "Call" nodes
1057   if ( is_ideal_call() )      ++reloc_entries;
1058   if ( is_ideal_return() )    ++reloc_entries;
1059   if ( is_ideal_safepoint() ) ++reloc_entries;
1060 
1061 
1062   // Check if operands MAYBE oop pointers, by checking for ConP elements
1063   // Proceed through the leaves of the match-tree and check for ConPs
1064   if ( _matrule != nullptr ) {
1065     uint         position = 0;
1066     const char  *result   = nullptr;
1067     const char  *name     = nullptr;
1068     const char  *opType   = nullptr;
1069     while (_matrule->base_operand(position, globals, result, name, opType)) {
1070       if ( strcmp(opType,"ConP") == 0 ) {
1071         ++reloc_entries;
1072       }
1073       ++position;
1074     }
1075   }
1076 
1077   // Above is only a conservative estimate
1078   // because it did not check contents of operand classes.
1079   // !!!!! !!!!!
1080   // Add 1 to reloc info for each operand class in the component list.
1081   Component  *comp;
1082   _components.reset();
1083   while ( (comp = _components.iter()) != nullptr ) {
1084     const Form        *form = globals[comp->_type];
1085     assert( form, "Did not find component's type in global names");
1086     const OpClassForm *opc  = form->is_opclass();
1087     const OperandForm *oper = form->is_operand();
1088     if ( opc && (oper == nullptr) ) {
1089       ++reloc_entries;
1090     } else if ( oper ) {
1091       // floats and doubles loaded out of method's constant pool require reloc info
1092       Form::DataType type = oper->is_base_constant(globals);
1093       if ( (type == Form::idealF) || (type == Form::idealD) ) {
1094         ++reloc_entries;
1095       }
1096     }
1097   }
1098 
1099   // Float and Double constants may come from the CodeBuffer table
1100   // and require relocatable addresses for access
1101   // !!!!!
1102   // Check for any component being an immediate float or double.
1103   Form::DataType data_type = is_chain_of_constant(globals);
1104   if( data_type==idealD || data_type==idealF ) {
1105     reloc_entries++;
1106   }
1107 
1108   return reloc_entries;
1109 }
1110 
1111 // Utility function defined in archDesc.cpp
1112 extern bool is_def(int usedef);
1113 
1114 // Return the result of reducing an instruction
1115 const char *InstructForm::reduce_result() {
1116   const char* result = "Universe";  // default
1117   _components.reset();
1118   Component *comp = _components.iter();
1119   if (comp != nullptr && comp->isa(Component::DEF)) {
1120     result = comp->_type;
1121     // Override this if the rule is a store operation:
1122     if (_matrule && _matrule->_rChild &&
1123         is_store_to_memory(_matrule->_rChild->_opType))
1124       result = "Universe";
1125   }
1126   return result;
1127 }
1128 
1129 // Return the name of the operand on the right hand side of the binary match
1130 // Return null if there is no right hand side
1131 const char *InstructForm::reduce_right(FormDict &globals)  const {
1132   if( _matrule == nullptr ) return nullptr;
1133   return  _matrule->reduce_right(globals);
1134 }
1135 
1136 // Similar for left
1137 const char *InstructForm::reduce_left(FormDict &globals)   const {
1138   if( _matrule == nullptr ) return nullptr;
1139   return  _matrule->reduce_left(globals);
1140 }
1141 
1142 
1143 // Base class for this instruction, MachNode except for calls
1144 const char *InstructForm::mach_base_class(FormDict &globals)  const {
1145   if( is_ideal_call() == Form::JAVA_STATIC ) {
1146     return "MachCallStaticJavaNode";
1147   }
1148   else if( is_ideal_call() == Form::JAVA_DYNAMIC ) {
1149     return "MachCallDynamicJavaNode";
1150   }
1151   else if( is_ideal_call() == Form::JAVA_RUNTIME ) {
1152     return "MachCallRuntimeNode";
1153   }
1154   else if( is_ideal_call() == Form::JAVA_LEAF ) {
1155     return "MachCallLeafNode";
1156   }
1157   else if (is_ideal_return()) {
1158     return "MachReturnNode";
1159   }
1160   else if (is_ideal_halt()) {
1161     return "MachHaltNode";
1162   }
1163   else if (is_ideal_safepoint()) {
1164     return "MachSafePointNode";
1165   }
1166   else if (is_ideal_if()) {
1167     return "MachIfNode";
1168   }
1169   else if (is_ideal_goto()) {
1170     return "MachGotoNode";
1171   }
1172   else if (is_ideal_fastlock()) {
1173     return "MachFastLockNode";
1174   }
1175   else if (is_ideal_nop()) {
1176     return "MachNopNode";
1177   }
1178   else if( is_ideal_membar()) {
1179     return "MachMemBarNode";
1180   }
1181   else if (is_ideal_jump()) {
1182     return "MachJumpNode";
1183   }
1184   else if (is_mach_constant()) {
1185     return "MachConstantNode";
1186   }
1187   else if (captures_bottom_type(globals)) {
1188     return "MachTypeNode";
1189   } else {
1190     return "MachNode";
1191   }
1192   assert( false, "ShouldNotReachHere()");
1193   return nullptr;
1194 }
1195 
1196 // Compare the instruction predicates for textual equality
1197 bool equivalent_predicates( const InstructForm *instr1, const InstructForm *instr2 ) {
1198   const Predicate *pred1  = instr1->_predicate;
1199   const Predicate *pred2  = instr2->_predicate;
1200   if( pred1 == nullptr && pred2 == nullptr ) {
1201     // no predicates means they are identical
1202     return true;
1203   }
1204   if( pred1 != nullptr && pred2 != nullptr ) {
1205     // compare the predicates
1206     if (ADLParser::equivalent_expressions(pred1->_pred, pred2->_pred)) {
1207       return true;
1208     }
1209   }
1210 
1211   return false;
1212 }
1213 
1214 // Check if this instruction can cisc-spill to 'alternate'
1215 bool InstructForm::cisc_spills_to(ArchDesc &AD, InstructForm *instr) {
1216   assert( _matrule != nullptr && instr->_matrule != nullptr, "must have match rules");
1217   // Do not replace if a cisc-version has been found.
1218   if( cisc_spill_operand() != Not_cisc_spillable ) return false;
1219 
1220   int         cisc_spill_operand = Maybe_cisc_spillable;
1221   char       *result             = nullptr;
1222   char       *result2            = nullptr;
1223   const char *op_name            = nullptr;
1224   const char *reg_type           = nullptr;
1225   FormDict   &globals            = AD.globalNames();
1226   cisc_spill_operand = _matrule->matchrule_cisc_spill_match(globals, AD.get_registers(), instr->_matrule, op_name, reg_type);
1227   if( (cisc_spill_operand != Not_cisc_spillable) && (op_name != nullptr) && equivalent_predicates(this, instr) ) {
1228     cisc_spill_operand = operand_position(op_name, Component::USE);
1229     int def_oper  = operand_position(op_name, Component::DEF);
1230     if( def_oper == NameList::Not_in_list && instr->num_opnds() == num_opnds()) {
1231       // Do not support cisc-spilling for destination operands and
1232       // make sure they have the same number of operands.
1233       _cisc_spill_alternate = instr;
1234       instr->set_cisc_alternate(true);
1235       if( AD._cisc_spill_debug ) {
1236         fprintf(stderr, "Instruction %s cisc-spills-to %s\n", _ident, instr->_ident);
1237         fprintf(stderr, "   using operand %s %s at index %d\n", reg_type, op_name, cisc_spill_operand);
1238       }
1239       // Record that a stack-version of the reg_mask is needed
1240       // !!!!!
1241       OperandForm *oper = (OperandForm*)(globals[reg_type]->is_operand());
1242       assert( oper != nullptr, "cisc-spilling non operand");
1243       const char *reg_class_name = oper->constrained_reg_class();
1244       AD.set_stack_or_reg(reg_class_name);
1245       const char *reg_mask_name  = AD.reg_mask(*oper);
1246       set_cisc_reg_mask_name(reg_mask_name);
1247       const char *stack_or_reg_mask_name = AD.stack_or_reg_mask(*oper);
1248     } else {
1249       cisc_spill_operand = Not_cisc_spillable;
1250     }
1251   } else {
1252     cisc_spill_operand = Not_cisc_spillable;
1253   }
1254 
1255   set_cisc_spill_operand(cisc_spill_operand);
1256   return (cisc_spill_operand != Not_cisc_spillable);
1257 }
1258 
1259 // Check to see if this instruction can be replaced with the short branch
1260 // instruction `short-branch'
1261 bool InstructForm::check_branch_variant(ArchDesc &AD, InstructForm *short_branch) {
1262   if (_matrule != nullptr &&
1263       this != short_branch &&   // Don't match myself
1264       !is_short_branch() &&     // Don't match another short branch variant
1265       reduce_result() != nullptr &&
1266       strstr(_ident, "restoreMask") == nullptr && // Don't match side effects
1267       strcmp(reduce_result(), short_branch->reduce_result()) == 0 &&
1268       _matrule->equivalent(AD.globalNames(), short_branch->_matrule)) {
1269     // The instructions are equivalent.
1270 
1271     // Now verify that both instructions have the same parameters and
1272     // the same effects. Both branch forms should have the same inputs
1273     // and resulting projections to correctly replace a long branch node
1274     // with corresponding short branch node during code generation.
1275 
1276     bool different = false;
1277     if (short_branch->_components.count() != _components.count()) {
1278        different = true;
1279     } else if (_components.count() > 0) {
1280       short_branch->_components.reset();
1281       _components.reset();
1282       Component *comp;
1283       while ((comp = _components.iter()) != nullptr) {
1284         Component *short_comp = short_branch->_components.iter();
1285         if (short_comp == nullptr ||
1286             short_comp->_type != comp->_type ||
1287             short_comp->_usedef != comp->_usedef) {
1288           different = true;
1289           break;
1290         }
1291       }
1292       if (short_branch->_components.iter() != nullptr)
1293         different = true;
1294     }
1295     if (different) {
1296       globalAD->syntax_err(short_branch->_linenum, "Instruction %s and its short form %s have different parameters\n", _ident, short_branch->_ident);
1297     }
1298     if (AD._adl_debug > 1 || AD._short_branch_debug) {
1299       fprintf(stderr, "Instruction %s has short form %s\n", _ident, short_branch->_ident);
1300     }
1301     _short_branch_form = short_branch;
1302     return true;
1303   }
1304   return false;
1305 }
1306 
1307 
1308 // --------------------------- FILE *output_routines
1309 //
1310 // Generate the format call for the replacement variable
1311 void InstructForm::rep_var_format(FILE *fp, const char *rep_var) {
1312   // Handle special constant table variables.
1313   if (strcmp(rep_var, "constanttablebase") == 0) {
1314     fprintf(fp, "char reg[128];  ra->dump_register(in(mach_constant_base_node_input()), reg, sizeof(reg));\n");
1315     fprintf(fp, "    st->print(\"%%s\", reg);\n");
1316     return;
1317   }
1318   if (strcmp(rep_var, "constantoffset") == 0) {
1319     fprintf(fp, "st->print(\"#%%d\", constant_offset_unchecked());\n");
1320     return;
1321   }
1322   if (strcmp(rep_var, "constantaddress") == 0) {
1323     fprintf(fp, "st->print(\"constant table base + #%%d\", constant_offset_unchecked());\n");
1324     return;
1325   }
1326 
1327   // Find replacement variable's type
1328   const Form *form   = _localNames[rep_var];
1329   if (form == nullptr) {
1330     globalAD->syntax_err(_linenum, "Unknown replacement variable %s in format statement of %s.",
1331                          rep_var, _ident);
1332     return;
1333   }
1334   OpClassForm *opc   = form->is_opclass();
1335   assert( opc, "replacement variable was not found in local names");
1336   // Lookup the index position of the replacement variable
1337   int idx  = operand_position_format(rep_var);
1338   if ( idx == -1 ) {
1339     globalAD->syntax_err(_linenum, "Could not find replacement variable %s in format statement of %s.\n",
1340                          rep_var, _ident);
1341     assert(strcmp(opc->_ident, "label") == 0, "Unimplemented");
1342     return;
1343   }
1344 
1345   if (is_noninput_operand(idx)) {
1346     // This component isn't in the input array.  Print out the static
1347     // name of the register.
1348     OperandForm* oper = form->is_operand();
1349     if (oper != nullptr && oper->is_bound_register()) {
1350       const RegDef* first = oper->get_RegClass()->find_first_elem();
1351       fprintf(fp, "    st->print_raw(\"%s\");\n", first->_regname);
1352     } else {
1353       globalAD->syntax_err(_linenum, "In %s can't find format for %s %s", _ident, opc->_ident, rep_var);
1354     }
1355   } else {
1356     // Output the format call for this operand
1357     fprintf(fp,"opnd_array(%d)->",idx);
1358     if (idx == 0)
1359       fprintf(fp,"int_format(ra, this, st); // %s\n", rep_var);
1360     else
1361       fprintf(fp,"ext_format(ra, this,idx%d, st); // %s\n", idx, rep_var );
1362   }
1363 }
1364 
1365 // Search through operands to determine parameters unique positions.
1366 void InstructForm::set_unique_opnds() {
1367   uint* uniq_idx = nullptr;
1368   uint  nopnds = num_opnds();
1369   uint  num_uniq = nopnds;
1370   uint i;
1371   _uniq_idx_length = 0;
1372   if (nopnds > 0) {
1373     // Allocate index array.  Worst case we're mapping from each
1374     // component back to an index and any DEF always goes at 0 so the
1375     // length of the array has to be the number of components + 1.
1376     _uniq_idx_length = _components.count() + 1;
1377     uniq_idx = (uint*) AdlAllocateHeap(sizeof(uint) * _uniq_idx_length);
1378     for (i = 0; i < _uniq_idx_length; i++) {
1379       uniq_idx[i] = i;
1380     }
1381   }
1382   // Do it only if there is a match rule and no expand rule.  With an
1383   // expand rule it is done by creating new mach node in Expand()
1384   // method.
1385   if (nopnds > 0 && _matrule != nullptr && _exprule == nullptr) {
1386     const char *name;
1387     uint count;
1388     bool has_dupl_use = false;
1389 
1390     _parameters.reset();
1391     while ((name = _parameters.iter()) != nullptr) {
1392       count = 0;
1393       uint position = 0;
1394       uint uniq_position = 0;
1395       _components.reset();
1396       Component *comp = nullptr;
1397       if (sets_result()) {
1398         comp = _components.iter();
1399         position++;
1400       }
1401       // The next code is copied from the method operand_position().
1402       for (; (comp = _components.iter()) != nullptr; ++position) {
1403         // When the first component is not a DEF,
1404         // leave space for the result operand!
1405         if (position==0 && (!comp->isa(Component::DEF))) {
1406           ++position;
1407         }
1408         if (strcmp(name, comp->_name) == 0) {
1409           if (++count > 1) {
1410             assert(position < _uniq_idx_length, "out of bounds");
1411             uniq_idx[position] = uniq_position;
1412             has_dupl_use = true;
1413           } else {
1414             uniq_position = position;
1415           }
1416         }
1417         if (comp->isa(Component::DEF) && comp->isa(Component::USE)) {
1418           ++position;
1419           if (position != 1)
1420             --position;   // only use two slots for the 1st USE_DEF
1421         }
1422       }
1423     }
1424     if (has_dupl_use) {
1425       for (i = 1; i < nopnds; i++) {
1426         if (i != uniq_idx[i]) {
1427           break;
1428         }
1429       }
1430       uint j = i;
1431       for (; i < nopnds; i++) {
1432         if (i == uniq_idx[i]) {
1433           uniq_idx[i] = j++;
1434         }
1435       }
1436       num_uniq = j;
1437     }
1438   }
1439   _uniq_idx = uniq_idx;
1440   _num_uniq = num_uniq;
1441 }
1442 
1443 // Generate index values needed for determining the operand position
1444 void InstructForm::index_temps(FILE *fp, FormDict &globals, const char *prefix, const char *receiver) {
1445   uint  idx = 0;                  // position of operand in match rule
1446   int   cur_num_opnds = num_opnds();
1447 
1448   // Compute the index into vector of operand pointers:
1449   // idx0=0 is used to indicate that info comes from this same node, not from input edge.
1450   // idx1 starts at oper_input_base()
1451   if ( cur_num_opnds >= 1 ) {
1452     fprintf(fp,"  // Start at oper_input_base() and count operands\n");
1453     fprintf(fp,"  unsigned %sidx0 = %d;\n", prefix, oper_input_base(globals));
1454     fprintf(fp,"  unsigned %sidx1 = %d;", prefix, oper_input_base(globals));
1455     fprintf(fp," \t// %s\n", unique_opnd_ident(1));
1456 
1457     // Generate starting points for other unique operands if they exist
1458     for ( idx = 2; idx < num_unique_opnds(); ++idx ) {
1459       if( *receiver == 0 ) {
1460         fprintf(fp,"  unsigned %sidx%d = %sidx%d + opnd_array(%d)->num_edges();",
1461                 prefix, idx, prefix, idx-1, idx-1 );
1462       } else {
1463         fprintf(fp,"  unsigned %sidx%d = %sidx%d + %s_opnds[%d]->num_edges();",
1464                 prefix, idx, prefix, idx-1, receiver, idx-1 );
1465       }
1466       fprintf(fp," \t// %s\n", unique_opnd_ident(idx));
1467     }
1468   }
1469   if( *receiver != 0 ) {
1470     // This value is used by generate_peepreplace when copying a node.
1471     // Don't emit it in other cases since it can hide bugs with the
1472     // use invalid idx's.
1473     fprintf(fp,"  unsigned %sidx%d = %sreq(); \n", prefix, idx, receiver);
1474   }
1475 
1476 }
1477 
1478 // ---------------------------
1479 bool InstructForm::verify() {
1480   // !!!!! !!!!!
1481   // Check that a "label" operand occurs last in the operand list, if present
1482   return true;
1483 }
1484 
1485 void InstructForm::dump() {
1486   output(stderr);
1487 }
1488 
1489 void InstructForm::output(FILE *fp) {
1490   fprintf(fp,"\nInstruction: %s\n", (_ident?_ident:""));
1491   if (_matrule)   _matrule->output(fp);
1492   if (_insencode) _insencode->output(fp);
1493   if (_constant)  _constant->output(fp);
1494   if (_opcode)    _opcode->output(fp);
1495   if (_attribs)   _attribs->output(fp);
1496   if (_predicate) _predicate->output(fp);
1497   if (_effects.Size()) {
1498     fprintf(fp,"Effects\n");
1499     _effects.dump();
1500   }
1501   if (_exprule)   _exprule->output(fp);
1502   if (_rewrule)   _rewrule->output(fp);
1503   if (_format)    _format->output(fp);
1504   if (_peephole)  _peephole->output(fp);
1505 }
1506 
1507 void InstructForm::forms_do(FormClosure *f) {
1508   if (_cisc_spill_alternate) f->do_form(_cisc_spill_alternate);
1509   if (_short_branch_form) f->do_form(_short_branch_form);
1510   _localNames.forms_do(f);
1511   if (_matrule) f->do_form(_matrule);
1512   if (_opcode) f->do_form(_opcode);
1513   if (_insencode) f->do_form(_insencode);
1514   if (_constant) f->do_form(_constant);
1515   if (_attribs) f->do_form(_attribs);
1516   if (_predicate) f->do_form(_predicate);
1517   _effects.forms_do(f);
1518   if (_exprule) f->do_form(_exprule);
1519   if (_rewrule) f->do_form(_rewrule);
1520   if (_format) f->do_form(_format);
1521   if (_peephole) f->do_form(_peephole);
1522   assert(_components.count() == 0, "skip components");
1523 }
1524 
1525 void MachNodeForm::dump() {
1526   output(stderr);
1527 }
1528 
1529 void MachNodeForm::output(FILE *fp) {
1530   fprintf(fp,"\nMachNode: %s\n", (_ident?_ident:""));
1531 }
1532 
1533 //------------------------------build_predicate--------------------------------
1534 // Build instruction predicates.  If the user uses the same operand name
1535 // twice, we need to check that the operands are pointer-eequivalent in
1536 // the DFA during the labeling process.
1537 Predicate *InstructForm::build_predicate() {
1538   const int buflen = 1024;
1539   char buf[buflen], *s=buf;
1540   Dict names(cmpstr,hashstr,Form::arena);       // Map Names to counts
1541 
1542   MatchNode *mnode =
1543     strcmp(_matrule->_opType, "Set") ? _matrule : _matrule->_rChild;
1544   if (mnode != nullptr) mnode->count_instr_names(names);
1545 
1546   uint first = 1;
1547   // Start with the predicate supplied in the .ad file.
1548   if (_predicate) {
1549     if (first) first = 0;
1550     strcpy(s, "("); s += strlen(s);
1551     strncpy(s, _predicate->_pred, buflen - strlen(s) - 1);
1552     s += strlen(s);
1553     strcpy(s, ")"); s += strlen(s);
1554   }
1555   for( DictI i(&names); i.test(); ++i ) {
1556     uintptr_t cnt = (uintptr_t)i._value;
1557     if( cnt > 1 ) {             // Need a predicate at all?
1558       int path_bitmask = 0;
1559       assert( cnt == 2, "Unimplemented" );
1560       // Handle many pairs
1561       if( first ) first=0;
1562       else {                    // All tests must pass, so use '&&'
1563         strcpy(s," && ");
1564         s += strlen(s);
1565       }
1566       // Add predicate to working buffer
1567       snprintf_checked(s, remaining_buflen(buf, s), "/*%s*/(",(char*)i._key);
1568       s += strlen(s);
1569       mnode->build_instr_pred(s,(char*)i._key, 0, path_bitmask, 0);
1570       s += strlen(s);
1571       strcpy(s," == "); s += strlen(s);
1572       mnode->build_instr_pred(s,(char*)i._key, 1, path_bitmask, 0);
1573       s += strlen(s);
1574       strcpy(s,")"); s += strlen(s);
1575     }
1576   }
1577   if( s == buf ) s = nullptr;
1578   else {
1579     assert( strlen(buf) < sizeof(buf), "String buffer overflow" );
1580     s = strdup(buf);
1581   }
1582   return new Predicate(s);
1583 }
1584 
1585 //------------------------------EncodeForm-------------------------------------
1586 // Constructor
1587 EncodeForm::EncodeForm()
1588   : _encClass(cmpstr,hashstr, Form::arena) {
1589 }
1590 EncodeForm::~EncodeForm() {
1591 }
1592 
1593 // record a new register class
1594 EncClass *EncodeForm::add_EncClass(const char *className) {
1595   EncClass *encClass = new EncClass(className);
1596   _eclasses.addName(className);
1597   _encClass.Insert(className,encClass);
1598   return encClass;
1599 }
1600 
1601 // Lookup the function body for an encoding class
1602 EncClass  *EncodeForm::encClass(const char *className) {
1603   assert( className != nullptr, "Must provide a defined encoding name");
1604 
1605   EncClass *encClass = (EncClass*)_encClass[className];
1606   return encClass;
1607 }
1608 
1609 // Lookup the function body for an encoding class
1610 const char *EncodeForm::encClassBody(const char *className) {
1611   if( className == nullptr ) return nullptr;
1612 
1613   EncClass *encClass = (EncClass*)_encClass[className];
1614   assert( encClass != nullptr, "Encode Class is missing.");
1615   encClass->_code.reset();
1616   const char *code = (const char*)encClass->_code.iter();
1617   assert( code != nullptr, "Found an empty encode class body.");
1618 
1619   return code;
1620 }
1621 
1622 // Lookup the function body for an encoding class
1623 const char *EncodeForm::encClassPrototype(const char *className) {
1624   assert( className != nullptr, "Encode class name must be non null.");
1625 
1626   return className;
1627 }
1628 
1629 void EncodeForm::dump() {                  // Debug printer
1630   output(stderr);
1631 }
1632 
1633 void EncodeForm::output(FILE *fp) {          // Write info to output files
1634   const char *name;
1635   fprintf(fp,"\n");
1636   fprintf(fp,"-------------------- Dump EncodeForm --------------------\n");
1637   for (_eclasses.reset(); (name = _eclasses.iter()) != nullptr;) {
1638     ((EncClass*)_encClass[name])->output(fp);
1639   }
1640   fprintf(fp,"-------------------- end  EncodeForm --------------------\n");
1641 }
1642 
1643 void EncodeForm::forms_do(FormClosure* f) {
1644   const char *name;
1645   for (_eclasses.reset(); (name = _eclasses.iter()) != nullptr;) {
1646     f->do_form((EncClass*)_encClass[name]);
1647   }
1648 }
1649 
1650 //------------------------------EncClass---------------------------------------
1651 EncClass::EncClass(const char *name)
1652   : _localNames(cmpstr,hashstr, Form::arena), _name(name) {
1653 }
1654 EncClass::~EncClass() {
1655 }
1656 
1657 // Add a parameter <type,name> pair
1658 void EncClass::add_parameter(const char *parameter_type, const char *parameter_name) {
1659   _parameter_type.addName( parameter_type );
1660   _parameter_name.addName( parameter_name );
1661 }
1662 
1663 // Verify operand types in parameter list
1664 bool EncClass::check_parameter_types(FormDict &globals) {
1665   // !!!!!
1666   return false;
1667 }
1668 
1669 // Add the decomposed "code" sections of an encoding's code-block
1670 void EncClass::add_code(const char *code) {
1671   _code.addName(code);
1672 }
1673 
1674 // Add the decomposed "replacement variables" of an encoding's code-block
1675 void EncClass::add_rep_var(char *replacement_var) {
1676   _code.addName(NameList::_signal);
1677   _rep_vars.addName(replacement_var);
1678 }
1679 
1680 // Lookup the function body for an encoding class
1681 int EncClass::rep_var_index(const char *rep_var) {
1682   uint        position = 0;
1683   const char *name     = nullptr;
1684 
1685   _parameter_name.reset();
1686   while ( (name = _parameter_name.iter()) != nullptr ) {
1687     if ( strcmp(rep_var,name) == 0 ) return position;
1688     ++position;
1689   }
1690 
1691   return -1;
1692 }
1693 
1694 // Check after parsing
1695 bool EncClass::verify() {
1696   // 1!!!!
1697   // Check that each replacement variable, '$name' in architecture description
1698   // is actually a local variable for this encode class, or a reserved name
1699   // "primary, secondary, tertiary"
1700   return true;
1701 }
1702 
1703 void EncClass::dump() {
1704   output(stderr);
1705 }
1706 
1707 // Write info to output files
1708 void EncClass::output(FILE *fp) {
1709   fprintf(fp,"EncClass: %s", (_name ? _name : ""));
1710 
1711   // Output the parameter list
1712   _parameter_type.reset();
1713   _parameter_name.reset();
1714   const char *type = _parameter_type.iter();
1715   const char *name = _parameter_name.iter();
1716   fprintf(fp, " ( ");
1717   for ( ; (type != nullptr) && (name != nullptr);
1718         (type = _parameter_type.iter()), (name = _parameter_name.iter()) ) {
1719     fprintf(fp, " %s %s,", type, name);
1720   }
1721   fprintf(fp, " ) ");
1722 
1723   // Output the code block
1724   _code.reset();
1725   _rep_vars.reset();
1726   const char *code;
1727   while ( (code = _code.iter()) != nullptr ) {
1728     if ( _code.is_signal(code) ) {
1729       // A replacement variable
1730       const char *rep_var = _rep_vars.iter();
1731       fprintf(fp,"($%s)", rep_var);
1732     } else {
1733       // A section of code
1734       fprintf(fp,"%s", code);
1735     }
1736   }
1737 
1738 }
1739 
1740 void EncClass::forms_do(FormClosure *f) {
1741   _parameter_type.reset();
1742   const char *type = _parameter_type.iter();
1743   for ( ; type != nullptr ; type = _parameter_type.iter() ) {
1744     f->do_form_by_name(type);
1745   }
1746   _localNames.forms_do(f);
1747 }
1748 
1749 //------------------------------Opcode-----------------------------------------
1750 Opcode::Opcode(char *primary, char *secondary, char *tertiary)
1751   : _primary(primary), _secondary(secondary), _tertiary(tertiary) {
1752 }
1753 
1754 Opcode::~Opcode() {
1755 }
1756 
1757 Opcode::opcode_type Opcode::as_opcode_type(const char *param) {
1758   if( strcmp(param,"primary") == 0 ) {
1759     return Opcode::PRIMARY;
1760   }
1761   else if( strcmp(param,"secondary") == 0 ) {
1762     return Opcode::SECONDARY;
1763   }
1764   else if( strcmp(param,"tertiary") == 0 ) {
1765     return Opcode::TERTIARY;
1766   }
1767   return Opcode::NOT_AN_OPCODE;
1768 }
1769 
1770 bool Opcode::print_opcode(FILE *fp, Opcode::opcode_type desired_opcode) {
1771   // Default values previously provided by MachNode::primary()...
1772   const char *description = nullptr;
1773   const char *value       = nullptr;
1774   // Check if user provided any opcode definitions
1775   // Update 'value' if user provided a definition in the instruction
1776   switch (desired_opcode) {
1777   case PRIMARY:
1778     description = "primary()";
1779     if( _primary   != nullptr)  { value = _primary;     }
1780     break;
1781   case SECONDARY:
1782     description = "secondary()";
1783     if( _secondary != nullptr ) { value = _secondary;   }
1784     break;
1785   case TERTIARY:
1786     description = "tertiary()";
1787     if( _tertiary  != nullptr ) { value = _tertiary;    }
1788     break;
1789   default:
1790     assert( false, "ShouldNotReachHere();");
1791     break;
1792   }
1793 
1794   if (value != nullptr) {
1795     fprintf(fp, "(%s /*%s*/)", value, description);
1796   }
1797   return value != nullptr;
1798 }
1799 
1800 void Opcode::dump() {
1801   output(stderr);
1802 }
1803 
1804 // Write info to output files
1805 void Opcode::output(FILE *fp) {
1806   if (_primary   != nullptr) fprintf(fp,"Primary   opcode: %s\n", _primary);
1807   if (_secondary != nullptr) fprintf(fp,"Secondary opcode: %s\n", _secondary);
1808   if (_tertiary  != nullptr) fprintf(fp,"Tertiary  opcode: %s\n", _tertiary);
1809 }
1810 
1811 //------------------------------InsEncode--------------------------------------
1812 InsEncode::InsEncode() {
1813 }
1814 InsEncode::~InsEncode() {
1815 }
1816 
1817 // Add "encode class name" and its parameters
1818 NameAndList *InsEncode::add_encode(char *encoding) {
1819   assert( encoding != nullptr, "Must provide name for encoding");
1820 
1821   // add_parameter(NameList::_signal);
1822   NameAndList *encode = new NameAndList(encoding);
1823   _encoding.addName((char*)encode);
1824 
1825   return encode;
1826 }
1827 
1828 // Access the list of encodings
1829 void InsEncode::reset() {
1830   _encoding.reset();
1831   // _parameter.reset();
1832 }
1833 const char* InsEncode::encode_class_iter() {
1834   NameAndList  *encode_class = (NameAndList*)_encoding.iter();
1835   return  ( encode_class != nullptr ? encode_class->name() : nullptr );
1836 }
1837 // Obtain parameter name from zero based index
1838 const char *InsEncode::rep_var_name(InstructForm &inst, uint param_no) {
1839   NameAndList *params = (NameAndList*)_encoding.current();
1840   assert( params != nullptr, "Internal Error");
1841   const char *param = (*params)[param_no];
1842 
1843   // Remove '$' if parser placed it there.
1844   return ( param != nullptr && *param == '$') ? (param+1) : param;
1845 }
1846 
1847 void InsEncode::dump() {
1848   output(stderr);
1849 }
1850 
1851 // Write info to output files
1852 void InsEncode::output(FILE *fp) {
1853   NameAndList *encoding  = nullptr;
1854   const char  *parameter = nullptr;
1855 
1856   fprintf(fp,"InsEncode: ");
1857   _encoding.reset();
1858 
1859   while ( (encoding = (NameAndList*)_encoding.iter()) != 0 ) {
1860     // Output the encoding being used
1861     fprintf(fp,"%s(", encoding->name() );
1862 
1863     // Output its parameter list, if any
1864     bool first_param = true;
1865     encoding->reset();
1866     while (  (parameter = encoding->iter()) != 0 ) {
1867       // Output the ',' between parameters
1868       if ( ! first_param )  fprintf(fp,", ");
1869       first_param = false;
1870       // Output the parameter
1871       fprintf(fp,"%s", parameter);
1872     } // done with parameters
1873     fprintf(fp,")  ");
1874   } // done with encodings
1875 
1876   fprintf(fp,"\n");
1877 }
1878 
1879 void InsEncode::forms_do(FormClosure *f) {
1880   _encoding.reset();
1881   NameAndList *encoding = (NameAndList*)_encoding.iter();
1882   for( ; encoding != nullptr; encoding = (NameAndList*)_encoding.iter() ) {
1883     // just check name, other operands will be checked as instruction parameters
1884     f->do_form_by_name(encoding->name());
1885   }
1886 }
1887 
1888 //------------------------------Effect-----------------------------------------
1889 static int effect_lookup(const char *name) {
1890   if (!strcmp(name, "USE")) return Component::USE;
1891   if (!strcmp(name, "DEF")) return Component::DEF;
1892   if (!strcmp(name, "USE_DEF")) return Component::USE_DEF;
1893   if (!strcmp(name, "KILL")) return Component::KILL;
1894   if (!strcmp(name, "USE_KILL")) return Component::USE_KILL;
1895   if (!strcmp(name, "TEMP")) return Component::TEMP;
1896   if (!strcmp(name, "TEMP_DEF")) return Component::TEMP_DEF;
1897   if (!strcmp(name, "INVALID")) return Component::INVALID;
1898   if (!strcmp(name, "CALL")) return Component::CALL;
1899   assert(false,"Invalid effect name specified\n");
1900   return Component::INVALID;
1901 }
1902 
1903 const char *Component::getUsedefName() {
1904   switch (_usedef) {
1905     case Component::INVALID:  return "INVALID";  break;
1906     case Component::USE:      return "USE";      break;
1907     case Component::USE_DEF:  return "USE_DEF";  break;
1908     case Component::USE_KILL: return "USE_KILL"; break;
1909     case Component::KILL:     return "KILL";     break;
1910     case Component::TEMP:     return "TEMP";     break;
1911     case Component::TEMP_DEF: return "TEMP_DEF"; break;
1912     case Component::DEF:      return "DEF";      break;
1913     case Component::CALL:     return "CALL";     break;
1914     default: assert(false, "unknown effect");
1915   }
1916   return "Undefined Use/Def info";
1917 }
1918 
1919 Effect::Effect(const char *name) : _name(name), _use_def(effect_lookup(name)) {
1920   _ftype = Form::EFF;
1921 }
1922 
1923 Effect::~Effect() {
1924 }
1925 
1926 // Dynamic type check
1927 Effect *Effect::is_effect() const {
1928   return (Effect*)this;
1929 }
1930 
1931 
1932 // True if this component is equal to the parameter.
1933 bool Effect::is(int use_def_kill_enum) const {
1934   return (_use_def == use_def_kill_enum ? true : false);
1935 }
1936 // True if this component is used/def'd/kill'd as the parameter suggests.
1937 bool Effect::isa(int use_def_kill_enum) const {
1938   return (_use_def & use_def_kill_enum) == use_def_kill_enum;
1939 }
1940 
1941 void Effect::dump() {
1942   output(stderr);
1943 }
1944 
1945 void Effect::output(FILE *fp) {          // Write info to output files
1946   fprintf(fp,"Effect: %s\n", (_name?_name:""));
1947 }
1948 
1949 //---------------------------------Flag----------------------------------------
1950 Flag::Flag(const char *name) : _name(name), _next(nullptr) {
1951   _ftype = Form::FLG;
1952 }
1953 
1954 Flag::~Flag() {
1955 }
1956 
1957 void Flag::append_flag(Flag *next_flag) {
1958   if( _next == nullptr ) {
1959     _next = next_flag;
1960   } else {
1961     _next->append_flag( next_flag );
1962   }
1963 }
1964 
1965 Flag* Flag::next() {
1966   return _next;
1967 }
1968 
1969 void Flag::dump() {
1970   output(stderr);
1971 }
1972 
1973 void Flag::output(FILE *fp) {          // Write info to output files
1974   fprintf(fp,"Flag: %s\n", (_name?_name:""));
1975 }
1976 
1977 //------------------------------ExpandRule-------------------------------------
1978 ExpandRule::ExpandRule() : _expand_instrs(),
1979                            _newopconst(cmpstr, hashstr, Form::arena) {
1980   _ftype = Form::EXP;
1981 }
1982 
1983 ExpandRule::~ExpandRule() {                  // Destructor
1984 }
1985 
1986 void ExpandRule::add_instruction(NameAndList *instruction_name_and_operand_list) {
1987   _expand_instrs.addName((char*)instruction_name_and_operand_list);
1988 }
1989 
1990 void ExpandRule::reset_instructions() {
1991   _expand_instrs.reset();
1992 }
1993 
1994 NameAndList* ExpandRule::iter_instructions() {
1995   return (NameAndList*)_expand_instrs.iter();
1996 }
1997 
1998 
1999 void ExpandRule::dump() {
2000   output(stderr);
2001 }
2002 
2003 void ExpandRule::output(FILE *fp) {         // Write info to output files
2004   NameAndList *expand_instr = nullptr;
2005   const char *opid = nullptr;
2006 
2007   fprintf(fp,"\nExpand Rule:\n");
2008 
2009   // Iterate over the instructions 'node' expands into
2010   for(reset_instructions(); (expand_instr = iter_instructions()) != nullptr; ) {
2011     fprintf(fp,"%s(", expand_instr->name());
2012 
2013     // iterate over the operand list
2014     for( expand_instr->reset(); (opid = expand_instr->iter()) != nullptr; ) {
2015       fprintf(fp,"%s ", opid);
2016     }
2017     fprintf(fp,");\n");
2018   }
2019 }
2020 
2021 void ExpandRule::forms_do(FormClosure *f) {
2022   NameAndList *expand_instr = nullptr;
2023   // Iterate over the instructions 'node' expands into
2024   for(reset_instructions(); (expand_instr = iter_instructions()) != nullptr; ) {
2025     f->do_form_by_name(expand_instr->name());
2026   }
2027   _newopers.reset();
2028   const char* oper = _newopers.iter();
2029   for(; oper != nullptr; oper = _newopers.iter()) {
2030     f->do_form_by_name(oper);
2031   }
2032 }
2033 
2034 //------------------------------RewriteRule------------------------------------
2035 RewriteRule::RewriteRule(char* params, char* block)
2036   : _tempParams(params), _tempBlock(block) { };  // Constructor
2037 RewriteRule::~RewriteRule() {                 // Destructor
2038 }
2039 
2040 void RewriteRule::dump() {
2041   output(stderr);
2042 }
2043 
2044 void RewriteRule::output(FILE *fp) {         // Write info to output files
2045   fprintf(fp,"\nRewrite Rule:\n%s\n%s\n",
2046           (_tempParams?_tempParams:""),
2047           (_tempBlock?_tempBlock:""));
2048 }
2049 
2050 void RewriteRule::forms_do(FormClosure *f) {
2051   if (_condition) f->do_form(_condition);
2052   if (_instrs) f->do_form(_instrs);
2053   if (_opers) f->do_form(_opers);
2054 }
2055 
2056 
2057 //==============================MachNodes======================================
2058 //------------------------------MachNodeForm-----------------------------------
2059 MachNodeForm::MachNodeForm(char *id)
2060   : _ident(id) {
2061 }
2062 
2063 MachNodeForm::~MachNodeForm() {
2064 }
2065 
2066 MachNodeForm *MachNodeForm::is_machnode() const {
2067   return (MachNodeForm*)this;
2068 }
2069 
2070 //==============================Operand Classes================================
2071 //------------------------------OpClassForm------------------------------------
2072 OpClassForm::OpClassForm(const char* id) : _ident(id) {
2073   _ftype = Form::OPCLASS;
2074 }
2075 
2076 OpClassForm::~OpClassForm() {
2077 }
2078 
2079 bool OpClassForm::ideal_only() const { return 0; }
2080 
2081 OpClassForm *OpClassForm::is_opclass() const {
2082   return (OpClassForm*)this;
2083 }
2084 
2085 Form::InterfaceType OpClassForm::interface_type(FormDict &globals) const {
2086   if( _oplst.count() == 0 ) return Form::no_interface;
2087 
2088   // Check that my operands have the same interface type
2089   Form::InterfaceType  interface;
2090   bool  first = true;
2091   NameList &op_list = (NameList &)_oplst;
2092   op_list.reset();
2093   const char *op_name;
2094   while( (op_name = op_list.iter()) != nullptr ) {
2095     const Form  *form    = globals[op_name];
2096     OperandForm *operand = form->is_operand();
2097     assert( operand, "Entry in operand class that is not an operand");
2098     if( first ) {
2099       first     = false;
2100       interface = operand->interface_type(globals);
2101     } else {
2102       interface = (interface == operand->interface_type(globals) ? interface : Form::no_interface);
2103     }
2104   }
2105   return interface;
2106 }
2107 
2108 bool OpClassForm::stack_slots_only(FormDict &globals) const {
2109   if( _oplst.count() == 0 ) return false;  // how?
2110 
2111   NameList &op_list = (NameList &)_oplst;
2112   op_list.reset();
2113   const char *op_name;
2114   while( (op_name = op_list.iter()) != nullptr ) {
2115     const Form  *form    = globals[op_name];
2116     OperandForm *operand = form->is_operand();
2117     assert( operand, "Entry in operand class that is not an operand");
2118     if( !operand->stack_slots_only(globals) )  return false;
2119   }
2120   return true;
2121 }
2122 
2123 
2124 void OpClassForm::dump() {
2125   output(stderr);
2126 }
2127 
2128 void OpClassForm::output(FILE *fp) {
2129   const char *name;
2130   fprintf(fp,"\nOperand Class: %s\n", (_ident?_ident:""));
2131   fprintf(fp,"\nCount = %d\n", _oplst.count());
2132   for(_oplst.reset(); (name = _oplst.iter()) != nullptr;) {
2133     fprintf(fp,"%s, ",name);
2134   }
2135   fprintf(fp,"\n");
2136 }
2137 
2138 void OpClassForm::forms_do(FormClosure* f) {
2139   const char *name;
2140   for(_oplst.reset(); (name = _oplst.iter()) != nullptr;) {
2141     f->do_form_by_name(name);
2142   }
2143 }
2144 
2145 
2146 //==============================Operands=======================================
2147 //------------------------------OperandForm------------------------------------
2148 OperandForm::OperandForm(const char* id)
2149   : OpClassForm(id), _ideal_only(false),
2150     _localNames(cmpstr, hashstr, Form::arena) {
2151       _ftype = Form::OPER;
2152 
2153       _matrule   = nullptr;
2154       _interface = nullptr;
2155       _attribs   = nullptr;
2156       _predicate = nullptr;
2157       _constraint= nullptr;
2158       _construct = nullptr;
2159       _format    = nullptr;
2160 }
2161 OperandForm::OperandForm(const char* id, bool ideal_only)
2162   : OpClassForm(id), _ideal_only(ideal_only),
2163     _localNames(cmpstr, hashstr, Form::arena) {
2164       _ftype = Form::OPER;
2165 
2166       _matrule   = nullptr;
2167       _interface = nullptr;
2168       _attribs   = nullptr;
2169       _predicate = nullptr;
2170       _constraint= nullptr;
2171       _construct = nullptr;
2172       _format    = nullptr;
2173 }
2174 OperandForm::~OperandForm() {
2175 }
2176 
2177 
2178 OperandForm *OperandForm::is_operand() const {
2179   return (OperandForm*)this;
2180 }
2181 
2182 bool OperandForm::ideal_only() const {
2183   return _ideal_only;
2184 }
2185 
2186 Form::InterfaceType OperandForm::interface_type(FormDict &globals) const {
2187   if( _interface == nullptr )  return Form::no_interface;
2188 
2189   return _interface->interface_type(globals);
2190 }
2191 
2192 
2193 bool OperandForm::stack_slots_only(FormDict &globals) const {
2194   if( _constraint == nullptr )  return false;
2195   return _constraint->stack_slots_only();
2196 }
2197 
2198 
2199 // Access op_cost attribute or return null.
2200 const char* OperandForm::cost() {
2201   for (Attribute* cur = _attribs; cur != nullptr; cur = (Attribute*)cur->_next) {
2202     if( strcmp(cur->_ident,AttributeForm::_op_cost) == 0 ) {
2203       return cur->_val;
2204     }
2205   }
2206   return nullptr;
2207 }
2208 
2209 // Return the number of leaves below this complex operand
2210 uint OperandForm::num_leaves() const {
2211   if ( ! _matrule) return 0;
2212 
2213   int num_leaves = _matrule->_numleaves;
2214   return num_leaves;
2215 }
2216 
2217 // Return the number of constants contained within this complex operand
2218 uint OperandForm::num_consts(FormDict &globals) const {
2219   if ( ! _matrule) return 0;
2220 
2221   // This is a recursive invocation on all operands in the matchrule
2222   return _matrule->num_consts(globals);
2223 }
2224 
2225 // Return the number of constants in match rule with specified type
2226 uint OperandForm::num_consts(FormDict &globals, Form::DataType type) const {
2227   if ( ! _matrule) return 0;
2228 
2229   // This is a recursive invocation on all operands in the matchrule
2230   return _matrule->num_consts(globals, type);
2231 }
2232 
2233 // Return the number of pointer constants contained within this complex operand
2234 uint OperandForm::num_const_ptrs(FormDict &globals) const {
2235   if ( ! _matrule) return 0;
2236 
2237   // This is a recursive invocation on all operands in the matchrule
2238   return _matrule->num_const_ptrs(globals);
2239 }
2240 
2241 uint OperandForm::num_edges(FormDict &globals) const {
2242   uint edges  = 0;
2243   uint leaves = num_leaves();
2244   uint consts = num_consts(globals);
2245 
2246   // If we are matching a constant directly, there are no leaves.
2247   edges = ( leaves > consts ) ? leaves - consts : 0;
2248 
2249   // !!!!!
2250   // Special case operands that do not have a corresponding ideal node.
2251   if( (edges == 0) && (consts == 0) ) {
2252     if( constrained_reg_class() != nullptr ) {
2253       edges = 1;
2254     } else {
2255       if( _matrule
2256           && (_matrule->_lChild == nullptr) && (_matrule->_rChild == nullptr) ) {
2257         const Form *form = globals[_matrule->_opType];
2258         OperandForm *oper = form ? form->is_operand() : nullptr;
2259         if( oper ) {
2260           return oper->num_edges(globals);
2261         }
2262       }
2263     }
2264   }
2265 
2266   return edges;
2267 }
2268 
2269 
2270 // Check if this operand is usable for cisc-spilling
2271 bool  OperandForm::is_cisc_reg(FormDict &globals) const {
2272   const char *ideal = ideal_type(globals);
2273   bool is_cisc_reg = (ideal && (ideal_to_Reg_type(ideal) != none));
2274   return is_cisc_reg;
2275 }
2276 
2277 bool  OpClassForm::is_cisc_mem(FormDict &globals) const {
2278   Form::InterfaceType my_interface = interface_type(globals);
2279   return (my_interface == memory_interface);
2280 }
2281 
2282 
2283 // node matches ideal 'Bool'
2284 bool OperandForm::is_ideal_bool() const {
2285   if( _matrule == nullptr ) return false;
2286 
2287   return _matrule->is_ideal_bool();
2288 }
2289 
2290 // Require user's name for an sRegX to be stackSlotX
2291 Form::DataType OperandForm::is_user_name_for_sReg() const {
2292   DataType data_type = none;
2293   if( _ident != nullptr ) {
2294     if(      strcmp(_ident,"stackSlotI") == 0 ) data_type = Form::idealI;
2295     else if( strcmp(_ident,"stackSlotP") == 0 ) data_type = Form::idealP;
2296     else if( strcmp(_ident,"stackSlotD") == 0 ) data_type = Form::idealD;
2297     else if( strcmp(_ident,"stackSlotF") == 0 ) data_type = Form::idealF;
2298     else if( strcmp(_ident,"stackSlotL") == 0 ) data_type = Form::idealL;
2299   }
2300   assert((data_type == none) || (_matrule == nullptr), "No match-rule for stackSlotX");
2301 
2302   return data_type;
2303 }
2304 
2305 
2306 // Return ideal type, if there is a single ideal type for this operand
2307 const char *OperandForm::ideal_type(FormDict &globals, RegisterForm *registers) const {
2308   const char *type = nullptr;
2309   if (ideal_only()) type = _ident;
2310   else if( _matrule == nullptr ) {
2311     // Check for condition code register
2312     const char *rc_name = constrained_reg_class();
2313     // !!!!!
2314     if (rc_name == nullptr) return nullptr;
2315     // !!!!! !!!!!
2316     // Check constraints on result's register class
2317     if( registers ) {
2318       RegClass *reg_class  = registers->getRegClass(rc_name);
2319       assert( reg_class != nullptr, "Register class is not defined");
2320 
2321       // Check for ideal type of entries in register class, all are the same type
2322       reg_class->reset();
2323       RegDef *reg_def = reg_class->RegDef_iter();
2324       assert( reg_def != nullptr, "No entries in register class");
2325       assert( reg_def->_idealtype != nullptr, "Did not define ideal type for register");
2326       // Return substring that names the register's ideal type
2327       type = reg_def->_idealtype + 3;
2328       assert( *(reg_def->_idealtype + 0) == 'O', "Expect Op_ prefix");
2329       assert( *(reg_def->_idealtype + 1) == 'p', "Expect Op_ prefix");
2330       assert( *(reg_def->_idealtype + 2) == '_', "Expect Op_ prefix");
2331     }
2332   }
2333   else if( _matrule->_lChild == nullptr && _matrule->_rChild == nullptr ) {
2334     // This operand matches a single type, at the top level.
2335     // Check for ideal type
2336     type = _matrule->_opType;
2337     if( strcmp(type,"Bool") == 0 )
2338       return "Bool";
2339     // transitive lookup
2340     const Form *frm = globals[type];
2341     OperandForm *op = frm->is_operand();
2342     type = op->ideal_type(globals, registers);
2343   }
2344   return type;
2345 }
2346 
2347 
2348 // If there is a single ideal type for this interface field, return it.
2349 const char *OperandForm::interface_ideal_type(FormDict &globals,
2350                                               const char *field) const {
2351   const char  *ideal_type = nullptr;
2352   const char  *value      = nullptr;
2353 
2354   // Check if "field" is valid for this operand's interface
2355   if ( ! is_interface_field(field, value) )   return ideal_type;
2356 
2357   // !!!!! !!!!! !!!!!
2358   // If a valid field has a constant value, identify "ConI" or "ConP" or ...
2359 
2360   // Else, lookup type of field's replacement variable
2361 
2362   return ideal_type;
2363 }
2364 
2365 
2366 RegClass* OperandForm::get_RegClass() const {
2367   if (_interface && !_interface->is_RegInterface()) return nullptr;
2368   return globalAD->get_registers()->getRegClass(constrained_reg_class());
2369 }
2370 
2371 
2372 bool OperandForm::is_bound_register() const {
2373   RegClass* reg_class = get_RegClass();
2374   if (reg_class == nullptr) {
2375     return false;
2376   }
2377 
2378   const char* name = ideal_type(globalAD->globalNames());
2379   if (name == nullptr) {
2380     return false;
2381   }
2382 
2383   uint size = 0;
2384   if (strcmp(name, "RegFlags") == 0) size = 1;
2385   if (strcmp(name, "RegI") == 0) size = 1;
2386   if (strcmp(name, "RegF") == 0) size = 1;
2387   if (strcmp(name, "RegD") == 0) size = 2;
2388   if (strcmp(name, "RegL") == 0) size = 2;
2389   if (strcmp(name, "RegN") == 0) size = 1;
2390   if (strcmp(name, "RegVectMask") == 0) size = globalAD->get_preproc_def("AARCH64") ? 1 : 2;
2391   if (strcmp(name, "VecX") == 0) size = 4;
2392   if (strcmp(name, "VecY") == 0) size = 8;
2393   if (strcmp(name, "VecZ") == 0) size = 16;
2394   if (strcmp(name, "RegP") == 0) size = globalAD->get_preproc_def("_LP64") ? 2 : 1;
2395   if (size == 0) {
2396     return false;
2397   }
2398   return size == reg_class->size();
2399 }
2400 
2401 
2402 // Check if this is a valid field for this operand,
2403 // Return 'true' if valid, and set the value to the string the user provided.
2404 bool  OperandForm::is_interface_field(const char *field,
2405                                       const char * &value) const {
2406   return false;
2407 }
2408 
2409 
2410 // Return register class name if a constraint specifies the register class.
2411 const char *OperandForm::constrained_reg_class() const {
2412   const char *reg_class  = nullptr;
2413   if ( _constraint ) {
2414     // !!!!!
2415     Constraint *constraint = _constraint;
2416     if ( strcmp(_constraint->_func,"ALLOC_IN_RC") == 0 ) {
2417       reg_class = _constraint->_arg;
2418     }
2419   }
2420 
2421   return reg_class;
2422 }
2423 
2424 
2425 // Return the register class associated with 'leaf'.
2426 const char *OperandForm::in_reg_class(uint leaf, FormDict &globals) {
2427   const char *reg_class = nullptr; // "RegMask::Empty";
2428 
2429   if((_matrule == nullptr) || (_matrule->is_chain_rule(globals))) {
2430     reg_class = constrained_reg_class();
2431     return reg_class;
2432   }
2433   const char *result   = nullptr;
2434   const char *name     = nullptr;
2435   const char *type     = nullptr;
2436   // iterate through all base operands
2437   // until we reach the register that corresponds to "leaf"
2438   // This function is not looking for an ideal type.  It needs the first
2439   // level user type associated with the leaf.
2440   for(uint idx = 0;_matrule->base_operand(idx,globals,result,name,type);++idx) {
2441     const Form *form = (_localNames[name] ? _localNames[name] : globals[result]);
2442     OperandForm *oper = form ? form->is_operand() : nullptr;
2443     if( oper ) {
2444       reg_class = oper->constrained_reg_class();
2445       if( reg_class ) {
2446         reg_class = reg_class;
2447       } else {
2448         // ShouldNotReachHere();
2449       }
2450     } else {
2451       // ShouldNotReachHere();
2452     }
2453 
2454     // Increment our target leaf position if current leaf is not a candidate.
2455     if( reg_class == nullptr)    ++leaf;
2456     // Exit the loop with the value of reg_class when at the correct index
2457     if( idx == leaf )         break;
2458     // May iterate through all base operands if reg_class for 'leaf' is null
2459   }
2460   return reg_class;
2461 }
2462 
2463 
2464 // Recursive call to construct list of top-level operands.
2465 // Implementation does not modify state of internal structures
2466 void OperandForm::build_components() {
2467   if (_matrule)  _matrule->append_components(_localNames, _components);
2468 
2469   // Add parameters that "do not appear in match rule".
2470   const char *name;
2471   for (_parameters.reset(); (name = _parameters.iter()) != nullptr;) {
2472     OpClassForm *opForm = _localNames[name]->is_opclass();
2473     assert(opForm != nullptr, "sanity");
2474 
2475     if ( _components.operand_position(name) == -1 ) {
2476       _components.insert(name, opForm->_ident, Component::INVALID, false);
2477     }
2478   }
2479 
2480   return;
2481 }
2482 
2483 int OperandForm::operand_position(const char *name, int usedef) {
2484   return _components.operand_position(name, usedef, this);
2485 }
2486 
2487 
2488 // Return zero-based position in component list, only counting constants;
2489 // Return -1 if not in list.
2490 int OperandForm::constant_position(FormDict &globals, const Component *last) {
2491   // Iterate through components and count constants preceding 'constant'
2492   int position = 0;
2493   Component *comp;
2494   _components.reset();
2495   while( (comp = _components.iter()) != nullptr  && (comp != last) ) {
2496     // Special case for operands that take a single user-defined operand
2497     // Skip the initial definition in the component list.
2498     if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2499 
2500     const char *type = comp->_type;
2501     // Lookup operand form for replacement variable's type
2502     const Form *form = globals[type];
2503     assert( form != nullptr, "Component's type not found");
2504     OperandForm *oper = form ? form->is_operand() : nullptr;
2505     if( oper ) {
2506       if( oper->_matrule->is_base_constant(globals) != Form::none ) {
2507         ++position;
2508       }
2509     }
2510   }
2511 
2512   // Check for being passed a component that was not in the list
2513   if( comp != last )  position = -1;
2514 
2515   return position;
2516 }
2517 // Provide position of constant by "name"
2518 int OperandForm::constant_position(FormDict &globals, const char *name) {
2519   const Component *comp = _components.search(name);
2520   int idx = constant_position( globals, comp );
2521 
2522   return idx;
2523 }
2524 
2525 
2526 // Return zero-based position in component list, only counting constants;
2527 // Return -1 if not in list.
2528 int OperandForm::register_position(FormDict &globals, const char *reg_name) {
2529   // Iterate through components and count registers preceding 'last'
2530   uint  position = 0;
2531   Component *comp;
2532   _components.reset();
2533   while( (comp = _components.iter()) != nullptr
2534          && (strcmp(comp->_name,reg_name) != 0) ) {
2535     // Special case for operands that take a single user-defined operand
2536     // Skip the initial definition in the component list.
2537     if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2538 
2539     const char *type = comp->_type;
2540     // Lookup operand form for component's type
2541     const Form *form = globals[type];
2542     assert( form != nullptr, "Component's type not found");
2543     OperandForm *oper = form ? form->is_operand() : nullptr;
2544     if( oper ) {
2545       if( oper->_matrule->is_base_register(globals) ) {
2546         ++position;
2547       }
2548     }
2549   }
2550 
2551   return position;
2552 }
2553 
2554 
2555 const char *OperandForm::reduce_result()  const {
2556   return _ident;
2557 }
2558 // Return the name of the operand on the right hand side of the binary match
2559 // Return null if there is no right hand side
2560 const char *OperandForm::reduce_right(FormDict &globals)  const {
2561   return  ( _matrule ? _matrule->reduce_right(globals) : nullptr );
2562 }
2563 
2564 // Similar for left
2565 const char *OperandForm::reduce_left(FormDict &globals)   const {
2566   return  ( _matrule ? _matrule->reduce_left(globals) : nullptr );
2567 }
2568 
2569 
2570 // --------------------------- FILE *output_routines
2571 //
2572 // Output code for disp_is_oop, if true.
2573 void OperandForm::disp_is_oop(FILE *fp, FormDict &globals) {
2574   //  Check it is a memory interface with a non-user-constant disp field
2575   if ( this->_interface == nullptr ) return;
2576   MemInterface *mem_interface = this->_interface->is_MemInterface();
2577   if ( mem_interface == nullptr )    return;
2578   const char   *disp  = mem_interface->_disp;
2579   if ( *disp != '$' )             return;
2580 
2581   // Lookup replacement variable in operand's component list
2582   const char   *rep_var = disp + 1;
2583   const Component *comp = this->_components.search(rep_var);
2584   assert( comp != nullptr, "Replacement variable not found in components");
2585   // Lookup operand form for replacement variable's type
2586   const char      *type = comp->_type;
2587   Form            *form = (Form*)globals[type];
2588   assert( form != nullptr, "Replacement variable's type not found");
2589   OperandForm     *op   = form->is_operand();
2590   assert( op, "Memory Interface 'disp' can only emit an operand form");
2591   // Check if this is a ConP, which may require relocation
2592   if ( op->is_base_constant(globals) == Form::idealP ) {
2593     // Find the constant's index:  _c0, _c1, _c2, ... , _cN
2594     uint idx  = op->constant_position( globals, rep_var);
2595     fprintf(fp,"  virtual relocInfo::relocType disp_reloc() const {");
2596     fprintf(fp,  "  return _c%d->reloc();", idx);
2597     fprintf(fp, " }\n");
2598   }
2599 }
2600 
2601 // Generate code for internal and external format methods
2602 //
2603 // internal access to reg# node->_idx
2604 // access to subsumed constant _c0, _c1,
2605 void  OperandForm::int_format(FILE *fp, FormDict &globals, uint index) {
2606   Form::DataType dtype;
2607   if (_matrule && (_matrule->is_base_register(globals) ||
2608                    strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2609     // !!!!! !!!!!
2610     fprintf(fp,"  { char reg_str[128];\n");
2611     fprintf(fp,"    ra->dump_register(node,reg_str, sizeof(reg_str));\n");
2612     fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2613     fprintf(fp,"  }\n");
2614   } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2615     format_constant( fp, index, dtype );
2616   } else if (ideal_to_sReg_type(_ident) != Form::none) {
2617     // Special format for Stack Slot Register
2618     fprintf(fp,"  { char reg_str[128];\n");
2619     fprintf(fp,"    ra->dump_register(node,reg_str, sizeof(reg_str));\n");
2620     fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2621     fprintf(fp,"  }\n");
2622   } else {
2623     fprintf(fp,"  st->print(\"No format defined for %s\n\");\n", _ident);
2624     fflush(fp);
2625     fprintf(stderr,"No format defined for %s\n", _ident);
2626     dump();
2627     assert( false,"Internal error:\n  output_internal_operand() attempting to output other than a Register or Constant");
2628   }
2629 }
2630 
2631 // Similar to "int_format" but for cases where data is external to operand
2632 // external access to reg# node->in(idx)->_idx,
2633 void  OperandForm::ext_format(FILE *fp, FormDict &globals, uint index) {
2634   Form::DataType dtype;
2635   if (_matrule && (_matrule->is_base_register(globals) ||
2636                    strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2637     fprintf(fp,"  { char reg_str[128];\n");
2638     fprintf(fp,"    ra->dump_register(node->in(idx");
2639     if ( index != 0 ) fprintf(fp,              "+%d",index);
2640     fprintf(fp,                                      "),reg_str,sizeof(reg_str));\n");
2641     fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2642     fprintf(fp,"  }\n");
2643   } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2644     format_constant( fp, index, dtype );
2645   } else if (ideal_to_sReg_type(_ident) != Form::none) {
2646     // Special format for Stack Slot Register
2647     fprintf(fp,"  { char reg_str[128];\n");
2648     fprintf(fp,"    ra->dump_register(node->in(idx");
2649     if ( index != 0 ) fprintf(fp,                  "+%d",index);
2650     fprintf(fp,                                       "),reg_str,sizeof(reg_str));\n");
2651     fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2652     fprintf(fp,"  }\n");
2653   } else {
2654     fprintf(fp,"  st->print(\"No format defined for %s\n\");\n", _ident);
2655     assert( false,"Internal error:\n  output_external_operand() attempting to output other than a Register or Constant");
2656   }
2657 }
2658 
2659 void OperandForm::format_constant(FILE *fp, uint const_index, uint const_type) {
2660   switch(const_type) {
2661   case Form::idealI: fprintf(fp,"  st->print(\"#%%d\", _c%d);\n", const_index); break;
2662   case Form::idealP: fprintf(fp,"  if (_c%d) _c%d->dump_on(st);\n", const_index, const_index); break;
2663   case Form::idealNKlass:
2664   case Form::idealN: fprintf(fp,"  if (_c%d) _c%d->dump_on(st);\n", const_index, const_index); break;
2665   case Form::idealL: fprintf(fp,"  st->print(\"#\" INT64_FORMAT, (int64_t)_c%d);\n", const_index); break;
2666   case Form::idealF: fprintf(fp,"  st->print(\"#%%f\", _c%d);\n", const_index); break;
2667   case Form::idealD: fprintf(fp,"  st->print(\"#%%f\", _c%d);\n", const_index); break;
2668   default:
2669     assert( false, "ShouldNotReachHere()");
2670   }
2671 }
2672 
2673 // Return the operand form corresponding to the given index, else null.
2674 OperandForm *OperandForm::constant_operand(FormDict &globals,
2675                                            uint      index) {
2676   // !!!!!
2677   // Check behavior on complex operands
2678   uint n_consts = num_consts(globals);
2679   if( n_consts > 0 ) {
2680     uint i = 0;
2681     const char *type;
2682     Component  *comp;
2683     _components.reset();
2684     if ((comp = _components.iter()) == nullptr) {
2685       assert(n_consts == 1, "Bad component list detected.\n");
2686       // Current operand is THE operand
2687       if ( index == 0 ) {
2688         return this;
2689       }
2690     } // end if null
2691     else {
2692       // Skip the first component, it can not be a DEF of a constant
2693       do {
2694         type = comp->base_type(globals);
2695         // Check that "type" is a 'ConI', 'ConP', ...
2696         if ( ideal_to_const_type(type) != Form::none ) {
2697           // When at correct component, get corresponding Operand
2698           if ( index == 0 ) {
2699             return globals[comp->_type]->is_operand();
2700           }
2701           // Decrement number of constants to go
2702           --index;
2703         }
2704       } while((comp = _components.iter()) != nullptr);
2705     }
2706   }
2707 
2708   // Did not find a constant for this index.
2709   return nullptr;
2710 }
2711 
2712 // If this operand has a single ideal type, return its type
2713 Form::DataType OperandForm::simple_type(FormDict &globals) const {
2714   const char *type_name = ideal_type(globals);
2715   Form::DataType type   = type_name ? ideal_to_const_type( type_name )
2716                                     : Form::none;
2717   return type;
2718 }
2719 
2720 Form::DataType OperandForm::is_base_constant(FormDict &globals) const {
2721   if ( _matrule == nullptr )    return Form::none;
2722 
2723   return _matrule->is_base_constant(globals);
2724 }
2725 
2726 // "true" if this operand is a simple type that is swallowed
2727 bool  OperandForm::swallowed(FormDict &globals) const {
2728   Form::DataType type   = simple_type(globals);
2729   if( type != Form::none ) {
2730     return true;
2731   }
2732 
2733   return false;
2734 }
2735 
2736 // Output code to access the value of the index'th constant
2737 void OperandForm::access_constant(FILE *fp, FormDict &globals,
2738                                   uint const_index) {
2739   OperandForm *oper = constant_operand(globals, const_index);
2740   assert( oper, "Index exceeds number of constants in operand");
2741   Form::DataType dtype = oper->is_base_constant(globals);
2742 
2743   switch(dtype) {
2744   case idealI: fprintf(fp,"_c%d",           const_index); break;
2745   case idealP: fprintf(fp,"_c%d->get_con()",const_index); break;
2746   case idealL: fprintf(fp,"_c%d",           const_index); break;
2747   case idealF: fprintf(fp,"_c%d",           const_index); break;
2748   case idealD: fprintf(fp,"_c%d",           const_index); break;
2749   default:
2750     assert( false, "ShouldNotReachHere()");
2751   }
2752 }
2753 
2754 
2755 void OperandForm::dump() {
2756   output(stderr);
2757 }
2758 
2759 void OperandForm::output(FILE *fp) {
2760   fprintf(fp,"\nOperand: %s\n", (_ident?_ident:""));
2761   if (_matrule)    _matrule->dump();
2762   if (_interface)  _interface->dump();
2763   if (_attribs)    _attribs->dump();
2764   if (_predicate)  _predicate->dump();
2765   if (_constraint) _constraint->dump();
2766   if (_construct)  _construct->dump();
2767   if (_format)     _format->dump();
2768 }
2769 
2770 void OperandForm::forms_do(FormClosure* f) {
2771   if (_matrule)    f->do_form(_matrule);
2772   if (_interface)  f->do_form(_interface);
2773   if (_attribs)    f->do_form(_attribs);
2774   if (_predicate)  f->do_form(_predicate);
2775   if (_constraint) f->do_form(_constraint);
2776   if (_construct)  f->do_form(_construct);
2777   if (_format)     f->do_form(_format);
2778   _localNames.forms_do(f);
2779   const char* opclass = nullptr;
2780   for ( _classes.reset(); (opclass = _classes.iter()) != nullptr; ) {
2781     f->do_form_by_name(opclass);
2782   }
2783   assert(_components.count() == 0, "skip _compnets");
2784 }
2785 
2786 //------------------------------Constraint-------------------------------------
2787 Constraint::Constraint(const char *func, const char *arg)
2788   : _func(func), _arg(arg) {
2789 }
2790 Constraint::~Constraint() { /* not owner of char* */
2791 }
2792 
2793 bool Constraint::stack_slots_only() const {
2794   return strcmp(_func, "ALLOC_IN_RC") == 0
2795       && strcmp(_arg,  "stack_slots") == 0;
2796 }
2797 
2798 void Constraint::dump() {
2799   output(stderr);
2800 }
2801 
2802 void Constraint::output(FILE *fp) {           // Write info to output files
2803   assert((_func != nullptr && _arg != nullptr),"missing constraint function or arg");
2804   fprintf(fp,"Constraint: %s ( %s )\n", _func, _arg);
2805 }
2806 
2807 void Constraint::forms_do(FormClosure *f) {
2808   f->do_form_by_name(_arg);
2809 }
2810 
2811 //------------------------------Predicate--------------------------------------
2812 Predicate::Predicate(char *pr)
2813   : _pred(pr) {
2814 }
2815 Predicate::~Predicate() {
2816 }
2817 
2818 void Predicate::dump() {
2819   output(stderr);
2820 }
2821 
2822 void Predicate::output(FILE *fp) {
2823   fprintf(fp,"Predicate");  // Write to output files
2824 }
2825 //------------------------------Interface--------------------------------------
2826 Interface::Interface(const char *name) : _name(name) {
2827 }
2828 Interface::~Interface() {
2829 }
2830 
2831 Form::InterfaceType Interface::interface_type(FormDict &globals) const {
2832   Interface *thsi = (Interface*)this;
2833   if ( thsi->is_RegInterface()   ) return Form::register_interface;
2834   if ( thsi->is_MemInterface()   ) return Form::memory_interface;
2835   if ( thsi->is_ConstInterface() ) return Form::constant_interface;
2836   if ( thsi->is_CondInterface()  ) return Form::conditional_interface;
2837 
2838   return Form::no_interface;
2839 }
2840 
2841 RegInterface   *Interface::is_RegInterface() {
2842   if ( strcmp(_name,"REG_INTER") != 0 )
2843     return nullptr;
2844   return (RegInterface*)this;
2845 }
2846 MemInterface   *Interface::is_MemInterface() {
2847   if ( strcmp(_name,"MEMORY_INTER") != 0 )  return nullptr;
2848   return (MemInterface*)this;
2849 }
2850 ConstInterface *Interface::is_ConstInterface() {
2851   if ( strcmp(_name,"CONST_INTER") != 0 )  return nullptr;
2852   return (ConstInterface*)this;
2853 }
2854 CondInterface  *Interface::is_CondInterface() {
2855   if ( strcmp(_name,"COND_INTER") != 0 )  return nullptr;
2856   return (CondInterface*)this;
2857 }
2858 
2859 
2860 void Interface::dump() {
2861   output(stderr);
2862 }
2863 
2864 // Write info to output files
2865 void Interface::output(FILE *fp) {
2866   fprintf(fp,"Interface: %s\n", (_name ? _name : "") );
2867 }
2868 
2869 //------------------------------RegInterface-----------------------------------
2870 RegInterface::RegInterface() : Interface("REG_INTER") {
2871 }
2872 RegInterface::~RegInterface() {
2873 }
2874 
2875 void RegInterface::dump() {
2876   output(stderr);
2877 }
2878 
2879 // Write info to output files
2880 void RegInterface::output(FILE *fp) {
2881   Interface::output(fp);
2882 }
2883 
2884 //------------------------------ConstInterface---------------------------------
2885 ConstInterface::ConstInterface() : Interface("CONST_INTER") {
2886 }
2887 ConstInterface::~ConstInterface() {
2888 }
2889 
2890 void ConstInterface::dump() {
2891   output(stderr);
2892 }
2893 
2894 // Write info to output files
2895 void ConstInterface::output(FILE *fp) {
2896   Interface::output(fp);
2897 }
2898 
2899 //------------------------------MemInterface-----------------------------------
2900 MemInterface::MemInterface(char *base, char *index, char *scale, char *disp)
2901   : Interface("MEMORY_INTER"), _base(base), _index(index), _scale(scale), _disp(disp) {
2902 }
2903 MemInterface::~MemInterface() {
2904   // not owner of any character arrays
2905 }
2906 
2907 void MemInterface::dump() {
2908   output(stderr);
2909 }
2910 
2911 // Write info to output files
2912 void MemInterface::output(FILE *fp) {
2913   Interface::output(fp);
2914   if ( _base  != nullptr ) fprintf(fp,"  base  == %s\n", _base);
2915   if ( _index != nullptr ) fprintf(fp,"  index == %s\n", _index);
2916   if ( _scale != nullptr ) fprintf(fp,"  scale == %s\n", _scale);
2917   if ( _disp  != nullptr ) fprintf(fp,"  disp  == %s\n", _disp);
2918   // fprintf(fp,"\n");
2919 }
2920 
2921 //------------------------------CondInterface----------------------------------
2922 CondInterface::CondInterface(const char* equal,         const char* equal_format,
2923                              const char* not_equal,     const char* not_equal_format,
2924                              const char* less,          const char* less_format,
2925                              const char* greater_equal, const char* greater_equal_format,
2926                              const char* less_equal,    const char* less_equal_format,
2927                              const char* greater,       const char* greater_format,
2928                              const char* overflow,      const char* overflow_format,
2929                              const char* no_overflow,   const char* no_overflow_format)
2930   : Interface("COND_INTER"),
2931     _equal(equal),                 _equal_format(equal_format),
2932     _not_equal(not_equal),         _not_equal_format(not_equal_format),
2933     _less(less),                   _less_format(less_format),
2934     _greater_equal(greater_equal), _greater_equal_format(greater_equal_format),
2935     _less_equal(less_equal),       _less_equal_format(less_equal_format),
2936     _greater(greater),             _greater_format(greater_format),
2937     _overflow(overflow),           _overflow_format(overflow_format),
2938     _no_overflow(no_overflow),     _no_overflow_format(no_overflow_format) {
2939 }
2940 CondInterface::~CondInterface() {
2941   // not owner of any character arrays
2942 }
2943 
2944 void CondInterface::dump() {
2945   output(stderr);
2946 }
2947 
2948 // Write info to output files
2949 void CondInterface::output(FILE *fp) {
2950   Interface::output(fp);
2951   if ( _equal  != nullptr )     fprintf(fp," equal        == %s\n", _equal);
2952   if ( _not_equal  != nullptr ) fprintf(fp," not_equal    == %s\n", _not_equal);
2953   if ( _less  != nullptr )      fprintf(fp," less         == %s\n", _less);
2954   if ( _greater_equal  != nullptr ) fprintf(fp," greater_equal    == %s\n", _greater_equal);
2955   if ( _less_equal  != nullptr ) fprintf(fp," less_equal   == %s\n", _less_equal);
2956   if ( _greater  != nullptr )    fprintf(fp," greater      == %s\n", _greater);
2957   if ( _overflow != nullptr )    fprintf(fp," overflow     == %s\n", _overflow);
2958   if ( _no_overflow != nullptr ) fprintf(fp," no_overflow  == %s\n", _no_overflow);
2959   // fprintf(fp,"\n");
2960 }
2961 
2962 //------------------------------ConstructRule----------------------------------
2963 ConstructRule::ConstructRule(char *cnstr)
2964   : _construct(cnstr) {
2965 }
2966 ConstructRule::~ConstructRule() {
2967 }
2968 
2969 void ConstructRule::dump() {
2970   output(stderr);
2971 }
2972 
2973 void ConstructRule::output(FILE *fp) {
2974   fprintf(fp,"\nConstruct Rule\n");  // Write to output files
2975 }
2976 
2977 
2978 //==============================Shared Forms===================================
2979 //------------------------------AttributeForm----------------------------------
2980 int         AttributeForm::_insId   = 0;           // start counter at 0
2981 int         AttributeForm::_opId    = 0;           // start counter at 0
2982 const char* AttributeForm::_ins_cost = "ins_cost"; // required name
2983 const char* AttributeForm::_op_cost  = "op_cost";  // required name
2984 
2985 AttributeForm::AttributeForm(char *attr, int type, char *attrdef)
2986   : Form(Form::ATTR), _attrname(attr), _atype(type), _attrdef(attrdef) {
2987     if (type==OP_ATTR) {
2988       id = ++_opId;
2989     }
2990     else if (type==INS_ATTR) {
2991       id = ++_insId;
2992     }
2993     else assert( false,"");
2994 }
2995 AttributeForm::~AttributeForm() {
2996 }
2997 
2998 // Dynamic type check
2999 AttributeForm *AttributeForm::is_attribute() const {
3000   return (AttributeForm*)this;
3001 }
3002 
3003 
3004 // inlined  // int  AttributeForm::type() { return id;}
3005 
3006 void AttributeForm::dump() {
3007   output(stderr);
3008 }
3009 
3010 void AttributeForm::output(FILE *fp) {
3011   if( _attrname && _attrdef ) {
3012     fprintf(fp,"\n// AttributeForm \nstatic const int %s = %s;\n",
3013             _attrname, _attrdef);
3014   }
3015   else {
3016     fprintf(fp,"\n// AttributeForm missing name %s or definition %s\n",
3017             (_attrname?_attrname:""), (_attrdef?_attrdef:"") );
3018   }
3019 }
3020 
3021 //------------------------------Component--------------------------------------
3022 Component::Component(const char *name, const char *type, int usedef)
3023   : _name(name), _type(type), _usedef(usedef) {
3024     _ftype = Form::COMP;
3025 }
3026 Component::~Component() {
3027 }
3028 
3029 // True if this component is equal to the parameter.
3030 bool Component::is(int use_def_kill_enum) const {
3031   return (_usedef == use_def_kill_enum ? true : false);
3032 }
3033 // True if this component is used/def'd/kill'd as the parameter suggests.
3034 bool Component::isa(int use_def_kill_enum) const {
3035   return (_usedef & use_def_kill_enum) == use_def_kill_enum;
3036 }
3037 
3038 // Extend this component with additional use/def/kill behavior
3039 int Component::promote_use_def_info(int new_use_def) {
3040   _usedef |= new_use_def;
3041 
3042   return _usedef;
3043 }
3044 
3045 // Check the base type of this component, if it has one
3046 const char *Component::base_type(FormDict &globals) {
3047   const Form *frm = globals[_type];
3048   if (frm == nullptr) return nullptr;
3049   OperandForm *op = frm->is_operand();
3050   if (op == nullptr) return nullptr;
3051   if (op->ideal_only()) return op->_ident;
3052   return (char *)op->ideal_type(globals);
3053 }
3054 
3055 void Component::dump() {
3056   output(stderr);
3057 }
3058 
3059 void Component::output(FILE *fp) {
3060   fprintf(fp,"Component:");  // Write to output files
3061   fprintf(fp, "  name = %s", _name);
3062   fprintf(fp, ", type = %s", _type);
3063   assert(_usedef != 0, "unknown effect");
3064   fprintf(fp, ", use/def = %s\n", getUsedefName());
3065 }
3066 
3067 
3068 //------------------------------ComponentList---------------------------------
3069 ComponentList::ComponentList() : NameList(), _matchcnt(0) {
3070 }
3071 ComponentList::~ComponentList() {
3072   // // This list may not own its elements if copied via assignment
3073   // Component *component;
3074   // for (reset(); (component = iter()) != nullptr;) {
3075   //   delete component;
3076   // }
3077 }
3078 
3079 void   ComponentList::insert(Component *component, bool mflag) {
3080   NameList::addName((char *)component);
3081   if(mflag) _matchcnt++;
3082 }
3083 void   ComponentList::insert(const char *name, const char *opType, int usedef,
3084                              bool mflag) {
3085   Component * component = new Component(name, opType, usedef);
3086   insert(component, mflag);
3087 }
3088 Component *ComponentList::current() { return (Component*)NameList::current(); }
3089 Component *ComponentList::iter()    { return (Component*)NameList::iter(); }
3090 Component *ComponentList::match_iter() {
3091   if(_iter < _matchcnt) return (Component*)NameList::iter();
3092   return nullptr;
3093 }
3094 Component *ComponentList::post_match_iter() {
3095   Component *comp = iter();
3096   // At end of list?
3097   if ( comp == nullptr ) {
3098     return comp;
3099   }
3100   // In post-match components?
3101   if (_iter > match_count()-1) {
3102     return comp;
3103   }
3104 
3105   return post_match_iter();
3106 }
3107 
3108 void       ComponentList::reset()   { NameList::reset(); }
3109 int        ComponentList::count()   { return NameList::count(); }
3110 
3111 Component *ComponentList::operator[](int position) {
3112   // Shortcut complete iteration if there are not enough entries
3113   if (position >= count()) return nullptr;
3114 
3115   int        index     = 0;
3116   Component *component = nullptr;
3117   for (reset(); (component = iter()) != nullptr;) {
3118     if (index == position) {
3119       return component;
3120     }
3121     ++index;
3122   }
3123 
3124   return nullptr;
3125 }
3126 
3127 const Component *ComponentList::search(const char *name) {
3128   PreserveIter pi(this);
3129   reset();
3130   for( Component *comp = nullptr; ((comp = iter()) != nullptr); ) {
3131     if( strcmp(comp->_name,name) == 0 ) return comp;
3132   }
3133 
3134   return nullptr;
3135 }
3136 
3137 // Return number of USEs + number of DEFs
3138 // When there are no components, or the first component is a USE,
3139 // then we add '1' to hold a space for the 'result' operand.
3140 int ComponentList::num_operands() {
3141   PreserveIter pi(this);
3142   uint       count = 1;           // result operand
3143   uint       position = 0;
3144 
3145   Component *component  = nullptr;
3146   for( reset(); (component = iter()) != nullptr; ++position ) {
3147     if( component->isa(Component::USE) ||
3148         ( position == 0 && (! component->isa(Component::DEF))) ) {
3149       ++count;
3150     }
3151   }
3152 
3153   return count;
3154 }
3155 
3156 // Return zero-based position of operand 'name' in list;  -1 if not in list.
3157 // if parameter 'usedef' is ::USE, it will match USE, USE_DEF, ...
3158 int ComponentList::operand_position(const char *name, int usedef, Form *fm) {
3159   PreserveIter pi(this);
3160   int position = 0;
3161   int num_opnds = num_operands();
3162   Component *component;
3163   Component* preceding_non_use = nullptr;
3164   Component* first_def = nullptr;
3165   for (reset(); (component = iter()) != nullptr; ++position) {
3166     // When the first component is not a DEF,
3167     // leave space for the result operand!
3168     if ( position==0 && (! component->isa(Component::DEF)) ) {
3169       ++position;
3170       ++num_opnds;
3171     }
3172     if (strcmp(name, component->_name)==0 && (component->isa(usedef))) {
3173       // When the first entry in the component list is a DEF and a USE
3174       // Treat them as being separate, a DEF first, then a USE
3175       if( position==0
3176           && usedef==Component::USE && component->isa(Component::DEF) ) {
3177         assert(position+1 < num_opnds, "advertised index in bounds");
3178         return position+1;
3179       } else {
3180         if( preceding_non_use && strcmp(component->_name, preceding_non_use->_name) ) {
3181           fprintf(stderr, "the name '%s(%s)' should not precede the name '%s(%s)'",
3182                   preceding_non_use->_name, preceding_non_use->getUsedefName(),
3183                   name, component->getUsedefName());
3184           if (fm && fm->is_instruction()) fprintf(stderr,  "in form '%s'", fm->is_instruction()->_ident);
3185           if (fm && fm->is_operand()) fprintf(stderr,  "in form '%s'", fm->is_operand()->_ident);
3186           fprintf(stderr,  "\n");
3187         }
3188         if( position >= num_opnds ) {
3189           fprintf(stderr, "the name '%s' is too late in its name list", name);
3190           if (fm && fm->is_instruction()) fprintf(stderr,  "in form '%s'", fm->is_instruction()->_ident);
3191           if (fm && fm->is_operand()) fprintf(stderr,  "in form '%s'", fm->is_operand()->_ident);
3192           fprintf(stderr,  "\n");
3193         }
3194         assert(position < num_opnds, "advertised index in bounds");
3195         return position;
3196       }
3197     }
3198     if( component->isa(Component::DEF)
3199         && component->isa(Component::USE) ) {
3200       ++position;
3201       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3202     }
3203     if( component->isa(Component::DEF) && !first_def ) {
3204       first_def = component;
3205     }
3206     if( !component->isa(Component::USE) && component != first_def ) {
3207       preceding_non_use = component;
3208     } else if( preceding_non_use && !strcmp(component->_name, preceding_non_use->_name) ) {
3209       preceding_non_use = nullptr;
3210     }
3211   }
3212   return Not_in_list;
3213 }
3214 
3215 // Find position for this name, regardless of use/def information
3216 int ComponentList::operand_position(const char *name) {
3217   PreserveIter pi(this);
3218   int position = 0;
3219   Component *component;
3220   for (reset(); (component = iter()) != nullptr; ++position) {
3221     // When the first component is not a DEF,
3222     // leave space for the result operand!
3223     if ( position==0 && (! component->isa(Component::DEF)) ) {
3224       ++position;
3225     }
3226     if (strcmp(name, component->_name)==0) {
3227       return position;
3228     }
3229     if( component->isa(Component::DEF)
3230         && component->isa(Component::USE) ) {
3231       ++position;
3232       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3233     }
3234   }
3235   return Not_in_list;
3236 }
3237 
3238 int ComponentList::operand_position_format(const char *name, Form *fm) {
3239   PreserveIter pi(this);
3240   int  first_position = operand_position(name);
3241   int  use_position   = operand_position(name, Component::USE, fm);
3242 
3243   return ((first_position < use_position) ? use_position : first_position);
3244 }
3245 
3246 int ComponentList::label_position() {
3247   PreserveIter pi(this);
3248   int position = 0;
3249   reset();
3250   for( Component *comp; (comp = iter()) != nullptr; ++position) {
3251     // When the first component is not a DEF,
3252     // leave space for the result operand!
3253     if ( position==0 && (! comp->isa(Component::DEF)) ) {
3254       ++position;
3255     }
3256     if (strcmp(comp->_type, "label")==0) {
3257       return position;
3258     }
3259     if( comp->isa(Component::DEF)
3260         && comp->isa(Component::USE) ) {
3261       ++position;
3262       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3263     }
3264   }
3265 
3266   return -1;
3267 }
3268 
3269 int ComponentList::method_position() {
3270   PreserveIter pi(this);
3271   int position = 0;
3272   reset();
3273   for( Component *comp; (comp = iter()) != nullptr; ++position) {
3274     // When the first component is not a DEF,
3275     // leave space for the result operand!
3276     if ( position==0 && (! comp->isa(Component::DEF)) ) {
3277       ++position;
3278     }
3279     if (strcmp(comp->_type, "method")==0) {
3280       return position;
3281     }
3282     if( comp->isa(Component::DEF)
3283         && comp->isa(Component::USE) ) {
3284       ++position;
3285       if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3286     }
3287   }
3288 
3289   return -1;
3290 }
3291 
3292 void ComponentList::dump() { output(stderr); }
3293 
3294 void ComponentList::output(FILE *fp) {
3295   PreserveIter pi(this);
3296   fprintf(fp, "\n");
3297   Component *component;
3298   for (reset(); (component = iter()) != nullptr;) {
3299     component->output(fp);
3300   }
3301   fprintf(fp, "\n");
3302 }
3303 
3304 //------------------------------MatchNode--------------------------------------
3305 MatchNode::MatchNode(ArchDesc &ad, const char *result, const char *mexpr,
3306                      const char *opType, MatchNode *lChild, MatchNode *rChild)
3307   : _AD(ad), _result(result), _name(mexpr), _opType(opType),
3308     _lChild(lChild), _rChild(rChild), _internalop(0), _numleaves(0),
3309     _commutative_id(0) {
3310   _numleaves = (lChild ? lChild->_numleaves : 0)
3311                + (rChild ? rChild->_numleaves : 0);
3312 }
3313 
3314 MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode)
3315   : _AD(ad), _result(mnode._result), _name(mnode._name),
3316     _opType(mnode._opType), _lChild(mnode._lChild), _rChild(mnode._rChild),
3317     _internalop(0), _numleaves(mnode._numleaves),
3318     _commutative_id(mnode._commutative_id) {
3319 }
3320 
3321 MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode, int clone)
3322   : _AD(ad), _result(mnode._result), _name(mnode._name),
3323     _opType(mnode._opType),
3324     _internalop(0), _numleaves(mnode._numleaves),
3325     _commutative_id(mnode._commutative_id) {
3326   if (mnode._lChild) {
3327     _lChild = new MatchNode(ad, *mnode._lChild, clone);
3328   } else {
3329     _lChild = nullptr;
3330   }
3331   if (mnode._rChild) {
3332     _rChild = new MatchNode(ad, *mnode._rChild, clone);
3333   } else {
3334     _rChild = nullptr;
3335   }
3336 }
3337 
3338 MatchNode::~MatchNode() {
3339   // // This node may not own its children if copied via assignment
3340   // if( _lChild ) delete _lChild;
3341   // if( _rChild ) delete _rChild;
3342 }
3343 
3344 bool  MatchNode::find_type(const char *type, int &position) const {
3345   if ( (_lChild != nullptr) && (_lChild->find_type(type, position)) ) return true;
3346   if ( (_rChild != nullptr) && (_rChild->find_type(type, position)) ) return true;
3347 
3348   if (strcmp(type,_opType)==0)  {
3349     return true;
3350   } else {
3351     ++position;
3352   }
3353   return false;
3354 }
3355 
3356 // Recursive call collecting info on top-level operands, not transitive.
3357 // Implementation does not modify state of internal structures.
3358 void MatchNode::append_components(FormDict& locals, ComponentList& components,
3359                                   bool def_flag) const {
3360   int usedef = def_flag ? Component::DEF : Component::USE;
3361   FormDict &globals = _AD.globalNames();
3362 
3363   assert (_name != nullptr, "MatchNode::build_components encountered empty node\n");
3364   // Base case
3365   if (_lChild==nullptr && _rChild==nullptr) {
3366     // If _opType is not an operation, do not build a component for it #####
3367     const Form *f = globals[_opType];
3368     if( f != nullptr ) {
3369       // Add non-ideals that are operands, operand-classes,
3370       if( ! f->ideal_only()
3371           && (f->is_opclass() || f->is_operand()) ) {
3372         components.insert(_name, _opType, usedef, true);
3373       }
3374     }
3375     return;
3376   }
3377   // Promote results of "Set" to DEF
3378   bool tmpdef_flag = (!strcmp(_opType, "Set")) ? true : false;
3379   if (_lChild) _lChild->append_components(locals, components, tmpdef_flag);
3380   tmpdef_flag = false;   // only applies to component immediately following 'Set'
3381   if (_rChild) _rChild->append_components(locals, components, tmpdef_flag);
3382 }
3383 
3384 // Find the n'th base-operand in the match node,
3385 // recursively investigates match rules of user-defined operands.
3386 //
3387 // Implementation does not modify state of internal structures since they
3388 // can be shared.
3389 bool MatchNode::base_operand(uint &position, FormDict &globals,
3390                              const char * &result, const char * &name,
3391                              const char * &opType) const {
3392   assert (_name != nullptr, "MatchNode::base_operand encountered empty node\n");
3393   // Base case
3394   if (_lChild==nullptr && _rChild==nullptr) {
3395     // Check for special case: "Universe", "label"
3396     if (strcmp(_opType,"Universe") == 0 || strcmp(_opType,"label")==0 ) {
3397       if (position == 0) {
3398         result = _result;
3399         name   = _name;
3400         opType = _opType;
3401         return 1;
3402       } else {
3403         -- position;
3404         return 0;
3405       }
3406     }
3407 
3408     const Form *form = globals[_opType];
3409     MatchNode *matchNode = nullptr;
3410     // Check for user-defined type
3411     if (form) {
3412       // User operand or instruction?
3413       OperandForm  *opForm = form->is_operand();
3414       InstructForm *inForm = form->is_instruction();
3415       if ( opForm ) {
3416         matchNode = (MatchNode*)opForm->_matrule;
3417       } else if ( inForm ) {
3418         matchNode = (MatchNode*)inForm->_matrule;
3419       }
3420     }
3421     // if this is user-defined, recurse on match rule
3422     // User-defined operand and instruction forms have a match-rule.
3423     if (matchNode) {
3424       return (matchNode->base_operand(position,globals,result,name,opType));
3425     } else {
3426       // Either not a form, or a system-defined form (no match rule).
3427       if (position==0) {
3428         result = _result;
3429         name   = _name;
3430         opType = _opType;
3431         return 1;
3432       } else {
3433         --position;
3434         return 0;
3435       }
3436     }
3437 
3438   } else {
3439     // Examine the left child and right child as well
3440     if (_lChild) {
3441       if (_lChild->base_operand(position, globals, result, name, opType))
3442         return 1;
3443     }
3444 
3445     if (_rChild) {
3446       if (_rChild->base_operand(position, globals, result, name, opType))
3447         return 1;
3448     }
3449   }
3450 
3451   return 0;
3452 }
3453 
3454 // Recursive call on all operands' match rules in my match rule.
3455 uint  MatchNode::num_consts(FormDict &globals) const {
3456   uint        index      = 0;
3457   uint        num_consts = 0;
3458   const char *result;
3459   const char *name;
3460   const char *opType;
3461 
3462   for (uint position = index;
3463        base_operand(position,globals,result,name,opType); position = index) {
3464     ++index;
3465     if( ideal_to_const_type(opType) )        num_consts++;
3466   }
3467 
3468   return num_consts;
3469 }
3470 
3471 // Recursive call on all operands' match rules in my match rule.
3472 // Constants in match rule subtree with specified type
3473 uint  MatchNode::num_consts(FormDict &globals, Form::DataType type) const {
3474   uint        index      = 0;
3475   uint        num_consts = 0;
3476   const char *result;
3477   const char *name;
3478   const char *opType;
3479 
3480   for (uint position = index;
3481        base_operand(position,globals,result,name,opType); position = index) {
3482     ++index;
3483     if( ideal_to_const_type(opType) == type ) num_consts++;
3484   }
3485 
3486   return num_consts;
3487 }
3488 
3489 // Recursive call on all operands' match rules in my match rule.
3490 uint  MatchNode::num_const_ptrs(FormDict &globals) const {
3491   return  num_consts( globals, Form::idealP );
3492 }
3493 
3494 bool  MatchNode::sets_result() const {
3495   return   ( (strcmp(_name,"Set") == 0) ? true : false );
3496 }
3497 
3498 const char *MatchNode::reduce_right(FormDict &globals) const {
3499   // If there is no right reduction, return null.
3500   const char      *rightStr    = nullptr;
3501 
3502   // If we are a "Set", start from the right child.
3503   const MatchNode *const mnode = sets_result() ?
3504     (const MatchNode *)this->_rChild :
3505     (const MatchNode *)this;
3506 
3507   // If our right child exists, it is the right reduction
3508   if ( mnode->_rChild ) {
3509     rightStr = mnode->_rChild->_internalop ? mnode->_rChild->_internalop
3510       : mnode->_rChild->_opType;
3511   }
3512   // Else, May be simple chain rule: (Set dst operand_form), rightStr=nullptr;
3513   return rightStr;
3514 }
3515 
3516 const char *MatchNode::reduce_left(FormDict &globals) const {
3517   // If there is no left reduction, return null.
3518   const char  *leftStr  = nullptr;
3519 
3520   // If we are a "Set", start from the right child.
3521   const MatchNode *const mnode = sets_result() ?
3522     (const MatchNode *)this->_rChild :
3523     (const MatchNode *)this;
3524 
3525   // If our left child exists, it is the left reduction
3526   if ( mnode->_lChild ) {
3527     leftStr = mnode->_lChild->_internalop ? mnode->_lChild->_internalop
3528       : mnode->_lChild->_opType;
3529   } else {
3530     // May be simple chain rule: (Set dst operand_form_source)
3531     if ( sets_result() ) {
3532       OperandForm *oper = globals[mnode->_opType]->is_operand();
3533       if( oper ) {
3534         leftStr = mnode->_opType;
3535       }
3536     }
3537   }
3538   return leftStr;
3539 }
3540 
3541 //------------------------------count_instr_names------------------------------
3542 // Count occurrences of operands names in the leaves of the instruction
3543 // match rule.
3544 void MatchNode::count_instr_names( Dict &names ) {
3545   if( _lChild ) _lChild->count_instr_names(names);
3546   if( _rChild ) _rChild->count_instr_names(names);
3547   if( !_lChild && !_rChild ) {
3548     uintptr_t cnt = (uintptr_t)names[_name];
3549     cnt++;                      // One more name found
3550     names.Insert(_name,(void*)cnt);
3551   }
3552 }
3553 
3554 //------------------------------build_instr_pred-------------------------------
3555 // Build a path to 'name' in buf.  Actually only build if cnt is zero, so we
3556 // can skip some leading instances of 'name'.
3557 int MatchNode::build_instr_pred( char *buf, const char *name, int cnt, int path_bitmask, int level) {
3558   if( _lChild ) {
3559     cnt = _lChild->build_instr_pred(buf, name, cnt, path_bitmask, level+1);
3560     if( cnt < 0 ) {
3561       return cnt;   // Found it, all done
3562     }
3563   }
3564   if( _rChild ) {
3565     path_bitmask |= 1 << level;
3566     cnt = _rChild->build_instr_pred( buf, name, cnt, path_bitmask, level+1);
3567     if( cnt < 0 ) {
3568       return cnt;   // Found it, all done
3569     }
3570   }
3571   if( !_lChild && !_rChild ) {  // Found a leaf
3572     // Wrong name?  Give up...
3573     if( strcmp(name,_name) ) return cnt;
3574     if( !cnt )  {
3575       for(int i = 0; i < level; i++) {
3576         int kid = path_bitmask &  (1 << i);
3577         if (0 == kid) {
3578           strcpy( buf, "_kids[0]->" );
3579         } else {
3580           strcpy( buf, "_kids[1]->" );
3581         }
3582         buf += 10;
3583       }
3584       strcpy( buf, "_leaf" );
3585     }
3586     return cnt-1;
3587   }
3588   return cnt;
3589 }
3590 
3591 
3592 //------------------------------build_internalop-------------------------------
3593 // Build string representation of subtree
3594 void MatchNode::build_internalop( ) {
3595   char *iop, *subtree;
3596   const char *lstr, *rstr;
3597   // Build string representation of subtree
3598   // Operation lchildType rchildType
3599   int len = (int)strlen(_opType) + 4;
3600   lstr = (_lChild) ? ((_lChild->_internalop) ?
3601                        _lChild->_internalop : _lChild->_opType) : "";
3602   rstr = (_rChild) ? ((_rChild->_internalop) ?
3603                        _rChild->_internalop : _rChild->_opType) : "";
3604   len += (int)strlen(lstr) + (int)strlen(rstr);
3605   subtree = (char *)AdlAllocateHeap(len);
3606   snprintf_checked(subtree, len, "_%s_%s_%s", _opType, lstr, rstr);
3607   // Hash the subtree string in _internalOps; if a name exists, use it
3608   iop = (char *)_AD._internalOps[subtree];
3609   // Else create a unique name, and add it to the hash table
3610   if (iop == nullptr) {
3611     iop = subtree;
3612     _AD._internalOps.Insert(subtree, iop);
3613     _AD._internalOpNames.addName(iop);
3614     _AD._internalMatch.Insert(iop, this);
3615   }
3616   // Add the internal operand name to the MatchNode
3617   _internalop = iop;
3618   _result = iop;
3619 }
3620 
3621 
3622 void MatchNode::dump() {
3623   output(stderr);
3624 }
3625 
3626 void MatchNode::output(FILE *fp) {
3627   if (_lChild==0 && _rChild==0) {
3628     fprintf(fp," %s",_name);    // operand
3629   }
3630   else {
3631     fprintf(fp," (%s ",_name);  // " (opcodeName "
3632     if(_lChild) _lChild->output(fp); //               left operand
3633     if(_rChild) _rChild->output(fp); //                    right operand
3634     fprintf(fp,")");                 //                                 ")"
3635   }
3636 }
3637 
3638 void MatchNode::forms_do(FormClosure *f) {
3639   f->do_form_by_name(_name);
3640   if (_lChild) f->do_form(_lChild);
3641   if (_rChild) f->do_form(_rChild);
3642 }
3643 
3644 int MatchNode::needs_ideal_memory_edge(FormDict &globals) const {
3645   static const char *needs_ideal_memory_list[] = {
3646     "StoreI","StoreL","StoreLSpecial","StoreP","StoreN","StoreNKlass","StoreD","StoreF" ,
3647     "StoreB","StoreC","Store" ,"StoreFP",
3648     "LoadI", "LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF"  ,
3649     "LoadB" , "LoadUB", "LoadUS" ,"LoadS" ,"Load" ,
3650     "StoreVector", "LoadVector", "LoadVectorMasked", "StoreVectorMasked",
3651     "LoadVectorGather", "StoreVectorScatter", "LoadVectorGatherMasked", "StoreVectorScatterMasked",
3652     "LoadRange", "LoadKlass", "LoadNKlass", "LoadL_unaligned", "LoadD_unaligned",
3653     "CompareAndSwapB", "CompareAndSwapS", "CompareAndSwapI", "CompareAndSwapL", "CompareAndSwapP", "CompareAndSwapN",
3654     "WeakCompareAndSwapB", "WeakCompareAndSwapS", "WeakCompareAndSwapI", "WeakCompareAndSwapL", "WeakCompareAndSwapP", "WeakCompareAndSwapN",
3655     "CompareAndExchangeB", "CompareAndExchangeS", "CompareAndExchangeI", "CompareAndExchangeL", "CompareAndExchangeP", "CompareAndExchangeN",
3656 #if INCLUDE_SHENANDOAHGC
3657     "ShenandoahCompareAndSwapN", "ShenandoahCompareAndSwapP", "ShenandoahWeakCompareAndSwapP", "ShenandoahWeakCompareAndSwapN", "ShenandoahCompareAndExchangeP", "ShenandoahCompareAndExchangeN",
3658 #endif
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", "XorI","XorL",
3963     "UMax","UMin"
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", "UMax","UMin"
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", "UMinV", "UMaxV",
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     "SelectFromTwoVector", "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", "SaturatingAddV", "SaturatingSubV",
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 }