1 //
   2 // Copyright (c) 1997, 2010, 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 -----------------------------
  32 inline char  toUpper(char lower) {
  33   return (('a' <= lower && lower <= 'z') ? (lower + ('A'-'a')) : lower);
  34 }
  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 // Utilities to characterize effect statements
  47 static 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 
  55 static 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 
  64 static 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-------------------------------
  73 ChainList::ChainList() {
  74 }
  75 
  76 void 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 
  82 bool ChainList::search(const char *name) {
  83   return _name.search(name);
  84 }
  85 
  86 void ChainList::reset() {
  87   _name.reset();
  88   _cost.reset();
  89   _rule.reset();
  90 }
  91 
  92 bool 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 
 108 void ChainList::dump() {
 109   output(stderr);
 110 }
 111 
 112 void 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-------------------------------
 135 bool 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 
 156 void MatchList::dump() {
 157   output(stderr);
 158 }
 159 
 160 void MatchList::output(FILE *fp) {
 161   fprintf(fp, "\nMatchList output is Unimplemented();\n");
 162 }
 163 
 164 
 165 //---------------------------ArchDesc Constructor and Destructor-------------
 166 
 167 ArchDesc::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 
 226 ArchDesc::~ArchDesc() {
 227   // Clean-up and quit
 228 
 229 }
 230 
 231 //---------------------------ArchDesc methods: Public ----------------------
 232 // Store forms according to type
 233 void ArchDesc::addForm(PreHeaderForm *ptr) { _pre_header.addForm(ptr); };
 234 void ArchDesc::addForm(HeaderForm    *ptr) { _header.addForm(ptr); };
 235 void ArchDesc::addForm(SourceForm    *ptr) { _source.addForm(ptr); };
 236 void ArchDesc::addForm(EncodeForm    *ptr) { _encode = ptr; };
 237 void ArchDesc::addForm(InstructForm  *ptr) { _instructions.addForm(ptr); };
 238 void ArchDesc::addForm(MachNodeForm  *ptr) { _machnodes.addForm(ptr); };
 239 void ArchDesc::addForm(OperandForm   *ptr) { _operands.addForm(ptr); };
 240 void ArchDesc::addForm(OpClassForm   *ptr) { _opclass.addForm(ptr); };
 241 void ArchDesc::addForm(AttributeForm *ptr) { _attributes.addForm(ptr); };
 242 void ArchDesc::addForm(RegisterForm  *ptr) { _register = ptr; };
 243 void ArchDesc::addForm(FrameForm     *ptr) { _frame = ptr; };
 244 void ArchDesc::addForm(PipelineForm  *ptr) { _pipeline = ptr; };
 245 
 246 // Build MatchList array and construct MatchLists
 247 void ArchDesc::generateMatchLists() {
 248   // Call inspection routines to populate array
 249   inspectOperands();
 250   inspectInstructions();
 251 }
 252 
 253 // Build MatchList structures for operands
 254 void 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
 306 void 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 
 352 static int setsResult(MatchRule &mrule) {
 353   if (strcmp(mrule._name,"Set") == 0) return 1;
 354   return 0;
 355 }
 356 
 357 const 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
 373 const 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--------------------------------
 385 const 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-----------------------------------
 397 void 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--------------------------
 414 void 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-------------------------------
 431 void 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     {
 440       const Form *form = _globalNames[oper->_matrule->_opType];
 441       if ((form) && form->is_operand() &&
 442           (form->ideal_only() == false)) {
 443         add_chain_rule_entry(oper->_matrule->_opType, oper->cost(), oper->_ident);
 444       }
 445     }
 446     // Check for additional chain rules
 447     if (oper->_matrule->_next) {
 448       rule = oper->_matrule;
 449       do {
 450         rule = rule->_next;
 451         // Any extra match rules after the first must be chain rules
 452         const Form *form = _globalNames[rule->_opType];
 453         if ((form) && form->is_operand() &&
 454             (form->ideal_only() == false)) {
 455           add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
 456         }
 457       } while(rule->_next != NULL);
 458     }
 459   }
 460   else if ((oper->_matrule) && (oper->_matrule->_next)) {
 461     // Regardles of whether the first matchrule is a chain rule, check the list
 462     rule = oper->_matrule;
 463     do {
 464       rule = rule->_next;
 465       // Any extra match rules after the first must be chain rules
 466       const Form *form = _globalNames[rule->_opType];
 467       if ((form) && form->is_operand() &&
 468           (form->ideal_only() == false)) {
 469         assert( oper->cost(), "This case expects NULL cost, not default cost");
 470         add_chain_rule_entry(rule->_opType, oper->cost(), oper->_ident);
 471       }
 472     } while(rule->_next != NULL);
 473   }
 474 
 475 }
 476 
 477 //------------------------------buildMatchList---------------------------------
 478 // operands and instructions provide the result
 479 void ArchDesc::buildMatchList(MatchRule *mrule, const char *resultStr,
 480                               const char *rootOp, Predicate *pred,
 481                               const char *cost) {
 482   const char *leftstr, *rightstr;
 483   MatchNode  *mnode;
 484 
 485   leftstr = rightstr = NULL;
 486   // Check for chain rule, and do not generate a match list for it
 487   if ( mrule->is_chain_rule(_globalNames) ) {
 488     return;
 489   }
 490 
 491   // Identify index position among ideal operands
 492   intptr_t    index     = _last_opcode;
 493   const char  *indexStr  = getMatchListIndex(*mrule);
 494   index  = (intptr_t)_idealIndex[indexStr];
 495   if (index == 0) {
 496     fprintf(stderr, "Ideal node missing: %s\n", indexStr);
 497     assert(index != 0, "Failed lookup of ideal node\n");
 498   }
 499 
 500   // Check that this will be placed appropriately in the DFA
 501   if (index >= _last_opcode) {
 502     fprintf(stderr, "Invalid match rule %s <-- ( %s )\n",
 503             resultStr ? resultStr : " ",
 504             rootOp    ? rootOp    : " ");
 505     assert(index < _last_opcode, "Matching item not in ideal graph\n");
 506     return;
 507   }
 508 
 509 
 510   // Walk the MatchRule, generating MatchList entries for each level
 511   // of the rule (each nesting of parentheses)
 512   // Check for "Set"
 513   if (!strcmp(mrule->_opType, "Set")) {
 514     mnode = mrule->_rChild;
 515     buildMList(mnode, rootOp, resultStr, pred, cost);
 516     return;
 517   }
 518   // Build MatchLists for children
 519   // Check each child for an internal operand name, and use that name
 520   // for the parent's matchlist entry if it exists
 521   mnode = mrule->_lChild;
 522   if (mnode) {
 523     buildMList(mnode, NULL, NULL, NULL, NULL);
 524     leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 525   }
 526   mnode = mrule->_rChild;
 527   if (mnode) {
 528     buildMList(mnode, NULL, NULL, NULL, NULL);
 529     rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 530   }
 531   // Search for an identical matchlist entry already on the list
 532   if ((_mlistab[index] == NULL) ||
 533       (_mlistab[index] &&
 534        !_mlistab[index]->search(rootOp, resultStr, leftstr, rightstr, pred))) {
 535     // Place this match rule at front of list
 536     MatchList *mList =
 537       new MatchList(_mlistab[index], pred, cost,
 538                     rootOp, resultStr, leftstr, rightstr);
 539     _mlistab[index] = mList;
 540   }
 541 }
 542 
 543 // Recursive call for construction of match lists
 544 void ArchDesc::buildMList(MatchNode *node, const char *rootOp,
 545                           const char *resultOp, Predicate *pred,
 546                           const char *cost) {
 547   const char *leftstr, *rightstr;
 548   const char *resultop;
 549   const char *opcode;
 550   MatchNode  *mnode;
 551   Form       *form;
 552 
 553   leftstr = rightstr = NULL;
 554   // Do not process leaves of the Match Tree if they are not ideal
 555   if ((node) && (node->_lChild == NULL) && (node->_rChild == NULL) &&
 556       ((form = (Form *)_globalNames[node->_opType]) != NULL) &&
 557       (!form->ideal_only())) {
 558     return;
 559   }
 560 
 561   // Identify index position among ideal operands
 562   intptr_t    index     = _last_opcode;
 563   const char *indexStr  = node ? node->_opType : (char *) " ";
 564   index            = (intptr_t)_idealIndex[indexStr];
 565   if (index == 0) {
 566     fprintf(stderr, "error: operand \"%s\" not found\n", indexStr);
 567     assert(0, "fatal error");
 568   }
 569 
 570   // Build MatchLists for children
 571   // Check each child for an internal operand name, and use that name
 572   // for the parent's matchlist entry if it exists
 573   mnode = node->_lChild;
 574   if (mnode) {
 575     buildMList(mnode, NULL, NULL, NULL, NULL);
 576     leftstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 577   }
 578   mnode = node->_rChild;
 579   if (mnode) {
 580     buildMList(mnode, NULL, NULL, NULL, NULL);
 581     rightstr = mnode->_internalop ? mnode->_internalop : mnode->_opType;
 582   }
 583   // Grab the string for the opcode of this list entry
 584   if (rootOp == NULL) {
 585     opcode = (node->_internalop) ? node->_internalop : node->_opType;
 586   } else {
 587     opcode = rootOp;
 588   }
 589   // Grab the string for the result of this list entry
 590   if (resultOp == NULL) {
 591     resultop = (node->_internalop) ? node->_internalop : node->_opType;
 592   }
 593   else resultop = resultOp;
 594   // Search for an identical matchlist entry already on the list
 595   if ((_mlistab[index] == NULL) || (_mlistab[index] &&
 596                                     !_mlistab[index]->search(opcode, resultop, leftstr, rightstr, pred))) {
 597     // Place this match rule at front of list
 598     MatchList *mList =
 599       new MatchList(_mlistab[index],pred,cost,
 600                     opcode, resultop, leftstr, rightstr);
 601     _mlistab[index] = mList;
 602   }
 603 }
 604 
 605 // Count number of OperandForms defined
 606 int  ArchDesc::operandFormCount() {
 607   // Only interested in ones with non-NULL match rule
 608   int  count = 0; _operands.reset();
 609   OperandForm *cur;
 610   for( ; (cur = (OperandForm*)_operands.iter()) != NULL; ) {
 611     if (cur->_matrule != NULL) ++count;
 612   };
 613   return count;
 614 }
 615 
 616 // Count number of OpClassForms defined
 617 int  ArchDesc::opclassFormCount() {
 618   // Only interested in ones with non-NULL match rule
 619   int  count = 0; _operands.reset();
 620   OpClassForm *cur;
 621   for( ; (cur = (OpClassForm*)_opclass.iter()) != NULL; ) {
 622     ++count;
 623   };
 624   return count;
 625 }
 626 
 627 // Count number of InstructForms defined
 628 int  ArchDesc::instructFormCount() {
 629   // Only interested in ones with non-NULL match rule
 630   int  count = 0; _instructions.reset();
 631   InstructForm *cur;
 632   for( ; (cur = (InstructForm*)_instructions.iter()) != NULL; ) {
 633     if (cur->_matrule != NULL) ++count;
 634   };
 635   return count;
 636 }
 637 
 638 
 639 //------------------------------get_preproc_def--------------------------------
 640 // Return the textual binding for a given CPP flag name.
 641 // Return NULL if there is no binding, or it has been #undef-ed.
 642 char* ArchDesc::get_preproc_def(const char* flag) {
 643   SourceForm* deff = (SourceForm*) _preproc_table[flag];
 644   return (deff == NULL) ? NULL : deff->_code;
 645 }
 646 
 647 
 648 //------------------------------set_preproc_def--------------------------------
 649 // Change or create a textual binding for a given CPP flag name.
 650 // Giving NULL means the flag name is to be #undef-ed.
 651 // In any case, _preproc_list collects all names either #defined or #undef-ed.
 652 void ArchDesc::set_preproc_def(const char* flag, const char* def) {
 653   SourceForm* deff = (SourceForm*) _preproc_table[flag];
 654   if (deff == NULL) {
 655     deff = new SourceForm(NULL);
 656     _preproc_table.Insert(flag, deff);
 657     _preproc_list.addName(flag);   // this supports iteration
 658   }
 659   deff->_code = (char*) def;
 660 }
 661 
 662 
 663 bool ArchDesc::verify() {
 664 
 665   if (_register)
 666     assert( _register->verify(), "Register declarations failed verification");
 667   if (!_quiet_mode)
 668     fprintf(stderr,"\n");
 669   // fprintf(stderr,"---------------------------- Verify Operands ---------------\n");
 670   // _operands.verify();
 671   // fprintf(stderr,"\n");
 672   // fprintf(stderr,"---------------------------- Verify Operand Classes --------\n");
 673   // _opclass.verify();
 674   // fprintf(stderr,"\n");
 675   // fprintf(stderr,"---------------------------- Verify Attributes  ------------\n");
 676   // _attributes.verify();
 677   // fprintf(stderr,"\n");
 678   if (!_quiet_mode)
 679     fprintf(stderr,"---------------------------- Verify Instructions ----------------------------\n");
 680   _instructions.verify();
 681   if (!_quiet_mode)
 682     fprintf(stderr,"\n");
 683   // if ( _encode ) {
 684   //   fprintf(stderr,"---------------------------- Verify Encodings --------------\n");
 685   //   _encode->verify();
 686   // }
 687 
 688   //if (_pipeline) _pipeline->verify();
 689 
 690   return true;
 691 }
 692 
 693 
 694 void ArchDesc::dump() {
 695   _pre_header.dump();
 696   _header.dump();
 697   _source.dump();
 698   if (_register) _register->dump();
 699   fprintf(stderr,"\n");
 700   fprintf(stderr,"------------------ Dump Operands ---------------------\n");
 701   _operands.dump();
 702   fprintf(stderr,"\n");
 703   fprintf(stderr,"------------------ Dump Operand Classes --------------\n");
 704   _opclass.dump();
 705   fprintf(stderr,"\n");
 706   fprintf(stderr,"------------------ Dump Attributes  ------------------\n");
 707   _attributes.dump();
 708   fprintf(stderr,"\n");
 709   fprintf(stderr,"------------------ Dump Instructions -----------------\n");
 710   _instructions.dump();
 711   if ( _encode ) {
 712     fprintf(stderr,"------------------ Dump Encodings --------------------\n");
 713     _encode->dump();
 714   }
 715   if (_pipeline) _pipeline->dump();
 716 }
 717 
 718 
 719 //------------------------------init_keywords----------------------------------
 720 // Load the kewords into the global name table
 721 void ArchDesc::initKeywords(FormDict& names) {
 722   // Insert keyword strings into Global Name Table.  Keywords have a NULL value
 723   // field for quick easy identification when checking identifiers.
 724   names.Insert("instruct", NULL);
 725   names.Insert("operand", NULL);
 726   names.Insert("attribute", NULL);
 727   names.Insert("source", NULL);
 728   names.Insert("register", NULL);
 729   names.Insert("pipeline", NULL);
 730   names.Insert("constraint", NULL);
 731   names.Insert("predicate", NULL);
 732   names.Insert("encode", NULL);
 733   names.Insert("enc_class", NULL);
 734   names.Insert("interface", NULL);
 735   names.Insert("opcode", NULL);
 736   names.Insert("ins_encode", NULL);
 737   names.Insert("match", NULL);
 738   names.Insert("effect", NULL);
 739   names.Insert("expand", NULL);
 740   names.Insert("rewrite", NULL);
 741   names.Insert("reg_def", NULL);
 742   names.Insert("reg_class", NULL);
 743   names.Insert("alloc_class", NULL);
 744   names.Insert("resource", NULL);
 745   names.Insert("pipe_class", NULL);
 746   names.Insert("pipe_desc", NULL);
 747 }
 748 
 749 
 750 //------------------------------internal_err----------------------------------
 751 // Issue a parser error message, and skip to the end of the current line
 752 void ArchDesc::internal_err(const char *fmt, ...) {
 753   va_list args;
 754 
 755   va_start(args, fmt);
 756   _internal_errs += emit_msg(0, INTERNAL_ERR, 0, fmt, args);
 757   va_end(args);
 758 
 759   _no_output = 1;
 760 }
 761 
 762 //------------------------------syntax_err----------------------------------
 763 // Issue a parser error message, and skip to the end of the current line
 764 void ArchDesc::syntax_err(int lineno, const char *fmt, ...) {
 765   va_list args;
 766 
 767   va_start(args, fmt);
 768   _internal_errs += emit_msg(0, SYNERR, lineno, fmt, args);
 769   va_end(args);
 770 
 771   _no_output = 1;
 772 }
 773 
 774 //------------------------------emit_msg---------------------------------------
 775 // Emit a user message, typically a warning or error
 776 int ArchDesc::emit_msg(int quiet, int flag, int line, const char *fmt,
 777     va_list args) {
 778   static int  last_lineno = -1;
 779   int         i;
 780   const char *pref;
 781 
 782   switch(flag) {
 783   case 0: pref = "Warning: "; break;
 784   case 1: pref = "Syntax Error: "; break;
 785   case 2: pref = "Semantic Error: "; break;
 786   case 3: pref = "Internal Error: "; break;
 787   default: assert(0, ""); break;
 788   }
 789 
 790   if (line == last_lineno) return 0;
 791   last_lineno = line;
 792 
 793   if (!quiet) {                        /* no output if in quiet mode         */
 794     i = fprintf(errfile, "%s(%d) ", _ADL_file._name, line);
 795     while (i++ <= 15)  fputc(' ', errfile);
 796     fprintf(errfile, "%-8s:", pref);
 797     vfprintf(errfile, fmt, args);
 798     fprintf(errfile, "\n"); }
 799   return 1;
 800 }
 801 
 802 
 803 // ---------------------------------------------------------------------------
 804 //--------Utilities to build mappings for machine registers ------------------
 805 // ---------------------------------------------------------------------------
 806 
 807 // Construct the name of the register mask.
 808 static const char *getRegMask(const char *reg_class_name) {
 809   if( reg_class_name == NULL ) return "RegMask::Empty";
 810 
 811   if (strcmp(reg_class_name,"Universe")==0) {
 812     return "RegMask::Empty";
 813   } else if (strcmp(reg_class_name,"stack_slots")==0) {
 814     return "(Compile::current()->FIRST_STACK_mask())";
 815   } else {
 816     char       *rc_name = toUpper(reg_class_name);
 817     const char *mask    = "_mask";
 818     int         length  = (int)strlen(rc_name) + (int)strlen(mask) + 3;
 819     char       *regMask = new char[length];
 820     sprintf(regMask,"%s%s", rc_name, mask);
 821     return regMask;
 822   }
 823 }
 824 
 825 // Convert a register class name to its register mask.
 826 const char *ArchDesc::reg_class_to_reg_mask(const char *rc_name) {
 827   const char *reg_mask = "RegMask::Empty";
 828 
 829   if( _register ) {
 830     RegClass *reg_class  = _register->getRegClass(rc_name);
 831     if (reg_class == NULL) {
 832       syntax_err(0, "Use of an undefined register class %s", rc_name);
 833       return reg_mask;
 834     }
 835 
 836     // Construct the name of the register mask.
 837     reg_mask = getRegMask(rc_name);
 838   }
 839 
 840   return reg_mask;
 841 }
 842 
 843 
 844 // Obtain the name of the RegMask for an OperandForm
 845 const char *ArchDesc::reg_mask(OperandForm  &opForm) {
 846   const char *regMask      = "RegMask::Empty";
 847 
 848   // Check constraints on result's register class
 849   const char *result_class = opForm.constrained_reg_class();
 850   if (!result_class) opForm.dump();
 851   assert( result_class, "Resulting register class was not defined for operand");
 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
 858 const char *ArchDesc::reg_mask(InstructForm &inForm) {
 859   const char *result = inForm.reduce_result();
 860   assert( result,
 861           "Did not find result operand or RegMask for this instruction");
 862 
 863   // Instructions producing 'Universe' use RegMask::Empty
 864   if( strcmp(result,"Universe")==0 ) {
 865     return "RegMask::Empty";
 866   }
 867 
 868   // Lookup this result operand and get its register class
 869   Form *form = (Form*)_globalNames[result];
 870   assert( form, "Result operand must be defined");
 871   OperandForm *oper = form->is_operand();
 872   if (oper == NULL) form->dump();
 873   assert( oper, "Result must be an OperandForm");
 874   return reg_mask( *oper );
 875 }
 876 
 877 
 878 // Obtain the STACK_OR_reg_mask name for an OperandForm
 879 char *ArchDesc::stack_or_reg_mask(OperandForm  &opForm) {
 880   // name of cisc_spillable version
 881   const char *reg_mask_name = reg_mask(opForm);
 882   assert( reg_mask_name != NULL, "called with incorrect opForm");
 883 
 884   const char *stack_or = "STACK_OR_";
 885   int   length         = (int)strlen(stack_or) + (int)strlen(reg_mask_name) + 1;
 886   char *result         = new char[length];
 887   sprintf(result,"%s%s", stack_or, reg_mask_name);
 888 
 889   return result;
 890 }
 891 
 892 // Record that the register class must generate a stack_or_reg_mask
 893 void ArchDesc::set_stack_or_reg(const char *reg_class_name) {
 894   if( _register ) {
 895     RegClass *reg_class  = _register->getRegClass(reg_class_name);
 896     reg_class->_stack_or_reg = true;
 897   }
 898 }
 899 
 900 
 901 // Return the type signature for the ideal operation
 902 const char *ArchDesc::getIdealType(const char *idealOp) {
 903   // Find last character in idealOp, it specifies the type
 904   char  last_char = 0;
 905   const char *ptr = idealOp;
 906   for( ; *ptr != '\0'; ++ptr) {
 907     last_char = *ptr;
 908   }
 909 
 910   // !!!!!
 911   switch( last_char ) {
 912   case 'I':    return "TypeInt::INT";
 913   case 'P':    return "TypePtr::BOTTOM";
 914   case 'N':    return "TypeNarrowOop::BOTTOM";
 915   case 'F':    return "Type::FLOAT";
 916   case 'D':    return "Type::DOUBLE";
 917   case 'L':    return "TypeLong::LONG";
 918   case 's':    return "TypeInt::CC /*flags*/";
 919   default:
 920     return NULL;
 921     // !!!!!
 922     // internal_err("Ideal type %s with unrecognized type\n",idealOp);
 923     break;
 924   }
 925 
 926   return NULL;
 927 }
 928 
 929 
 930 
 931 OperandForm *ArchDesc::constructOperand(const char *ident,
 932                                         bool  ideal_only) {
 933   OperandForm *opForm = new OperandForm(ident, ideal_only);
 934   _globalNames.Insert(ident, opForm);
 935   addForm(opForm);
 936 
 937   return opForm;
 938 }
 939 
 940 
 941 // Import predefined base types: Set = 1, RegI, RegP, ...
 942 void ArchDesc::initBaseOpTypes() {
 943   // Create OperandForm and assign type for each opcode.
 944   for (int i = 1; i < _last_machine_leaf; ++i) {
 945     char        *ident   = (char *)NodeClassNames[i];
 946     constructOperand(ident, true);
 947   }
 948   // Create InstructForm and assign type for each ideal instruction.
 949   for ( int j = _last_machine_leaf+1; j < _last_opcode; ++j) {
 950     char         *ident    = (char *)NodeClassNames[j];
 951     if(!strcmp(ident, "ConI") || !strcmp(ident, "ConP") || !strcmp(ident, "ConN") ||
 952        !strcmp(ident, "ConF") || !strcmp(ident, "ConD") ||
 953        !strcmp(ident, "ConL") || !strcmp(ident, "Con" ) ||
 954        !strcmp(ident, "Bool") ) {
 955       constructOperand(ident, true);
 956     }
 957     else {
 958       InstructForm *insForm  = new InstructForm(ident, true);
 959       // insForm->_opcode       = nextUserOpType(ident);
 960       _globalNames.Insert(ident,insForm);
 961       addForm(insForm);
 962     }
 963   }
 964 
 965   { OperandForm *opForm;
 966   // Create operand type "Universe" for return instructions.
 967   const char *ident = "Universe";
 968   opForm = constructOperand(ident, false);
 969 
 970   // Create operand type "label" for branch targets
 971   ident = "label";
 972   opForm = constructOperand(ident, false);
 973 
 974   // !!!!! Update - when adding a new sReg/stackSlot type
 975   // Create operand types "sReg[IPFDL]" for stack slot registers
 976   opForm = constructOperand("sRegI", false);
 977   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
 978   opForm = constructOperand("sRegP", false);
 979   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
 980   opForm = constructOperand("sRegF", false);
 981   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
 982   opForm = constructOperand("sRegD", false);
 983   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
 984   opForm = constructOperand("sRegL", false);
 985   opForm->_constraint = new Constraint("ALLOC_IN_RC", "stack_slots");
 986 
 987   // Create operand type "method" for call targets
 988   ident = "method";
 989   opForm = constructOperand(ident, false);
 990   }
 991 
 992   // Create Effect Forms for each of the legal effects
 993   // USE, DEF, USE_DEF, KILL, USE_KILL
 994   {
 995     const char *ident = "USE";
 996     Effect     *eForm = new Effect(ident);
 997     _globalNames.Insert(ident, eForm);
 998     ident = "DEF";
 999     eForm = new Effect(ident);
1000     _globalNames.Insert(ident, eForm);
1001     ident = "USE_DEF";
1002     eForm = new Effect(ident);
1003     _globalNames.Insert(ident, eForm);
1004     ident = "KILL";
1005     eForm = new Effect(ident);
1006     _globalNames.Insert(ident, eForm);
1007     ident = "USE_KILL";
1008     eForm = new Effect(ident);
1009     _globalNames.Insert(ident, eForm);
1010     ident = "TEMP";
1011     eForm = new Effect(ident);
1012     _globalNames.Insert(ident, eForm);
1013   }
1014 
1015   //
1016   // Build mapping from ideal names to ideal indices
1017   int idealIndex = 0;
1018   for (idealIndex = 1; idealIndex < _last_machine_leaf; ++idealIndex) {
1019     const char *idealName = NodeClassNames[idealIndex];
1020     _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
1021   }
1022   for ( idealIndex = _last_machine_leaf+1;
1023         idealIndex < _last_opcode; ++idealIndex) {
1024     const char *idealName = NodeClassNames[idealIndex];
1025     _idealIndex.Insert((void*) idealName, (void*) (intptr_t) idealIndex);
1026   }
1027 
1028 }
1029 
1030 
1031 //---------------------------addSUNcopyright-------------------------------
1032 // output SUN copyright info
1033 void ArchDesc::addSunCopyright(char* legal, int size, FILE *fp) {
1034   size_t count = fwrite(legal, 1, size, fp);
1035   assert(count == (size_t) size, "copyright info truncated");
1036   fprintf(fp,"\n");
1037   fprintf(fp,"// Machine Generated File.  Do Not Edit!\n");
1038   fprintf(fp,"\n");
1039 }
1040 
1041 
1042 //---------------------------addIncludeGuardStart--------------------------
1043 // output the start of an include guard.
1044 void ArchDesc::addIncludeGuardStart(ADLFILE &adlfile, const char* guardString) {
1045   // Build #include lines
1046   fprintf(adlfile._fp, "\n");
1047   fprintf(adlfile._fp, "#ifndef %s\n", guardString);
1048   fprintf(adlfile._fp, "#define %s\n", guardString);
1049   fprintf(adlfile._fp, "\n");
1050 
1051 }
1052 
1053 //---------------------------addIncludeGuardEnd--------------------------
1054 // output the end of an include guard.
1055 void ArchDesc::addIncludeGuardEnd(ADLFILE &adlfile, const char* guardString) {
1056   // Build #include lines
1057   fprintf(adlfile._fp, "\n");
1058   fprintf(adlfile._fp, "#endif // %s\n", guardString);
1059 
1060 }
1061 
1062 //---------------------------addInclude--------------------------
1063 // output the #include line for this file.
1064 void ArchDesc::addInclude(ADLFILE &adlfile, const char* fileName) {
1065   fprintf(adlfile._fp, "#include \"%s\"\n", fileName);
1066 
1067 }
1068 
1069 void ArchDesc::addInclude(ADLFILE &adlfile, const char* includeDir, const char* fileName) {
1070   fprintf(adlfile._fp, "#include \"%s/%s\"\n", includeDir, fileName);
1071 
1072 }
1073 
1074 //---------------------------addPreprocessorChecks-----------------------------
1075 // Output C preprocessor code to verify the backend compilation environment.
1076 // The idea is to force code produced by "adlc -DHS64" to be compiled by a
1077 // command of the form "CC ... -DHS64 ...", so that any #ifdefs in the source
1078 // blocks select C code that is consistent with adlc's selections of AD code.
1079 void ArchDesc::addPreprocessorChecks(FILE *fp) {
1080   const char* flag;
1081   _preproc_list.reset();
1082   if (_preproc_list.count() > 0 && !_preproc_list.current_is_signal()) {
1083     fprintf(fp, "// Check consistency of C++ compilation with ADLC options:\n");
1084   }
1085   for (_preproc_list.reset(); (flag = _preproc_list.iter()) != NULL; ) {
1086     if (_preproc_list.current_is_signal())  break;
1087     char* def = get_preproc_def(flag);
1088     fprintf(fp, "// Check adlc ");
1089     if (def)
1090           fprintf(fp, "-D%s=%s\n", flag, def);
1091     else  fprintf(fp, "-U%s\n", flag);
1092     fprintf(fp, "#%s %s\n",
1093             def ? "ifndef" : "ifdef", flag);
1094     fprintf(fp, "#  error \"%s %s be defined\"\n",
1095             flag, def ? "must" : "must not");
1096     fprintf(fp, "#endif // %s\n", flag);
1097   }
1098 }
1099 
1100 
1101 // Convert operand name into enum name
1102 const char *ArchDesc::machOperEnum(const char *opName) {
1103   return ArchDesc::getMachOperEnum(opName);
1104 }
1105 
1106 // Convert operand name into enum name
1107 const char *ArchDesc::getMachOperEnum(const char *opName) {
1108   return (opName ? toUpper(opName) : opName);
1109 }
1110 
1111 //---------------------------buildMustCloneMap-----------------------------
1112 // Flag cases when machine needs cloned values or instructions
1113 void ArchDesc::buildMustCloneMap(FILE *fp_hpp, FILE *fp_cpp) {
1114   // Build external declarations for mappings
1115   fprintf(fp_hpp, "// Mapping from machine-independent opcode to boolean\n");
1116   fprintf(fp_hpp, "// Flag cases where machine needs cloned values or instructions\n");
1117   fprintf(fp_hpp, "extern const char must_clone[];\n");
1118   fprintf(fp_hpp, "\n");
1119 
1120   // Build mapping from ideal names to ideal indices
1121   fprintf(fp_cpp, "\n");
1122   fprintf(fp_cpp, "// Mapping from machine-independent opcode to boolean\n");
1123   fprintf(fp_cpp, "const        char must_clone[] = {\n");
1124   for (int idealIndex = 0; idealIndex < _last_opcode; ++idealIndex) {
1125     int         must_clone = 0;
1126     const char *idealName = NodeClassNames[idealIndex];
1127     // Previously selected constants for cloning
1128     // !!!!!
1129     // These are the current machine-dependent clones
1130     if ( strcmp(idealName,"CmpI") == 0
1131          || strcmp(idealName,"CmpU") == 0
1132          || strcmp(idealName,"CmpP") == 0
1133          || strcmp(idealName,"CmpN") == 0
1134          || strcmp(idealName,"CmpL") == 0
1135          || strcmp(idealName,"CmpD") == 0
1136          || strcmp(idealName,"CmpF") == 0
1137          || strcmp(idealName,"FastLock") == 0
1138          || strcmp(idealName,"FastUnlock") == 0
1139          || strcmp(idealName,"Bool") == 0
1140          || strcmp(idealName,"Binary") == 0 ) {
1141       // Removed ConI from the must_clone list.  CPUs that cannot use
1142       // large constants as immediates manifest the constant as an
1143       // instruction.  The must_clone flag prevents the constant from
1144       // floating up out of loops.
1145       must_clone = 1;
1146     }
1147     fprintf(fp_cpp, "  %d%s // %s: %d\n", must_clone,
1148       (idealIndex != (_last_opcode - 1)) ? "," : " // no trailing comma",
1149       idealName, idealIndex);
1150   }
1151   // Finish defining table
1152   fprintf(fp_cpp, "};\n");
1153 }