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