archDesc.cpp revision 196:d1605aabd0a1
1//
2// Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
3// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4//
5// This code is free software; you can redistribute it and/or modify it
6// under the terms of the GNU General Public License version 2 only, as
7// published by the Free Software Foundation.
8//
9// This code is distributed in the hope that it will be useful, but WITHOUT
10// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12// version 2 for more details (a copy is included in the LICENSE file that
13// accompanied this code).
14//
15// You should have received a copy of the GNU General Public License version
16// 2 along with this work; if not, write to the Free Software Foundation,
17// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18//
19// Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20// CA 95054 USA or visit www.sun.com if you need additional information or
21// have any questions.
22//
23//
24
25
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 ((prStr == predStr) || (prStr && predStr && !strcmp(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    = "dfa_i486.cpp";  _DFA_file._fp = NULL;
216      _HPP_file._name    = "ad_i486.hpp";   _HPP_file._fp = NULL;
217      _CPP_file._name    = "ad_i486.cpp";   _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    Attribute *attr = instr->_attribs;
335    while (attr != NULL) {
336      if (strcmp(attr->_ident,"ins_short_branch") == 0 &&
337          attr->int_val(*this) != 0) {
338        instr->set_short_branch(true);
339      } else if (strcmp(attr->_ident,"ins_alignment") == 0 &&
340          attr->int_val(*this) != 0) {
341        instr->set_alignment(attr->int_val(*this));
342      }
343      attr = (Attribute *)attr->_next;
344    }
345
346    if (!instr->is_short_branch()) {
347      buildMatchList(instr->_matrule, result, mrule._machType, pred, cost);
348    }
349  }
350}
351
352static int setsResult(MatchRule &mrule) {
353  if (strcmp(mrule._name,"Set") == 0) return 1;
354  return 0;
355}
356
357const char *ArchDesc::getMatchListIndex(MatchRule &mrule) {
358  if (setsResult(mrule)) {
359    // right child
360    return mrule._rChild->_opType;
361  } else {
362    // first entry
363    return mrule._opType;
364  }
365}
366
367
368//------------------------------result of reduction----------------------------
369
370
371//------------------------------left reduction---------------------------------
372// Return the left reduction associated with an internal name
373const char *ArchDesc::reduceLeft(char         *internalName) {
374  const char *left  = NULL;
375  MatchNode *mnode = (MatchNode*)_internalMatch[internalName];
376  if (mnode->_lChild) {
377    mnode = mnode->_lChild;
378    left = mnode->_internalop ? mnode->_internalop : mnode->_opType;
379  }
380  return left;
381}
382
383
384//------------------------------right reduction--------------------------------
385const char *ArchDesc::reduceRight(char  *internalName) {
386  const char *right  = NULL;
387  MatchNode *mnode = (MatchNode*)_internalMatch[internalName];
388  if (mnode->_rChild) {
389    mnode = mnode->_rChild;
390    right = mnode->_internalop ? mnode->_internalop : mnode->_opType;
391  }
392  return right;
393}
394
395
396//------------------------------check_optype-----------------------------------
397void ArchDesc::check_optype(MatchRule *mrule) {
398  MatchRule *rule = mrule;
399
400  //   !!!!!
401  //   // Cycle through the list of match rules
402  //   while(mrule) {
403  //     // Check for a filled in type field
404  //     if (mrule->_opType == NULL) {
405  //     const Form  *form    = operands[_result];
406  //     OpClassForm *opcForm = form ? form->is_opclass() : NULL;
407  //     assert(opcForm != NULL, "Match Rule contains invalid operand name.");
408  //     }
409  //     char *opType = opcForm->_ident;
410  //   }
411}
412
413//------------------------------add_chain_rule_entry--------------------------
414void ArchDesc::add_chain_rule_entry(const char *src, const char *cost,
415                                    const char *result) {
416  // Look-up the operation in chain rule table
417  ChainList *lst = (ChainList *)_chainRules[src];
418  if (lst == NULL) {
419    lst = new ChainList();
420    _chainRules.Insert(src, lst);
421  }
422  if (!lst->search(result)) {
423    if (cost == NULL) {
424      cost = ((AttributeForm*)_globalNames[AttributeForm::_op_cost])->_attrdef;
425    }
426    lst->insert(result, cost, result);
427  }
428}
429
430//------------------------------build_chain_rule-------------------------------
431void ArchDesc::build_chain_rule(OperandForm *oper) {
432  MatchRule     *rule;
433
434  // Check for chain rules here
435  // If this is only a chain rule
436  if ((oper->_matrule) && (oper->_matrule->_lChild == NULL) &&
437      (oper->_matrule->_rChild == NULL)) {
438
439    const Form *form = _globalNames[oper->_matrule->_opType];
440    if ((form) && form->is_operand() &&
441        (form->ideal_only() == false)) {
442      add_chain_rule_entry(oper->_matrule->_opType, oper->cost(), oper->_ident);
443    }
444    // Check for additional chain rules
445    if (oper->_matrule->_next) {
446      rule = oper->_matrule;
447      do {
448        rule = rule->_next;
449        // Any extra match rules after the first must be chain rules
450        const Form *form = _globalNames[rule->_opType];
451        if ((form) && form->is_operand() &&
452            (form->ideal_only() == false)) {
453          add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
454        }
455      } while(rule->_next != NULL);
456    }
457  }
458  else if ((oper->_matrule) && (oper->_matrule->_next)) {
459    // Regardles of whether the first matchrule is a chain rule, check the list
460    rule = oper->_matrule;
461    do {
462      rule = rule->_next;
463      // Any extra match rules after the first must be chain rules
464      const Form *form = _globalNames[rule->_opType];
465      if ((form) && form->is_operand() &&
466          (form->ideal_only() == false)) {
467        assert( oper->cost(), "This case expects NULL cost, not default cost");
468        add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
469      }
470    } while(rule->_next != NULL);
471  }
472
473}
474
475//------------------------------buildMatchList---------------------------------
476// operands and instructions provide the result
477void ArchDesc::buildMatchList(MatchRule *mrule, const char *resultStr,
478                              const char *rootOp, Predicate *pred,
479                              const char *cost) {
480  const char *leftstr, *rightstr;
481  MatchNode  *mnode;
482
483  leftstr = rightstr = NULL;
484  // Check for chain rule, and do not generate a match list for it
485  if ( mrule->is_chain_rule(_globalNames) ) {
486    return;
487  }
488
489  // Identify index position among ideal operands
490  intptr_t    index     = _last_opcode;
491  const char  *indexStr  = getMatchListIndex(*mrule);
492  index  = (intptr_t)_idealIndex[indexStr];
493  if (index == 0) {
494    fprintf(stderr, "Ideal node missing: %s\n", indexStr);
495    assert(index != 0, "Failed lookup of ideal node\n");
496  }
497
498  // Check that this will be placed appropriately in the DFA
499  if (index >= _last_opcode) {
500    fprintf(stderr, "Invalid match rule %s <-- ( %s )\n",
501            resultStr ? resultStr : " ",
502            rootOp    ? rootOp    : " ");
503    assert(index < _last_opcode, "Matching item not in ideal graph\n");
504    return;
505  }
506
507
508  // Walk the MatchRule, generating MatchList entries for each level
509  // of the rule (each nesting of parentheses)
510  // Check for "Set"
511  if (!strcmp(mrule->_opType, "Set")) {
512    mnode = mrule->_rChild;
513    buildMList(mnode, rootOp, resultStr, pred, cost);
514    return;
515  }
516  // Build MatchLists for children
517  // Check each child for an internal operand name, and use that name
518  // for the parent's matchlist entry if it exists
519  mnode = mrule->_lChild;
520  if (mnode) {
521    buildMList(mnode, NULL, NULL, NULL, NULL);
522    leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
523  }
524  mnode = mrule->_rChild;
525  if (mnode) {
526    buildMList(mnode, NULL, NULL, NULL, NULL);
527    rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
528  }
529  // Search for an identical matchlist entry already on the list
530  if ((_mlistab[index] == NULL) ||
531      (_mlistab[index] &&
532       !_mlistab[index]->search(rootOp, resultStr, leftstr, rightstr, pred))) {
533    // Place this match rule at front of list
534    MatchList *mList =
535      new MatchList(_mlistab[index], pred, cost,
536                    rootOp, resultStr, leftstr, rightstr);
537    _mlistab[index] = mList;
538  }
539}
540
541// Recursive call for construction of match lists
542void ArchDesc::buildMList(MatchNode *node, const char *rootOp,
543                          const char *resultOp, Predicate *pred,
544                          const char *cost) {
545  const char *leftstr, *rightstr;
546  const char *resultop;
547  const char *opcode;
548  MatchNode  *mnode;
549  Form       *form;
550
551  leftstr = rightstr = NULL;
552  // Do not process leaves of the Match Tree if they are not ideal
553  if ((node) && (node->_lChild == NULL) && (node->_rChild == NULL) &&
554      ((form = (Form *)_globalNames[node->_opType]) != NULL) &&
555      (!form->ideal_only())) {
556    return;
557  }
558
559  // Identify index position among ideal operands
560  intptr_t    index     = _last_opcode;
561  const char *indexStr  = node ? node->_opType : (char *) " ";
562  index            = (intptr_t)_idealIndex[indexStr];
563  if (index == 0) {
564    fprintf(stderr, "error: operand \"%s\" not found\n", indexStr);
565    assert(0, "fatal error");
566  }
567
568  // Build MatchLists for children
569  // Check each child for an internal operand name, and use that name
570  // for the parent's matchlist entry if it exists
571  mnode = node->_lChild;
572  if (mnode) {
573    buildMList(mnode, NULL, NULL, NULL, NULL);
574    leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
575  }
576  mnode = node->_rChild;
577  if (mnode) {
578    buildMList(mnode, NULL, NULL, NULL, NULL);
579    rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
580  }
581  // Grab the string for the opcode of this list entry
582  if (rootOp == NULL) {
583    opcode = (node->_internalop) ? node->_internalop : node->_opType;
584  } else {
585    opcode = rootOp;
586  }
587  // Grab the string for the result of this list entry
588  if (resultOp == NULL) {
589    resultop = (node->_internalop) ? node->_internalop : node->_opType;
590  }
591  else resultop = resultOp;
592  // Search for an identical matchlist entry already on the list
593  if ((_mlistab[index] == NULL) || (_mlistab[index] &&
594                                    !_mlistab[index]->search(opcode, resultop, leftstr, rightstr, pred))) {
595    // Place this match rule at front of list
596    MatchList *mList =
597      new MatchList(_mlistab[index],pred,cost,
598                    opcode, resultop, leftstr, rightstr);
599    _mlistab[index] = mList;
600  }
601}
602
603// Count number of OperandForms defined
604int  ArchDesc::operandFormCount() {
605  // Only interested in ones with non-NULL match rule
606  int  count = 0; _operands.reset();
607  OperandForm *cur;
608  for( ; (cur = (OperandForm*)_operands.iter()) != NULL; ) {
609    if (cur->_matrule != NULL) ++count;
610  };
611  return count;
612}
613
614// Count number of OpClassForms defined
615int  ArchDesc::opclassFormCount() {
616  // Only interested in ones with non-NULL match rule
617  int  count = 0; _operands.reset();
618  OpClassForm *cur;
619  for( ; (cur = (OpClassForm*)_opclass.iter()) != NULL; ) {
620    ++count;
621  };
622  return count;
623}
624
625// Count number of InstructForms defined
626int  ArchDesc::instructFormCount() {
627  // Only interested in ones with non-NULL match rule
628  int  count = 0; _instructions.reset();
629  InstructForm *cur;
630  for( ; (cur = (InstructForm*)_instructions.iter()) != NULL; ) {
631    if (cur->_matrule != NULL) ++count;
632  };
633  return count;
634}
635
636
637//------------------------------get_preproc_def--------------------------------
638// Return the textual binding for a given CPP flag name.
639// Return NULL if there is no binding, or it has been #undef-ed.
640char* ArchDesc::get_preproc_def(const char* flag) {
641  SourceForm* deff = (SourceForm*) _preproc_table[flag];
642  return (deff == NULL) ? NULL : deff->_code;
643}
644
645
646//------------------------------set_preproc_def--------------------------------
647// Change or create a textual binding for a given CPP flag name.
648// Giving NULL means the flag name is to be #undef-ed.
649// In any case, _preproc_list collects all names either #defined or #undef-ed.
650void ArchDesc::set_preproc_def(const char* flag, const char* def) {
651  SourceForm* deff = (SourceForm*) _preproc_table[flag];
652  if (deff == NULL) {
653    deff = new SourceForm(NULL);
654    _preproc_table.Insert(flag, deff);
655    _preproc_list.addName(flag);   // this supports iteration
656  }
657  deff->_code = (char*) def;
658}
659
660
661bool ArchDesc::verify() {
662
663  if (_register)
664    assert( _register->verify(), "Register declarations failed verification");
665  if (!_quiet_mode)
666    fprintf(stderr,"\n");
667  // fprintf(stderr,"---------------------------- Verify Operands ---------------\n");
668  // _operands.verify();
669  // fprintf(stderr,"\n");
670  // fprintf(stderr,"---------------------------- Verify Operand Classes --------\n");
671  // _opclass.verify();
672  // fprintf(stderr,"\n");
673  // fprintf(stderr,"---------------------------- Verify Attributes  ------------\n");
674  // _attributes.verify();
675  // fprintf(stderr,"\n");
676  if (!_quiet_mode)
677    fprintf(stderr,"---------------------------- Verify Instructions ----------------------------\n");
678  _instructions.verify();
679  if (!_quiet_mode)
680    fprintf(stderr,"\n");
681  // if ( _encode ) {
682  //   fprintf(stderr,"---------------------------- Verify Encodings --------------\n");
683  //   _encode->verify();
684  // }
685
686  //if (_pipeline) _pipeline->verify();
687
688  return true;
689}
690
691
692void ArchDesc::dump() {
693  _pre_header.dump();
694  _header.dump();
695  _source.dump();
696  if (_register) _register->dump();
697  fprintf(stderr,"\n");
698  fprintf(stderr,"------------------ Dump Operands ---------------------\n");
699  _operands.dump();
700  fprintf(stderr,"\n");
701  fprintf(stderr,"------------------ Dump Operand Classes --------------\n");
702  _opclass.dump();
703  fprintf(stderr,"\n");
704  fprintf(stderr,"------------------ Dump Attributes  ------------------\n");
705  _attributes.dump();
706  fprintf(stderr,"\n");
707  fprintf(stderr,"------------------ Dump Instructions -----------------\n");
708  _instructions.dump();
709  if ( _encode ) {
710    fprintf(stderr,"------------------ Dump Encodings --------------------\n");
711    _encode->dump();
712  }
713  if (_pipeline) _pipeline->dump();
714}
715
716
717//------------------------------init_keywords----------------------------------
718// Load the kewords into the global name table
719void ArchDesc::initKeywords(FormDict& names) {
720  // Insert keyword strings into Global Name Table.  Keywords have a NULL value
721  // field for quick easy identification when checking identifiers.
722  names.Insert("instruct", NULL);
723  names.Insert("operand", NULL);
724  names.Insert("attribute", NULL);
725  names.Insert("source", NULL);
726  names.Insert("register", NULL);
727  names.Insert("pipeline", NULL);
728  names.Insert("constraint", NULL);
729  names.Insert("predicate", NULL);
730  names.Insert("encode", NULL);
731  names.Insert("enc_class", NULL);
732  names.Insert("interface", NULL);
733  names.Insert("opcode", NULL);
734  names.Insert("ins_encode", NULL);
735  names.Insert("match", NULL);
736  names.Insert("effect", NULL);
737  names.Insert("expand", NULL);
738  names.Insert("rewrite", NULL);
739  names.Insert("reg_def", NULL);
740  names.Insert("reg_class", NULL);
741  names.Insert("alloc_class", NULL);
742  names.Insert("resource", NULL);
743  names.Insert("pipe_class", NULL);
744  names.Insert("pipe_desc", NULL);
745}
746
747
748//------------------------------internal_err----------------------------------
749// Issue a parser error message, and skip to the end of the current line
750void ArchDesc::internal_err(const char *fmt, ...) {
751  va_list args;
752
753  va_start(args, fmt);
754  _internal_errs += emit_msg(0, INTERNAL_ERR, 0, fmt, args);
755  va_end(args);
756
757  _no_output = 1;
758}
759
760//------------------------------syntax_err----------------------------------
761// Issue a parser error message, and skip to the end of the current line
762void ArchDesc::syntax_err(int lineno, const char *fmt, ...) {
763  va_list args;
764
765  va_start(args, fmt);
766  _internal_errs += emit_msg(0, SYNERR, lineno, fmt, args);
767  va_end(args);
768
769  _no_output = 1;
770}
771
772//------------------------------emit_msg---------------------------------------
773// Emit a user message, typically a warning or error
774int ArchDesc::emit_msg(int quiet, int flag, int line, const char *fmt,
775    va_list args) {
776  static int  last_lineno = -1;
777  int         i;
778  const char *pref;
779
780  switch(flag) {
781  case 0: pref = "Warning: "; break;
782  case 1: pref = "Syntax Error: "; break;
783  case 2: pref = "Semantic Error: "; break;
784  case 3: pref = "Internal Error: "; break;
785  default: assert(0, ""); break;
786  }
787
788  if (line == last_lineno) return 0;
789  last_lineno = line;
790
791  if (!quiet) {                        /* no output if in quiet mode         */
792    i = fprintf(errfile, "%s(%d) ", _ADL_file._name, line);
793    while (i++ <= 15)  fputc(' ', errfile);
794    fprintf(errfile, "%-8s:", pref);
795    vfprintf(errfile, fmt, args);
796    fprintf(errfile, "\n"); }
797  return 1;
798}
799
800
801// ---------------------------------------------------------------------------
802//--------Utilities to build mappings for machine registers ------------------
803// ---------------------------------------------------------------------------
804
805// Construct the name of the register mask.
806static const char *getRegMask(const char *reg_class_name) {
807  if( reg_class_name == NULL ) return "RegMask::Empty";
808
809  if (strcmp(reg_class_name,"Universe")==0) {
810    return "RegMask::Empty";
811  } else if (strcmp(reg_class_name,"stack_slots")==0) {
812    return "(Compile::current()->FIRST_STACK_mask())";
813  } else {
814    char       *rc_name = toUpper(reg_class_name);
815    const char *mask    = "_mask";
816    int         length  = (int)strlen(rc_name) + (int)strlen(mask) + 3;
817    char       *regMask = new char[length];
818    sprintf(regMask,"%s%s", rc_name, mask);
819    return regMask;
820  }
821}
822
823// Convert a register class name to its register mask.
824const char *ArchDesc::reg_class_to_reg_mask(const char *rc_name) {
825  const char *reg_mask = "RegMask::Empty";
826
827  if( _register ) {
828    RegClass *reg_class  = _register->getRegClass(rc_name);
829    if (reg_class == NULL) {
830      syntax_err(0, "Use of an undefined register class %s", rc_name);
831      return reg_mask;
832    }
833
834    // Construct the name of the register mask.
835    reg_mask = getRegMask(rc_name);
836  }
837
838  return reg_mask;
839}
840
841
842// Obtain the name of the RegMask for an OperandForm
843const char *ArchDesc::reg_mask(OperandForm  &opForm) {
844  const char *regMask      = "RegMask::Empty";
845
846  // Check constraints on result's register class
847  const char *result_class = opForm.constrained_reg_class();
848  if (!result_class) opForm.dump();
849  assert( result_class, "Resulting register class was not defined for operand");
850  regMask = reg_class_to_reg_mask( result_class );
851
852  return regMask;
853}
854
855// Obtain the name of the RegMask for an InstructForm
856const char *ArchDesc::reg_mask(InstructForm &inForm) {
857  const char *result = inForm.reduce_result();
858  assert( result,
859          "Did not find result operand or RegMask for this instruction");
860
861  // Instructions producing 'Universe' use RegMask::Empty
862  if( strcmp(result,"Universe")==0 ) {
863    return "RegMask::Empty";
864  }
865
866  // Lookup this result operand and get its register class
867  Form *form = (Form*)_globalNames[result];
868  assert( form, "Result operand must be defined");
869  OperandForm *oper = form->is_operand();
870  if (oper == NULL) form->dump();
871  assert( oper, "Result must be an OperandForm");
872  return reg_mask( *oper );
873}
874
875
876// Obtain the STACK_OR_reg_mask name for an OperandForm
877char *ArchDesc::stack_or_reg_mask(OperandForm  &opForm) {
878  // name of cisc_spillable version
879  const char *reg_mask_name = reg_mask(opForm);
880  assert( reg_mask_name != NULL, "called with incorrect opForm");
881
882  const char *stack_or = "STACK_OR_";
883  int   length         = (int)strlen(stack_or) + (int)strlen(reg_mask_name) + 1;
884  char *result         = new char[length];
885  sprintf(result,"%s%s", stack_or, reg_mask_name);
886
887  return result;
888}
889
890// Record that the register class must generate a stack_or_reg_mask
891void ArchDesc::set_stack_or_reg(const char *reg_class_name) {
892  if( _register ) {
893    RegClass *reg_class  = _register->getRegClass(reg_class_name);
894    reg_class->_stack_or_reg = true;
895  }
896}
897
898
899// Return the type signature for the ideal operation
900const char *ArchDesc::getIdealType(const char *idealOp) {
901  // Find last character in idealOp, it specifies the type
902  char  last_char = 0;
903  const char *ptr = idealOp;
904  for( ; *ptr != '\0'; ++ptr) {
905    last_char = *ptr;
906  }
907
908  // !!!!!
909  switch( last_char ) {
910  case 'I':    return "TypeInt::INT";
911  case 'P':    return "TypePtr::BOTTOM";
912  case 'N':    return "TypeNarrowOop::BOTTOM";
913  case 'F':    return "Type::FLOAT";
914  case 'D':    return "Type::DOUBLE";
915  case 'L':    return "TypeLong::LONG";
916  case 's':    return "TypeInt::CC /*flags*/";
917  default:
918    return NULL;
919    // !!!!!
920    // internal_err("Ideal type %s with unrecognized type\n",idealOp);
921    break;
922  }
923
924  return NULL;
925}
926
927
928
929OperandForm *ArchDesc::constructOperand(const char *ident,
930                                        bool  ideal_only) {
931  OperandForm *opForm = new OperandForm(ident, ideal_only);
932  _globalNames.Insert(ident, opForm);
933  addForm(opForm);
934
935  return opForm;
936}
937
938
939// Import predefined base types: Set = 1, RegI, RegP, ...
940void ArchDesc::initBaseOpTypes() {
941  // Create OperandForm and assign type for each opcode.
942  for (int i = 1; i < _last_machine_leaf; ++i) {
943    char        *ident   = (char *)NodeClassNames[i];
944    constructOperand(ident, true);
945  }
946  // Create InstructForm and assign type for each ideal instruction.
947  for ( int j = _last_machine_leaf+1; j < _last_opcode; ++j) {
948    char         *ident    = (char *)NodeClassNames[j];
949    if(!strcmp(ident, "ConI") || !strcmp(ident, "ConP") || !strcmp(ident, "ConN") ||
950       !strcmp(ident, "ConF") || !strcmp(ident, "ConD") ||
951       !strcmp(ident, "ConL") || !strcmp(ident, "Con" ) ||
952       !strcmp(ident, "Bool") ) {
953      constructOperand(ident, true);
954    }
955    else {
956      InstructForm *insForm  = new InstructForm(ident, true);
957      // insForm->_opcode       = nextUserOpType(ident);
958      _globalNames.Insert(ident,insForm);
959      addForm(insForm);
960    }
961  }
962
963  { OperandForm *opForm;
964  // Create operand type "Universe" for return instructions.
965  const char *ident = "Universe";
966  opForm = constructOperand(ident, false);
967
968  // Create operand type "label" for branch targets
969  ident = "label";
970  opForm = constructOperand(ident, false);
971
972  // !!!!! Update - when adding a new sReg/stackSlot type
973  // Create operand types "sReg[IPFDL]" for stack slot registers
974  opForm = constructOperand("sRegI", false);
975  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
976  opForm = constructOperand("sRegP", false);
977  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
978  opForm = constructOperand("sRegF", false);
979  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
980  opForm = constructOperand("sRegD", false);
981  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
982  opForm = constructOperand("sRegL", false);
983  opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
984
985  // Create operand type "method" for call targets
986  ident = "method";
987  opForm = constructOperand(ident, false);
988  }
989
990  // Create Effect Forms for each of the legal effects
991  // USE, DEF, USE_DEF, KILL, USE_KILL
992  {
993    const char *ident = "USE";
994    Effect     *eForm = new Effect(ident);
995    _globalNames.Insert(ident, eForm);
996    ident = "DEF";
997    eForm = new Effect(ident);
998    _globalNames.Insert(ident, eForm);
999    ident = "USE_DEF";
1000    eForm = new Effect(ident);
1001    _globalNames.Insert(ident, eForm);
1002    ident = "KILL";
1003    eForm = new Effect(ident);
1004    _globalNames.Insert(ident, eForm);
1005    ident = "USE_KILL";
1006    eForm = new Effect(ident);
1007    _globalNames.Insert(ident, eForm);
1008    ident = "TEMP";
1009    eForm = new Effect(ident);
1010    _globalNames.Insert(ident, eForm);
1011  }
1012
1013  //
1014  // Build mapping from ideal names to ideal indices
1015  int idealIndex = 0;
1016  for (idealIndex = 1; idealIndex < _last_machine_leaf; ++idealIndex) {
1017    const char *idealName = NodeClassNames[idealIndex];
1018    _idealIndex.Insert((void*)idealName, (void*)idealIndex);
1019  }
1020  for ( idealIndex = _last_machine_leaf+1;
1021        idealIndex < _last_opcode; ++idealIndex) {
1022    const char *idealName = NodeClassNames[idealIndex];
1023    _idealIndex.Insert((void*)idealName, (void*)idealIndex);
1024  }
1025
1026}
1027
1028
1029//---------------------------addSUNcopyright-------------------------------
1030// output SUN copyright info
1031void ArchDesc::addSunCopyright(char* legal, int size, FILE *fp) {
1032  fwrite(legal, size, 1, fp);
1033  fprintf(fp,"\n");
1034  fprintf(fp,"// Machine Generated File.  Do Not Edit!\n");
1035  fprintf(fp,"\n");
1036}
1037
1038//---------------------------machineDependentIncludes--------------------------
1039// output #include declarations for machine specific files
1040void ArchDesc::machineDependentIncludes(ADLFILE &adlfile) {
1041  const char *basename = adlfile._name;
1042  const char *cp;
1043  for (cp = basename; *cp; cp++)
1044    if (*cp == '/')  basename = cp+1;
1045
1046  // Build #include lines
1047  fprintf(adlfile._fp, "\n");
1048  fprintf(adlfile._fp, "#include \"incls/_precompiled.incl\"\n");
1049  fprintf(adlfile._fp, "#include \"incls/_%s.incl\"\n",basename);
1050  fprintf(adlfile._fp, "\n");
1051
1052}
1053
1054
1055//---------------------------addPreprocessorChecks-----------------------------
1056// Output C preprocessor code to verify the backend compilation environment.
1057// The idea is to force code produced by "adlc -DHS64" to be compiled by a
1058// command of the form "CC ... -DHS64 ...", so that any #ifdefs in the source
1059// blocks select C code that is consistent with adlc's selections of AD code.
1060void ArchDesc::addPreprocessorChecks(FILE *fp) {
1061  const char* flag;
1062  _preproc_list.reset();
1063  if (_preproc_list.count() > 0 && !_preproc_list.current_is_signal()) {
1064    fprintf(fp, "// Check consistency of C++ compilation with ADLC options:\n");
1065  }
1066  for (_preproc_list.reset(); (flag = _preproc_list.iter()) != NULL; ) {
1067    if (_preproc_list.current_is_signal())  break;
1068    char* def = get_preproc_def(flag);
1069    fprintf(fp, "// Check adlc ");
1070    if (def)
1071          fprintf(fp, "-D%s=%s\n", flag, def);
1072    else  fprintf(fp, "-U%s\n", flag);
1073    fprintf(fp, "#%s %s\n",
1074            def ? "ifndef" : "ifdef", flag);
1075    fprintf(fp, "#  error \"%s %s be defined\"\n",
1076            flag, def ? "must" : "must not");
1077    fprintf(fp, "#endif // %s\n", flag);
1078  }
1079}
1080
1081
1082// Convert operand name into enum name
1083const char *ArchDesc::machOperEnum(const char *opName) {
1084  return ArchDesc::getMachOperEnum(opName);
1085}
1086
1087// Convert operand name into enum name
1088const char *ArchDesc::getMachOperEnum(const char *opName) {
1089  return (opName ? toUpper(opName) : opName);
1090}
1091
1092//---------------------------buildMustCloneMap-----------------------------
1093// Flag cases when machine needs cloned values or instructions
1094void ArchDesc::buildMustCloneMap(FILE *fp_hpp, FILE *fp_cpp) {
1095  // Build external declarations for mappings
1096  fprintf(fp_hpp, "// Mapping from machine-independent opcode to boolean\n");
1097  fprintf(fp_hpp, "// Flag cases where machine needs cloned values or instructions\n");
1098  fprintf(fp_hpp, "extern const char must_clone[];\n");
1099  fprintf(fp_hpp, "\n");
1100
1101  // Build mapping from ideal names to ideal indices
1102  fprintf(fp_cpp, "\n");
1103  fprintf(fp_cpp, "// Mapping from machine-independent opcode to boolean\n");
1104  fprintf(fp_cpp, "const        char must_clone[] = {\n");
1105  for (int idealIndex = 0; idealIndex < _last_opcode; ++idealIndex) {
1106    int         must_clone = 0;
1107    const char *idealName = NodeClassNames[idealIndex];
1108    // Previously selected constants for cloning
1109    // !!!!!
1110    // These are the current machine-dependent clones
1111    if ( strcmp(idealName,"CmpI") == 0
1112         || strcmp(idealName,"CmpU") == 0
1113         || strcmp(idealName,"CmpP") == 0
1114         || strcmp(idealName,"CmpN") == 0
1115         || strcmp(idealName,"CmpL") == 0
1116         || strcmp(idealName,"CmpD") == 0
1117         || strcmp(idealName,"CmpF") == 0
1118         || strcmp(idealName,"FastLock") == 0
1119         || strcmp(idealName,"FastUnlock") == 0
1120         || strcmp(idealName,"Bool") == 0
1121         || strcmp(idealName,"Binary") == 0 ) {
1122      // Removed ConI from the must_clone list.  CPUs that cannot use
1123      // large constants as immediates manifest the constant as an
1124      // instruction.  The must_clone flag prevents the constant from
1125      // floating up out of loops.
1126      must_clone = 1;
1127    }
1128    fprintf(fp_cpp, "  %d%s // %s: %d\n", must_clone,
1129      (idealIndex != (_last_opcode - 1)) ? "," : " // no trailing comma",
1130      idealName, idealIndex);
1131  }
1132  // Finish defining table
1133  fprintf(fp_cpp, "};\n");
1134}
1135