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