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