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