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