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