archDesc.cpp revision 3724:8e47bac5643a
1//
2// Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
3// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4//
5// This code is free software; you can redistribute it and/or modify it
6// under the terms of the GNU General Public License version 2 only, as
7// published by the Free Software Foundation.
8//
9// This code is distributed in the hope that it will be useful, but WITHOUT
10// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12// version 2 for more details (a copy is included in the LICENSE file that
13// accompanied this code).
14//
15// You should have received a copy of the GNU General Public License version
16// 2 along with this work; if not, write to the Free Software Foundation,
17// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18//
19// Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20// or visit www.oracle.com if you need additional information or have any
21// questions.
22//
23//
24
25
26// archDesc.cpp - Internal format for architecture definition
27#include "adlc.hpp"
28
29static FILE *errfile = stderr;
30
31//--------------------------- utility functions -----------------------------
32inline char  toUpper(char lower) {
33  return (('a' <= lower && lower <= 'z') ? (lower + ('A'-'a')) : lower);
34}
35char *toUpper(const char *str) {
36  char *upper  = new char[strlen(str)+1];
37  char *result = upper;
38  const char *end    = str + strlen(str);
39  for (; str < end; ++str, ++upper) {
40    *upper = toUpper(*str);
41  }
42  *upper = '\0';
43  return result;
44}
45
46// Utilities to characterize effect statements
47static bool is_def(int usedef) {
48  switch(usedef) {
49  case Component::DEF:
50  case Component::USE_DEF: return true; break;
51  }
52  return false;
53}
54
55static bool is_use(int usedef) {
56  switch(usedef) {
57  case Component::USE:
58  case Component::USE_DEF:
59  case Component::USE_KILL: return true; break;
60  }
61  return false;
62}
63
64static bool is_kill(int usedef) {
65  switch(usedef) {
66  case Component::KILL:
67  case Component::USE_KILL: return true; break;
68  }
69  return false;
70}
71
72//---------------------------ChainList Methods-------------------------------
73ChainList::ChainList() {
74}
75
76void ChainList::insert(const char *name, const char *cost, const char *rule) {
77  _name.addName(name);
78  _cost.addName(cost);
79  _rule.addName(rule);
80}
81
82bool ChainList::search(const char *name) {
83  return _name.search(name);
84}
85
86void ChainList::reset() {
87  _name.reset();
88  _cost.reset();
89  _rule.reset();
90}
91
92bool ChainList::iter(const char * &name, const char * &cost, const char * &rule) {
93  bool        notDone = false;
94  const char *n       = _name.iter();
95  const char *c       = _cost.iter();
96  const char *r       = _rule.iter();
97
98  if (n && c && r) {
99    notDone = true;
100    name = n;
101    cost = c;
102    rule = r;
103  }
104
105  return notDone;
106}
107
108void ChainList::dump() {
109  output(stderr);
110}
111
112void ChainList::output(FILE *fp) {
113  fprintf(fp, "\nChain Rules: output resets iterator\n");
114  const char   *cost  = NULL;
115  const char   *name  = NULL;
116  const char   *rule  = NULL;
117  bool   chains_exist = false;
118  for(reset(); (iter(name,cost,rule)) == true; ) {
119    fprintf(fp, "Chain to <%s> at cost #%s using %s_rule\n",name, cost ? cost : "0", rule);
120    //  // Check for transitive chain rules
121    //  Form *form = (Form *)_globalNames[rule];
122    //  if (form->is_instruction()) {
123    //    // chain_rule(fp, indent, name, cost, rule);
124    //    chain_rule(fp, indent, name, cost, rule);
125    //  }
126  }
127  reset();
128  if( ! chains_exist ) {
129    fprintf(fp, "No entries in this ChainList\n");
130  }
131}
132
133
134//---------------------------MatchList Methods-------------------------------
135bool MatchList::search(const char *opc, const char *res, const char *lch,
136                       const char *rch, Predicate *pr) {
137  bool tmp = false;
138  if ((res == _resultStr) || (res && _resultStr && !strcmp(res, _resultStr))) {
139    if ((lch == _lchild) || (lch && _lchild && !strcmp(lch, _lchild))) {
140      if ((rch == _rchild) || (rch && _rchild && !strcmp(rch, _rchild))) {
141        char * predStr = get_pred();
142        char * prStr = pr?pr->_pred:NULL;
143        if (ADLParser::equivalent_expressions(prStr, predStr)) {
144          return true;
145        }
146      }
147    }
148  }
149  if (_next) {
150    tmp = _next->search(opc, res, lch, rch, pr);
151  }
152  return tmp;
153}
154
155
156void MatchList::dump() {
157  output(stderr);
158}
159
160void MatchList::output(FILE *fp) {
161  fprintf(fp, "\nMatchList output is Unimplemented();\n");
162}
163
164
165//---------------------------ArchDesc Constructor and Destructor-------------
166
167ArchDesc::ArchDesc()
168  : _globalNames(cmpstr,hashstr, Form::arena),
169    _globalDefs(cmpstr,hashstr, Form::arena),
170    _preproc_table(cmpstr,hashstr, Form::arena),
171    _idealIndex(cmpstr,hashstr, Form::arena),
172    _internalOps(cmpstr,hashstr, Form::arena),
173    _internalMatch(cmpstr,hashstr, Form::arena),
174    _chainRules(cmpstr,hashstr, Form::arena),
175    _cisc_spill_operand(NULL) {
176
177      // Initialize the opcode to MatchList table with NULLs
178      for( int i=0; i<_last_opcode; ++i ) {
179        _mlistab[i] = NULL;
180      }
181
182      // Set-up the global tables
183      initKeywords(_globalNames);    // Initialize the Name Table with keywords
184
185      // Prime user-defined types with predefined types: Set, RegI, RegF, ...
186      initBaseOpTypes();
187
188      // Initialize flags & counters
189      _TotalLines        = 0;
190      _no_output         = 0;
191      _quiet_mode        = 0;
192      _disable_warnings  = 0;
193      _dfa_debug         = 0;
194      _dfa_small         = 0;
195      _adl_debug         = 0;
196      _adlocation_debug  = 0;
197      _internalOpCounter = 0;
198      _cisc_spill_debug  = false;
199      _short_branch_debug = false;
200
201      // Initialize match rule flags
202      for (int i = 0; i < _last_opcode; i++) {
203        _has_match_rule[i] = false;
204      }
205
206      // Error/Warning Counts
207      _syntax_errs       = 0;
208      _semantic_errs     = 0;
209      _warnings          = 0;
210      _internal_errs     = 0;
211
212      // Initialize I/O Files
213      _ADL_file._name = NULL; _ADL_file._fp = NULL;
214      // Machine dependent output files
215      _DFA_file._name    = NULL;  _DFA_file._fp = NULL;
216      _HPP_file._name    = NULL;  _HPP_file._fp = NULL;
217      _CPP_file._name    = NULL;  _CPP_file._fp = NULL;
218      _bug_file._name    = "bugs.out";      _bug_file._fp = NULL;
219
220      // Initialize Register & Pipeline Form Pointers
221      _register = NULL;
222      _encode = NULL;
223      _pipeline = NULL;
224}
225
226ArchDesc::~ArchDesc() {
227  // Clean-up and quit
228
229}
230
231//---------------------------ArchDesc methods: Public ----------------------
232// Store forms according to type
233void ArchDesc::addForm(PreHeaderForm *ptr) { _pre_header.addForm(ptr); };
234void ArchDesc::addForm(HeaderForm    *ptr) { _header.addForm(ptr); };
235void ArchDesc::addForm(SourceForm    *ptr) { _source.addForm(ptr); };
236void ArchDesc::addForm(EncodeForm    *ptr) { _encode = ptr; };
237void ArchDesc::addForm(InstructForm  *ptr) { _instructions.addForm(ptr); };
238void ArchDesc::addForm(MachNodeForm  *ptr) { _machnodes.addForm(ptr); };
239void ArchDesc::addForm(OperandForm   *ptr) { _operands.addForm(ptr); };
240void ArchDesc::addForm(OpClassForm   *ptr) { _opclass.addForm(ptr); };
241void ArchDesc::addForm(AttributeForm *ptr) { _attributes.addForm(ptr); };
242void ArchDesc::addForm(RegisterForm  *ptr) { _register = ptr; };
243void ArchDesc::addForm(FrameForm     *ptr) { _frame = ptr; };
244void ArchDesc::addForm(PipelineForm  *ptr) { _pipeline = ptr; };
245
246// Build MatchList array and construct MatchLists
247void ArchDesc::generateMatchLists() {
248  // Call inspection routines to populate array
249  inspectOperands();
250  inspectInstructions();
251}
252
253// Build MatchList structures for operands
254void ArchDesc::inspectOperands() {
255
256  // Iterate through all operands
257  _operands.reset();
258  OperandForm *op;
259  for( ; (op = (OperandForm*)_operands.iter()) != NULL;) {
260    // Construct list of top-level operands (components)
261    op->build_components();
262
263    // Ensure that match field is defined.
264    if ( op->_matrule == NULL )  continue;
265
266    // Type check match rules
267    check_optype(op->_matrule);
268
269    // Construct chain rules
270    build_chain_rule(op);
271
272    MatchRule &mrule = *op->_matrule;
273    Predicate *pred  =  op->_predicate;
274
275    // Grab the machine type of the operand
276    const char  *rootOp    = op->_ident;
277    mrule._machType  = rootOp;
278
279    // Check for special cases
280    if (strcmp(rootOp,"Universe")==0) continue;
281    if (strcmp(rootOp,"label")==0) continue;
282    // !!!!! !!!!!
283    assert( strcmp(rootOp,"sReg") != 0, "Disable untyped 'sReg'");
284    if (strcmp(rootOp,"sRegI")==0) continue;
285    if (strcmp(rootOp,"sRegP")==0) continue;
286    if (strcmp(rootOp,"sRegF")==0) continue;
287    if (strcmp(rootOp,"sRegD")==0) continue;
288    if (strcmp(rootOp,"sRegL")==0) continue;
289
290    // Cost for this match
291    const char *costStr     = op->cost();
292    const char *defaultCost =
293      ((AttributeForm*)_globalNames[AttributeForm::_op_cost])->_attrdef;
294    const char *cost        =  costStr? costStr : defaultCost;
295
296    // Find result type for match.
297    const char *result      = op->reduce_result();
298    bool        has_root    = false;
299
300    // Construct a MatchList for this entry
301    buildMatchList(op->_matrule, result, rootOp, pred, cost);
302  }
303}
304
305// Build MatchList structures for instructions
306void ArchDesc::inspectInstructions() {
307
308  // Iterate through all instructions
309  _instructions.reset();
310  InstructForm *instr;
311  for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
312    // Construct list of top-level operands (components)
313    instr->build_components();
314
315    // Ensure that match field is defined.
316    if ( instr->_matrule == NULL )  continue;
317
318    MatchRule &mrule = *instr->_matrule;
319    Predicate *pred  =  instr->build_predicate();
320
321    // Grab the machine type of the operand
322    const char  *rootOp    = instr->_ident;
323    mrule._machType  = rootOp;
324
325    // Cost for this match
326    const char *costStr = instr->cost();
327    const char *defaultCost =
328      ((AttributeForm*)_globalNames[AttributeForm::_ins_cost])->_attrdef;
329    const char *cost    =  costStr? costStr : defaultCost;
330
331    // Find result type for match
332    const char *result  = instr->reduce_result();
333
334    if ( instr->is_ideal_branch() && instr->label_position() == -1 ||
335        !instr->is_ideal_branch() && instr->label_position() != -1) {
336      syntax_err(instr->_linenum, "%s: Only branches to a label are supported\n", rootOp);
337    }
338
339    Attribute *attr = instr->_attribs;
340    while (attr != NULL) {
341      if (strcmp(attr->_ident,"ins_short_branch") == 0 &&
342          attr->int_val(*this) != 0) {
343        if (!instr->is_ideal_branch() || instr->label_position() == -1) {
344          syntax_err(instr->_linenum, "%s: Only short branch to a label is supported\n", rootOp);
345        }
346        instr->set_short_branch(true);
347      } else if (strcmp(attr->_ident,"ins_alignment") == 0 &&
348          attr->int_val(*this) != 0) {
349        instr->set_alignment(attr->int_val(*this));
350      }
351      attr = (Attribute *)attr->_next;
352    }
353
354    if (!instr->is_short_branch()) {
355      buildMatchList(instr->_matrule, result, mrule._machType, pred, cost);
356    }
357  }
358}
359
360static int setsResult(MatchRule &mrule) {
361  if (strcmp(mrule._name,"Set") == 0) return 1;
362  return 0;
363}
364
365const char *ArchDesc::getMatchListIndex(MatchRule &mrule) {
366  if (setsResult(mrule)) {
367    // right child
368    return mrule._rChild->_opType;
369  } else {
370    // first entry
371    return mrule._opType;
372  }
373}
374
375
376//------------------------------result of reduction----------------------------
377
378
379//------------------------------left reduction---------------------------------
380// Return the left reduction associated with an internal name
381const char *ArchDesc::reduceLeft(char         *internalName) {
382  const char *left  = NULL;
383  MatchNode *mnode = (MatchNode*)_internalMatch[internalName];
384  if (mnode->_lChild) {
385    mnode = mnode->_lChild;
386    left = mnode->_internalop ? mnode->_internalop : mnode->_opType;
387  }
388  return left;
389}
390
391
392//------------------------------right reduction--------------------------------
393const char *ArchDesc::reduceRight(char  *internalName) {
394  const char *right  = NULL;
395  MatchNode *mnode = (MatchNode*)_internalMatch[internalName];
396  if (mnode->_rChild) {
397    mnode = mnode->_rChild;
398    right = mnode->_internalop ? mnode->_internalop : mnode->_opType;
399  }
400  return right;
401}
402
403
404//------------------------------check_optype-----------------------------------
405void ArchDesc::check_optype(MatchRule *mrule) {
406  MatchRule *rule = mrule;
407
408  //   !!!!!
409  //   // Cycle through the list of match rules
410  //   while(mrule) {
411  //     // Check for a filled in type field
412  //     if (mrule->_opType == NULL) {
413  //     const Form  *form    = operands[_result];
414  //     OpClassForm *opcForm = form ? form->is_opclass() : NULL;
415  //     assert(opcForm != NULL, "Match Rule contains invalid operand name.");
416  //     }
417  //     char *opType = opcForm->_ident;
418  //   }
419}
420
421//------------------------------add_chain_rule_entry--------------------------
422void ArchDesc::add_chain_rule_entry(const char *src, const char *cost,
423                                    const char *result) {
424  // Look-up the operation in chain rule table
425  ChainList *lst = (ChainList *)_chainRules[src];
426  if (lst == NULL) {
427    lst = new ChainList();
428    _chainRules.Insert(src, lst);
429  }
430  if (!lst->search(result)) {
431    if (cost == NULL) {
432      cost = ((AttributeForm*)_globalNames[AttributeForm::_op_cost])->_attrdef;
433    }
434    lst->insert(result, cost, result);
435  }
436}
437
438//------------------------------build_chain_rule-------------------------------
439void ArchDesc::build_chain_rule(OperandForm *oper) {
440  MatchRule     *rule;
441
442  // Check for chain rules here
443  // If this is only a chain rule
444  if ((oper->_matrule) && (oper->_matrule->_lChild == NULL) &&
445      (oper->_matrule->_rChild == NULL)) {
446
447    {
448      const Form *form = _globalNames[oper->_matrule->_opType];
449      if ((form) && form->is_operand() &&
450          (form->ideal_only() == false)) {
451        add_chain_rule_entry(oper->_matrule->_opType, oper->cost(), oper->_ident);
452      }
453    }
454    // Check for additional chain rules
455    if (oper->_matrule->_next) {
456      rule = oper->_matrule;
457      do {
458        rule = rule->_next;
459        // Any extra match rules after the first must be chain rules
460        const Form *form = _globalNames[rule->_opType];
461        if ((form) && form->is_operand() &&
462            (form->ideal_only() == false)) {
463          add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
464        }
465      } while(rule->_next != NULL);
466    }
467  }
468  else if ((oper->_matrule) && (oper->_matrule->_next)) {
469    // Regardles of whether the first matchrule is a chain rule, check the list
470    rule = oper->_matrule;
471    do {
472      rule = rule->_next;
473      // Any extra match rules after the first must be chain rules
474      const Form *form = _globalNames[rule->_opType];
475      if ((form) && form->is_operand() &&
476          (form->ideal_only() == false)) {
477        assert( oper->cost(), "This case expects NULL cost, not default cost");
478        add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
479      }
480    } while(rule->_next != NULL);
481  }
482
483}
484
485//------------------------------buildMatchList---------------------------------
486// operands and instructions provide the result
487void ArchDesc::buildMatchList(MatchRule *mrule, const char *resultStr,
488                              const char *rootOp, Predicate *pred,
489                              const char *cost) {
490  const char *leftstr, *rightstr;
491  MatchNode  *mnode;
492
493  leftstr = rightstr = NULL;
494  // Check for chain rule, and do not generate a match list for it
495  if ( mrule->is_chain_rule(_globalNames) ) {
496    return;
497  }
498
499  // Identify index position among ideal operands
500  intptr_t    index     = _last_opcode;
501  const char  *indexStr  = getMatchListIndex(*mrule);
502  index  = (intptr_t)_idealIndex[indexStr];
503  if (index == 0) {
504    fprintf(stderr, "Ideal node missing: %s\n", indexStr);
505    assert(index != 0, "Failed lookup of ideal node\n");
506  }
507
508  // Check that this will be placed appropriately in the DFA
509  if (index >= _last_opcode) {
510    fprintf(stderr, "Invalid match rule %s <-- ( %s )\n",
511            resultStr ? resultStr : " ",
512            rootOp    ? rootOp    : " ");
513    assert(index < _last_opcode, "Matching item not in ideal graph\n");
514    return;
515  }
516
517
518  // Walk the MatchRule, generating MatchList entries for each level
519  // of the rule (each nesting of parentheses)
520  // Check for "Set"
521  if (!strcmp(mrule->_opType, "Set")) {
522    mnode = mrule->_rChild;
523    buildMList(mnode, rootOp, resultStr, pred, cost);
524    return;
525  }
526  // Build MatchLists for children
527  // Check each child for an internal operand name, and use that name
528  // for the parent's matchlist entry if it exists
529  mnode = mrule->_lChild;
530  if (mnode) {
531    buildMList(mnode, NULL, NULL, NULL, NULL);
532    leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
533  }
534  mnode = mrule->_rChild;
535  if (mnode) {
536    buildMList(mnode, NULL, NULL, NULL, NULL);
537    rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
538  }
539  // Search for an identical matchlist entry already on the list
540  if ((_mlistab[index] == NULL) ||
541      (_mlistab[index] &&
542       !_mlistab[index]->search(rootOp, resultStr, leftstr, rightstr, pred))) {
543    // Place this match rule at front of list
544    MatchList *mList =
545      new MatchList(_mlistab[index], pred, cost,
546                    rootOp, resultStr, leftstr, rightstr);
547    _mlistab[index] = mList;
548  }
549}
550
551// Recursive call for construction of match lists
552void ArchDesc::buildMList(MatchNode *node, const char *rootOp,
553                          const char *resultOp, Predicate *pred,
554                          const char *cost) {
555  const char *leftstr, *rightstr;
556  const char *resultop;
557  const char *opcode;
558  MatchNode  *mnode;
559  Form       *form;
560
561  leftstr = rightstr = NULL;
562  // Do not process leaves of the Match Tree if they are not ideal
563  if ((node) && (node->_lChild == NULL) && (node->_rChild == NULL) &&
564      ((form = (Form *)_globalNames[node->_opType]) != NULL) &&
565      (!form->ideal_only())) {
566    return;
567  }
568
569  // Identify index position among ideal operands
570  intptr_t    index     = _last_opcode;
571  const char *indexStr  = node ? node->_opType : (char *) " ";
572  index            = (intptr_t)_idealIndex[indexStr];
573  if (index == 0) {
574    fprintf(stderr, "error: operand \"%s\" not found\n", indexStr);
575    assert(0, "fatal error");
576  }
577
578  // Build MatchLists for children
579  // Check each child for an internal operand name, and use that name
580  // for the parent's matchlist entry if it exists
581  mnode = node->_lChild;
582  if (mnode) {
583    buildMList(mnode, NULL, NULL, NULL, NULL);
584    leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
585  }
586  mnode = node->_rChild;
587  if (mnode) {
588    buildMList(mnode, NULL, NULL, NULL, NULL);
589    rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
590  }
591  // Grab the string for the opcode of this list entry
592  if (rootOp == NULL) {
593    opcode = (node->_internalop) ? node->_internalop : node->_opType;
594  } else {
595    opcode = rootOp;
596  }
597  // Grab the string for the result of this list entry
598  if (resultOp == NULL) {
599    resultop = (node->_internalop) ? node->_internalop : node->_opType;
600  }
601  else resultop = resultOp;
602  // Search for an identical matchlist entry already on the list
603  if ((_mlistab[index] == NULL) || (_mlistab[index] &&
604                                    !_mlistab[index]->search(opcode, resultop, leftstr, rightstr, pred))) {
605    // Place this match rule at front of list
606    MatchList *mList =
607      new MatchList(_mlistab[index],pred,cost,
608                    opcode, resultop, leftstr, rightstr);
609    _mlistab[index] = mList;
610  }
611}
612
613// Count number of OperandForms defined
614int  ArchDesc::operandFormCount() {
615  // Only interested in ones with non-NULL match rule
616  int  count = 0; _operands.reset();
617  OperandForm *cur;
618  for( ; (cur = (OperandForm*)_operands.iter()) != NULL; ) {
619    if (cur->_matrule != NULL) ++count;
620  };
621  return count;
622}
623
624// Count number of OpClassForms defined
625int  ArchDesc::opclassFormCount() {
626  // Only interested in ones with non-NULL match rule
627  int  count = 0; _operands.reset();
628  OpClassForm *cur;
629  for( ; (cur = (OpClassForm*)_opclass.iter()) != NULL; ) {
630    ++count;
631  };
632  return count;
633}
634
635// Count number of InstructForms defined
636int  ArchDesc::instructFormCount() {
637  // Only interested in ones with non-NULL match rule
638  int  count = 0; _instructions.reset();
639  InstructForm *cur;
640  for( ; (cur = (InstructForm*)_instructions.iter()) != NULL; ) {
641    if (cur->_matrule != NULL) ++count;
642  };
643  return count;
644}
645
646
647//------------------------------get_preproc_def--------------------------------
648// Return the textual binding for a given CPP flag name.
649// Return NULL if there is no binding, or it has been #undef-ed.
650char* ArchDesc::get_preproc_def(const char* flag) {
651  SourceForm* deff = (SourceForm*) _preproc_table[flag];
652  return (deff == NULL) ? NULL : deff->_code;
653}
654
655
656//------------------------------set_preproc_def--------------------------------
657// Change or create a textual binding for a given CPP flag name.
658// Giving NULL means the flag name is to be #undef-ed.
659// In any case, _preproc_list collects all names either #defined or #undef-ed.
660void ArchDesc::set_preproc_def(const char* flag, const char* def) {
661  SourceForm* deff = (SourceForm*) _preproc_table[flag];
662  if (deff == NULL) {
663    deff = new SourceForm(NULL);
664    _preproc_table.Insert(flag, deff);
665    _preproc_list.addName(flag);   // this supports iteration
666  }
667  deff->_code = (char*) def;
668}
669
670
671bool ArchDesc::verify() {
672
673  if (_register)
674    assert( _register->verify(), "Register declarations failed verification");
675  if (!_quiet_mode)
676    fprintf(stderr,"\n");
677  // fprintf(stderr,"---------------------------- Verify Operands ---------------\n");
678  // _operands.verify();
679  // fprintf(stderr,"\n");
680  // fprintf(stderr,"---------------------------- Verify Operand Classes --------\n");
681  // _opclass.verify();
682  // fprintf(stderr,"\n");
683  // fprintf(stderr,"---------------------------- Verify Attributes  ------------\n");
684  // _attributes.verify();
685  // fprintf(stderr,"\n");
686  if (!_quiet_mode)
687    fprintf(stderr,"---------------------------- Verify Instructions ----------------------------\n");
688  _instructions.verify();
689  if (!_quiet_mode)
690    fprintf(stderr,"\n");
691  // if ( _encode ) {
692  //   fprintf(stderr,"---------------------------- Verify Encodings --------------\n");
693  //   _encode->verify();
694  // }
695
696  //if (_pipeline) _pipeline->verify();
697
698  return true;
699}
700
701
702void ArchDesc::dump() {
703  _pre_header.dump();
704  _header.dump();
705  _source.dump();
706  if (_register) _register->dump();
707  fprintf(stderr,"\n");
708  fprintf(stderr,"------------------ Dump Operands ---------------------\n");
709  _operands.dump();
710  fprintf(stderr,"\n");
711  fprintf(stderr,"------------------ Dump Operand Classes --------------\n");
712  _opclass.dump();
713  fprintf(stderr,"\n");
714  fprintf(stderr,"------------------ Dump Attributes  ------------------\n");
715  _attributes.dump();
716  fprintf(stderr,"\n");
717  fprintf(stderr,"------------------ Dump Instructions -----------------\n");
718  _instructions.dump();
719  if ( _encode ) {
720    fprintf(stderr,"------------------ Dump Encodings --------------------\n");
721    _encode->dump();
722  }
723  if (_pipeline) _pipeline->dump();
724}
725
726
727//------------------------------init_keywords----------------------------------
728// Load the kewords into the global name table
729void ArchDesc::initKeywords(FormDict& names) {
730  // Insert keyword strings into Global Name Table.  Keywords have a NULL value
731  // field for quick easy identification when checking identifiers.
732  names.Insert("instruct", NULL);
733  names.Insert("operand", NULL);
734  names.Insert("attribute", NULL);
735  names.Insert("source", NULL);
736  names.Insert("register", NULL);
737  names.Insert("pipeline", NULL);
738  names.Insert("constraint", NULL);
739  names.Insert("predicate", NULL);
740  names.Insert("encode", NULL);
741  names.Insert("enc_class", NULL);
742  names.Insert("interface", NULL);
743  names.Insert("opcode", NULL);
744  names.Insert("ins_encode", NULL);
745  names.Insert("match", NULL);
746  names.Insert("effect", NULL);
747  names.Insert("expand", NULL);
748  names.Insert("rewrite", NULL);
749  names.Insert("reg_def", NULL);
750  names.Insert("reg_class", NULL);
751  names.Insert("alloc_class", NULL);
752  names.Insert("resource", NULL);
753  names.Insert("pipe_class", NULL);
754  names.Insert("pipe_desc", NULL);
755}
756
757
758//------------------------------internal_err----------------------------------
759// Issue a parser error message, and skip to the end of the current line
760void ArchDesc::internal_err(const char *fmt, ...) {
761  va_list args;
762
763  va_start(args, fmt);
764  _internal_errs += emit_msg(0, INTERNAL_ERR, 0, fmt, args);
765  va_end(args);
766
767  _no_output = 1;
768}
769
770//------------------------------syntax_err----------------------------------
771// Issue a parser error message, and skip to the end of the current line
772void ArchDesc::syntax_err(int lineno, const char *fmt, ...) {
773  va_list args;
774
775  va_start(args, fmt);
776  _internal_errs += emit_msg(0, SYNERR, lineno, fmt, args);
777  va_end(args);
778
779  _no_output = 1;
780}
781
782//------------------------------emit_msg---------------------------------------
783// Emit a user message, typically a warning or error
784int ArchDesc::emit_msg(int quiet, int flag, int line, const char *fmt,
785    va_list args) {
786  static int  last_lineno = -1;
787  int         i;
788  const char *pref;
789
790  switch(flag) {
791  case 0: pref = "Warning: "; break;
792  case 1: pref = "Syntax Error: "; break;
793  case 2: pref = "Semantic Error: "; break;
794  case 3: pref = "Internal Error: "; break;
795  default: assert(0, ""); break;
796  }
797
798  if (line == last_lineno) return 0;
799  last_lineno = line;
800
801  if (!quiet) {                        /* no output if in quiet mode         */
802    i = fprintf(errfile, "%s(%d) ", _ADL_file._name, line);
803    while (i++ <= 15)  fputc(' ', errfile);
804    fprintf(errfile, "%-8s:", pref);
805    vfprintf(errfile, fmt, args);
806    fprintf(errfile, "\n"); }
807  return 1;
808}
809
810
811// ---------------------------------------------------------------------------
812//--------Utilities to build mappings for machine registers ------------------
813// ---------------------------------------------------------------------------
814
815// Construct the name of the register mask.
816static const char *getRegMask(const char *reg_class_name) {
817  if( reg_class_name == NULL ) return "RegMask::Empty";
818
819  if (strcmp(reg_class_name,"Universe")==0) {
820    return "RegMask::Empty";
821  } else if (strcmp(reg_class_name,"stack_slots")==0) {
822    return "(Compile::current()->FIRST_STACK_mask())";
823  } else {
824    char       *rc_name = toUpper(reg_class_name);
825    const char *mask    = "_mask";
826    int         length  = (int)strlen(rc_name) + (int)strlen(mask) + 5;
827    char       *regMask = new char[length];
828    sprintf(regMask,"%s%s()", rc_name, mask);
829    return regMask;
830  }
831}
832
833// Convert a register class name to its register mask.
834const char *ArchDesc::reg_class_to_reg_mask(const char *rc_name) {
835  const char *reg_mask = "RegMask::Empty";
836
837  if( _register ) {
838    RegClass *reg_class  = _register->getRegClass(rc_name);
839    if (reg_class == NULL) {
840      syntax_err(0, "Use of an undefined register class %s", rc_name);
841      return reg_mask;
842    }
843
844    // Construct the name of the register mask.
845    reg_mask = getRegMask(rc_name);
846  }
847
848  return reg_mask;
849}
850
851
852// Obtain the name of the RegMask for an OperandForm
853const char *ArchDesc::reg_mask(OperandForm  &opForm) {
854  const char *regMask      = "RegMask::Empty";
855
856  // Check constraints on result's register class
857  const char *result_class = opForm.constrained_reg_class();
858  if (!result_class) opForm.dump();
859  assert( result_class, "Resulting register class was not defined for operand");
860  regMask = reg_class_to_reg_mask( result_class );
861
862  return regMask;
863}
864
865// Obtain the name of the RegMask for an InstructForm
866const char *ArchDesc::reg_mask(InstructForm &inForm) {
867  const char *result = inForm.reduce_result();
868  assert( result,
869          "Did not find result operand or RegMask for this instruction");
870
871  // Instructions producing 'Universe' use RegMask::Empty
872  if( strcmp(result,"Universe")==0 ) {
873    return "RegMask::Empty";
874  }
875
876  // Lookup this result operand and get its register class
877  Form *form = (Form*)_globalNames[result];
878  assert( form, "Result operand must be defined");
879  OperandForm *oper = form->is_operand();
880  if (oper == NULL) form->dump();
881  assert( oper, "Result must be an OperandForm");
882  return reg_mask( *oper );
883}
884
885
886// Obtain the STACK_OR_reg_mask name for an OperandForm
887char *ArchDesc::stack_or_reg_mask(OperandForm  &opForm) {
888  // name of cisc_spillable version
889  const char *reg_mask_name = reg_mask(opForm);
890  assert( reg_mask_name != NULL, "called with incorrect opForm");
891
892  const char *stack_or = "STACK_OR_";
893  int   length         = (int)strlen(stack_or) + (int)strlen(reg_mask_name) + 1;
894  char *result         = new char[length];
895  sprintf(result,"%s%s", stack_or, reg_mask_name);
896
897  return result;
898}
899
900// Record that the register class must generate a stack_or_reg_mask
901void ArchDesc::set_stack_or_reg(const char *reg_class_name) {
902  if( _register ) {
903    RegClass *reg_class  = _register->getRegClass(reg_class_name);
904    reg_class->_stack_or_reg = true;
905  }
906}
907
908
909// Return the type signature for the ideal operation
910const char *ArchDesc::getIdealType(const char *idealOp) {
911  // Find last character in idealOp, it specifies the type
912  char  last_char = 0;
913  const char *ptr = idealOp;
914  for (; *ptr != '\0'; ++ptr) {
915    last_char = *ptr;
916  }
917
918  // Match Vector types.
919  if (strncmp(idealOp, "Vec",3)==0) {
920    switch(last_char) {
921    case 'S':  return "TypeVect::VECTS";
922    case 'D':  return "TypeVect::VECTD";
923    case 'X':  return "TypeVect::VECTX";
924    case 'Y':  return "TypeVect::VECTY";
925    default:
926      internal_err("Vector type %s with unrecognized type\n",idealOp);
927    }
928  }
929
930  // !!!!!
931  switch(last_char) {
932  case 'I':    return "TypeInt::INT";
933  case 'P':    return "TypePtr::BOTTOM";
934  case 'N':    return "TypeNarrowOop::BOTTOM";
935  case 'F':    return "Type::FLOAT";
936  case 'D':    return "Type::DOUBLE";
937  case 'L':    return "TypeLong::LONG";
938  case 's':    return "TypeInt::CC /*flags*/";
939  default:
940    return NULL;
941    // !!!!!
942    // internal_err("Ideal type %s with unrecognized type\n",idealOp);
943    break;
944  }
945
946  return NULL;
947}
948
949
950
951OperandForm *ArchDesc::constructOperand(const char *ident,
952                                        bool  ideal_only) {
953  OperandForm *opForm = new OperandForm(ident, ideal_only);
954  _globalNames.Insert(ident, opForm);
955  addForm(opForm);
956
957  return opForm;
958}
959
960
961// Import predefined base types: Set = 1, RegI, RegP, ...
962void ArchDesc::initBaseOpTypes() {
963  // Create OperandForm and assign type for each opcode.
964  for (int i = 1; i < _last_machine_leaf; ++i) {
965    char        *ident   = (char *)NodeClassNames[i];
966    constructOperand(ident, true);
967  }
968  // Create InstructForm and assign type for each ideal instruction.
969  for ( int j = _last_machine_leaf+1; j < _last_opcode; ++j) {
970    char         *ident    = (char *)NodeClassNames[j];
971    if(!strcmp(ident, "ConI") || !strcmp(ident, "ConP") ||
972       !strcmp(ident, "ConN") || !strcmp(ident, "ConNKlass") ||
973       !strcmp(ident, "ConF") || !strcmp(ident, "ConD") ||
974       !strcmp(ident, "ConL") || !strcmp(ident, "Con" ) ||
975       !strcmp(ident, "Bool") ) {
976      constructOperand(ident, true);
977    }
978    else {
979      InstructForm *insForm  = new InstructForm(ident, true);
980      // insForm->_opcode       = nextUserOpType(ident);
981      _globalNames.Insert(ident,insForm);
982      addForm(insForm);
983    }
984  }
985
986  { OperandForm *opForm;
987  // Create operand type "Universe" for return instructions.
988  const char *ident = "Universe";
989  opForm = constructOperand(ident, false);
990
991  // Create operand type "label" for branch targets
992  ident = "label";
993  opForm = constructOperand(ident, false);
994
995  // !!!!! Update - when adding a new sReg/stackSlot type
996  // Create operand types "sReg[IPFDL]" for stack slot registers
997  opForm = constructOperand("sRegI", false);
998  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
999  opForm = constructOperand("sRegP", false);
1000  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1001  opForm = constructOperand("sRegF", false);
1002  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1003  opForm = constructOperand("sRegD", false);
1004  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1005  opForm = constructOperand("sRegL", false);
1006  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
1007
1008  // Create operand type "method" for call targets
1009  ident = "method";
1010  opForm = constructOperand(ident, false);
1011  }
1012
1013  // Create Effect Forms for each of the legal effects
1014  // USE, DEF, USE_DEF, KILL, USE_KILL
1015  {
1016    const char *ident = "USE";
1017    Effect     *eForm = new Effect(ident);
1018    _globalNames.Insert(ident, eForm);
1019    ident = "DEF";
1020    eForm = new Effect(ident);
1021    _globalNames.Insert(ident, eForm);
1022    ident = "USE_DEF";
1023    eForm = new Effect(ident);
1024    _globalNames.Insert(ident, eForm);
1025    ident = "KILL";
1026    eForm = new Effect(ident);
1027    _globalNames.Insert(ident, eForm);
1028    ident = "USE_KILL";
1029    eForm = new Effect(ident);
1030    _globalNames.Insert(ident, eForm);
1031    ident = "TEMP";
1032    eForm = new Effect(ident);
1033    _globalNames.Insert(ident, eForm);
1034    ident = "CALL";
1035    eForm = new Effect(ident);
1036    _globalNames.Insert(ident, eForm);
1037  }
1038
1039  //
1040  // Build mapping from ideal names to ideal indices
1041  int idealIndex = 0;
1042  for (idealIndex = 1; idealIndex < _last_machine_leaf; ++idealIndex) {
1043    const char *idealName = NodeClassNames[idealIndex];
1044    _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
1045  }
1046  for ( idealIndex = _last_machine_leaf+1;
1047        idealIndex < _last_opcode; ++idealIndex) {
1048    const char *idealName = NodeClassNames[idealIndex];
1049    _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
1050  }
1051
1052}
1053
1054
1055//---------------------------addSUNcopyright-------------------------------
1056// output SUN copyright info
1057void ArchDesc::addSunCopyright(char* legal, int size, FILE *fp) {
1058  size_t count = fwrite(legal, 1, size, fp);
1059  assert(count == (size_t) size, "copyright info truncated");
1060  fprintf(fp,"\n");
1061  fprintf(fp,"// Machine Generated File.  Do Not Edit!\n");
1062  fprintf(fp,"\n");
1063}
1064
1065
1066//---------------------------addIncludeGuardStart--------------------------
1067// output the start of an include guard.
1068void ArchDesc::addIncludeGuardStart(ADLFILE &adlfile, const char* guardString) {
1069  // Build #include lines
1070  fprintf(adlfile._fp, "\n");
1071  fprintf(adlfile._fp, "#ifndef %s\n", guardString);
1072  fprintf(adlfile._fp, "#define %s\n", guardString);
1073  fprintf(adlfile._fp, "\n");
1074
1075}
1076
1077//---------------------------addIncludeGuardEnd--------------------------
1078// output the end of an include guard.
1079void ArchDesc::addIncludeGuardEnd(ADLFILE &adlfile, const char* guardString) {
1080  // Build #include lines
1081  fprintf(adlfile._fp, "\n");
1082  fprintf(adlfile._fp, "#endif // %s\n", guardString);
1083
1084}
1085
1086//---------------------------addInclude--------------------------
1087// output the #include line for this file.
1088void ArchDesc::addInclude(ADLFILE &adlfile, const char* fileName) {
1089  fprintf(adlfile._fp, "#include \"%s\"\n", fileName);
1090
1091}
1092
1093void ArchDesc::addInclude(ADLFILE &adlfile, const char* includeDir, const char* fileName) {
1094  fprintf(adlfile._fp, "#include \"%s/%s\"\n", includeDir, fileName);
1095
1096}
1097
1098//---------------------------addPreprocessorChecks-----------------------------
1099// Output C preprocessor code to verify the backend compilation environment.
1100// The idea is to force code produced by "adlc -DHS64" to be compiled by a
1101// command of the form "CC ... -DHS64 ...", so that any #ifdefs in the source
1102// blocks select C code that is consistent with adlc's selections of AD code.
1103void ArchDesc::addPreprocessorChecks(FILE *fp) {
1104  const char* flag;
1105  _preproc_list.reset();
1106  if (_preproc_list.count() > 0 && !_preproc_list.current_is_signal()) {
1107    fprintf(fp, "// Check consistency of C++ compilation with ADLC options:\n");
1108  }
1109  for (_preproc_list.reset(); (flag = _preproc_list.iter()) != NULL; ) {
1110    if (_preproc_list.current_is_signal())  break;
1111    char* def = get_preproc_def(flag);
1112    fprintf(fp, "// Check adlc ");
1113    if (def)
1114          fprintf(fp, "-D%s=%s\n", flag, def);
1115    else  fprintf(fp, "-U%s\n", flag);
1116    fprintf(fp, "#%s %s\n",
1117            def ? "ifndef" : "ifdef", flag);
1118    fprintf(fp, "#  error \"%s %s be defined\"\n",
1119            flag, def ? "must" : "must not");
1120    fprintf(fp, "#endif // %s\n", flag);
1121  }
1122}
1123
1124
1125// Convert operand name into enum name
1126const char *ArchDesc::machOperEnum(const char *opName) {
1127  return ArchDesc::getMachOperEnum(opName);
1128}
1129
1130// Convert operand name into enum name
1131const char *ArchDesc::getMachOperEnum(const char *opName) {
1132  return (opName ? toUpper(opName) : opName);
1133}
1134
1135//---------------------------buildMustCloneMap-----------------------------
1136// Flag cases when machine needs cloned values or instructions
1137void ArchDesc::buildMustCloneMap(FILE *fp_hpp, FILE *fp_cpp) {
1138  // Build external declarations for mappings
1139  fprintf(fp_hpp, "// Mapping from machine-independent opcode to boolean\n");
1140  fprintf(fp_hpp, "// Flag cases where machine needs cloned values or instructions\n");
1141  fprintf(fp_hpp, "extern const char must_clone[];\n");
1142  fprintf(fp_hpp, "\n");
1143
1144  // Build mapping from ideal names to ideal indices
1145  fprintf(fp_cpp, "\n");
1146  fprintf(fp_cpp, "// Mapping from machine-independent opcode to boolean\n");
1147  fprintf(fp_cpp, "const        char must_clone[] = {\n");
1148  for (int idealIndex = 0; idealIndex < _last_opcode; ++idealIndex) {
1149    int         must_clone = 0;
1150    const char *idealName = NodeClassNames[idealIndex];
1151    // Previously selected constants for cloning
1152    // !!!!!
1153    // These are the current machine-dependent clones
1154    if ( strcmp(idealName,"CmpI") == 0
1155         || strcmp(idealName,"CmpU") == 0
1156         || strcmp(idealName,"CmpP") == 0
1157         || strcmp(idealName,"CmpN") == 0
1158         || strcmp(idealName,"CmpL") == 0
1159         || strcmp(idealName,"CmpD") == 0
1160         || strcmp(idealName,"CmpF") == 0
1161         || strcmp(idealName,"FastLock") == 0
1162         || strcmp(idealName,"FastUnlock") == 0
1163         || strcmp(idealName,"Bool") == 0
1164         || strcmp(idealName,"Binary") == 0 ) {
1165      // Removed ConI from the must_clone list.  CPUs that cannot use
1166      // large constants as immediates manifest the constant as an
1167      // instruction.  The must_clone flag prevents the constant from
1168      // floating up out of loops.
1169      must_clone = 1;
1170    }
1171    fprintf(fp_cpp, "  %d%s // %s: %d\n", must_clone,
1172      (idealIndex != (_last_opcode - 1)) ? "," : " // no trailing comma",
1173      idealName, idealIndex);
1174  }
1175  // Finish defining table
1176  fprintf(fp_cpp, "};\n");
1177}
1178