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