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