adlparse.cpp 173.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
 *
 */

// ADLPARSE.CPP - Architecture Description Language Parser
// Authors: Chris Vick and Mike Paleczny
#include "adlc.hpp"

//----------------------------ADLParser----------------------------------------
// Create a new ADL parser
ADLParser::ADLParser(FileBuff& buffer, ArchDesc& archDesc)
  : _buf(buffer), _AD(archDesc),
    _globalNames(archDesc.globalNames()) {
  _AD._syntax_errs = _AD._semantic_errs = 0; // No errors so far this file
  _AD._warnings    = 0;                      // No warnings either
  _curline         = _ptr = NULL;            // No pointers into buffer yet

  _preproc_depth = 0;
  _preproc_not_taken = 0;

  // Delimit command-line definitions from in-file definitions:
  _AD._preproc_list.add_signal();
}

//------------------------------~ADLParser-------------------------------------
// Delete an ADL parser.
ADLParser::~ADLParser() {
  if (!_AD._quiet_mode)
    fprintf(stderr,"---------------------------- Errors and Warnings ----------------------------\n");
#ifndef ASSERT
  fprintf(stderr, "**************************************************************\n");
  fprintf(stderr, "***** WARNING: ASSERT is undefined, assertions disabled. *****\n");
  fprintf(stderr, "**************************************************************\n");
#endif
  if( _AD._syntax_errs + _AD._semantic_errs + _AD._warnings == 0 ) {
    if (!_AD._quiet_mode)
      fprintf(stderr,"No errors or warnings to report from phase-1 parse.\n" );
  }
  else {
    if( _AD._syntax_errs ) {      // Any syntax errors?
      fprintf(stderr,"%s:  Found %d syntax error", _buf._fp->_name, _AD._syntax_errs);
      if( _AD._syntax_errs > 1 ) fprintf(stderr,"s.\n\n");
      else fprintf(stderr,".\n\n");
    }
    if( _AD._semantic_errs ) {    // Any semantic errors?
      fprintf(stderr,"%s:  Found %d semantic error", _buf._fp->_name, _AD._semantic_errs);
      if( _AD._semantic_errs > 1 ) fprintf(stderr,"s.\n\n");
      else fprintf(stderr,".\n\n");
    }
    if( _AD._warnings ) {         // Any warnings?
      fprintf(stderr,"%s:  Found %d warning", _buf._fp->_name, _AD._warnings);
      if( _AD._warnings > 1 ) fprintf(stderr,"s.\n\n");
      else fprintf(stderr,".\n\n");
    }
  }
  if (!_AD._quiet_mode)
    fprintf(stderr,"-----------------------------------------------------------------------------\n");
78
  _AD._TotalLines += linenum()-1;     // -1 for overshoot in "nextline" routine
D
duke 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

  // Write out information we have stored
  // // UNIXism == fsync(stderr);
}

//------------------------------parse------------------------------------------
// Each top-level keyword should appear as the first non-whitespace on a line.
//
void ADLParser::parse() {
  char *ident;

  // Iterate over the lines in the file buffer parsing Level 1 objects
  for( next_line(); _curline != NULL; next_line()) {
    _ptr = _curline;             // Reset ptr to start of new line
    skipws();                    // Skip any leading whitespace
    ident = get_ident();         // Get first token
    if (ident == NULL) {         // Empty line
      continue;                  // Get the next line
    }
98
         if (!strcmp(ident, "instruct"))   instr_parse();
D
duke 已提交
99 100 101 102 103 104 105 106 107 108 109 110
    else if (!strcmp(ident, "operand"))    oper_parse();
    else if (!strcmp(ident, "opclass"))    opclass_parse();
    else if (!strcmp(ident, "ins_attrib")) ins_attr_parse();
    else if (!strcmp(ident, "op_attrib"))  op_attr_parse();
    else if (!strcmp(ident, "source"))     source_parse();
    else if (!strcmp(ident, "source_hpp")) source_hpp_parse();
    else if (!strcmp(ident, "register"))   reg_parse();
    else if (!strcmp(ident, "frame"))      frame_parse();
    else if (!strcmp(ident, "encode"))     encode_parse();
    else if (!strcmp(ident, "pipeline"))   pipe_parse();
    else if (!strcmp(ident, "definitions")) definitions_parse();
    else if (!strcmp(ident, "peephole"))   peep_parse();
111
    else if (!strcmp(ident, "#line"))      preproc_line();
D
duke 已提交
112 113 114 115 116 117
    else if (!strcmp(ident, "#define"))    preproc_define();
    else if (!strcmp(ident, "#undef"))     preproc_undef();
    else {
      parse_err(SYNERR, "expected one of - instruct, operand, ins_attrib, op_attrib, source, register, pipeline, encode\n     Found %s",ident);
    }
  }
118 119 120 121 122 123
  // Add reg_class spill_regs after parsing.
  RegisterForm *regBlock = _AD.get_registers();
  if (regBlock == NULL) {
    parse_err(SEMERR, "Did not declare 'register' definitions");
  }
  regBlock->addSpillRegClass();
D
duke 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

  // Done with parsing, check consistency.

  if (_preproc_depth != 0) {
    parse_err(SYNERR, "End of file inside #ifdef");
  }

  // AttributeForms ins_cost and op_cost must be defined for default behaviour
  if (_globalNames[AttributeForm::_ins_cost] == NULL) {
    parse_err(SEMERR, "Did not declare 'ins_cost' attribute");
  }
  if (_globalNames[AttributeForm::_op_cost] == NULL) {
    parse_err(SEMERR, "Did not declare 'op_cost' attribute");
  }
}

// ******************** Private Level 1 Parse Functions ********************
//------------------------------instr_parse------------------------------------
// Parse the contents of an instruction definition, build the InstructForm to
// represent that instruction, and add it to the InstructForm list.
void ADLParser::instr_parse(void) {
  char          *ident;
  InstructForm  *instr;
  MatchRule     *rule;
  int            match_rules_cnt = 0;

  // First get the name of the instruction
  if( (ident = get_unique_ident(_globalNames,"instruction")) == NULL )
    return;
  instr = new InstructForm(ident); // Create new instruction form
154
  instr->_linenum = linenum();
D
duke 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  _globalNames.Insert(ident, instr); // Add name to the name table
  // Debugging Stuff
  if (_AD._adl_debug > 1)
    fprintf(stderr,"Parsing Instruction Form %s\n", ident);

  // Then get the operands
  skipws();
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' in instruct definition\n");
  }
  // Parse the operand list
  else get_oplist(instr->_parameters, instr->_localNames);
  skipws();                        // Skip leading whitespace
  // Check for block delimiter
  if ( (_curchar != '%')
       || ( next_char(),  (_curchar != '{')) ) {
171
    parse_err(SYNERR, "missing '%%{' in instruction definition\n");
D
duke 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    return;
  }
  next_char();                     // Maintain the invariant
  do {
    ident = get_ident();           // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at %c\n", _curchar);
      continue;
    }
    if      (!strcmp(ident, "predicate")) instr->_predicate = pred_parse();
    else if      (!strcmp(ident, "match")) {
      // Allow one instruction have several match rules.
      rule = instr->_matrule;
      if (rule == NULL) {
        // This is first match rule encountered
        rule = match_parse(instr->_localNames);
        if (rule) {
          instr->_matrule = rule;
          // Special case the treatment of Control instructions.
          if( instr->is_ideal_control() ) {
            // Control instructions return a special result, 'Universe'
            rule->_result = "Universe";
          }
          // Check for commutative operations with tree operands.
          matchrule_clone_and_swap(rule, instr->_ident, match_rules_cnt);
        }
      } else {
        // Find the end of the match rule list
        while (rule->_next != NULL)
          rule = rule->_next;
        // Add the new match rule to the list
        rule->_next = match_parse(instr->_localNames);
        if (rule->_next) {
          rule = rule->_next;
          if( instr->is_ideal_control() ) {
            parse_err(SYNERR, "unique match rule expected for %s\n", rule->_name);
            return;
          }
          assert(match_rules_cnt < 100," too many match rule clones");
          char* buf = (char*) malloc(strlen(instr->_ident) + 4);
          sprintf(buf, "%s_%d", instr->_ident, match_rules_cnt++);
          rule->_result = buf;
          // Check for commutative operations with tree operands.
          matchrule_clone_and_swap(rule, instr->_ident, match_rules_cnt);
        }
      }
    }
    else if (!strcmp(ident, "encode"))  {
      parse_err(SYNERR, "Instructions specify ins_encode, not encode\n");
    }
222 223 224 225 226 227 228 229
    else if (!strcmp(ident, "ins_encode"))       ins_encode_parse(*instr);
    // Parse late expand keyword.
    else if (!strcmp(ident, "postalloc_expand")) postalloc_expand_parse(*instr);
    else if (!strcmp(ident, "opcode"))           instr->_opcode    = opcode_parse(instr);
    else if (!strcmp(ident, "size"))             instr->_size      = size_parse(instr);
    else if (!strcmp(ident, "effect"))           effect_parse(instr);
    else if (!strcmp(ident, "expand"))           instr->_exprule   = expand_parse(instr);
    else if (!strcmp(ident, "rewrite"))          instr->_rewrule   = rewrite_parse();
D
duke 已提交
230 231 232 233 234 235
    else if (!strcmp(ident, "constraint")) {
      parse_err(SYNERR, "Instructions do not specify a constraint\n");
    }
    else if (!strcmp(ident, "construct")) {
      parse_err(SYNERR, "Instructions do not specify a construct\n");
    }
236
    else if (!strcmp(ident, "format"))           instr->_format    = format_parse();
D
duke 已提交
237 238 239
    else if (!strcmp(ident, "interface")) {
      parse_err(SYNERR, "Instructions do not specify an interface\n");
    }
240
    else if (!strcmp(ident, "ins_pipe"))        ins_pipe_parse(*instr);
D
duke 已提交
241 242 243 244
    else {  // Done with staticly defined parts of instruction definition
      // Check identifier to see if it is the name of an attribute
      const Form    *form = _globalNames[ident];
      AttributeForm *attr = form ? form->is_attribute() : NULL;
245
      if (attr && (attr->_atype == INS_ATTR)) {
D
duke 已提交
246 247 248 249 250
        // Insert the new attribute into the linked list.
        Attribute *temp = attr_parse(ident);
        temp->_next = instr->_attribs;
        instr->_attribs = temp;
      } else {
251 252
        parse_err(SYNERR, "expected one of:\n predicate, match, encode, or the name of"
                  " an instruction attribute at %s\n", ident);
D
duke 已提交
253 254 255 256 257 258
      }
    }
    skipws();
  } while(_curchar != '%');
  next_char();
  if (_curchar != '}') {
259
    parse_err(SYNERR, "missing '%%}' in instruction definition\n");
D
duke 已提交
260 261 262 263
    return;
  }
  // Check for "Set" form of chain rule
  adjust_set_rule(instr);
264 265 266 267 268 269 270
  if (_AD._pipeline) {
    // No pipe required for late expand.
    if (instr->expands() || instr->postalloc_expands()) {
      if (instr->_ins_pipe) {
        parse_err(WARN, "ins_pipe and expand rule both specified for instruction \"%s\";"
                  " ins_pipe will be unused\n", instr->_ident);
      }
D
duke 已提交
271
    } else {
272
      if (!instr->_ins_pipe) {
D
duke 已提交
273
        parse_err(WARN, "No ins_pipe specified for instruction \"%s\"\n", instr->_ident);
274
      }
D
duke 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    }
  }
  // Add instruction to tail of instruction list
  _AD.addForm(instr);

  // Create instruction form for each additional match rule
  rule = instr->_matrule;
  if (rule != NULL) {
    rule = rule->_next;
    while (rule != NULL) {
      ident = (char*)rule->_result;
      InstructForm *clone = new InstructForm(ident, instr, rule); // Create new instruction form
      _globalNames.Insert(ident, clone); // Add name to the name table
      // Debugging Stuff
      if (_AD._adl_debug > 1)
        fprintf(stderr,"Parsing Instruction Form %s\n", ident);
      // Check for "Set" form of chain rule
      adjust_set_rule(clone);
      // Add instruction to tail of instruction list
      _AD.addForm(clone);
      rule = rule->_next;
      clone->_matrule->_next = NULL; // One match rule per clone
    }
  }
}

//------------------------------matchrule_clone_and_swap-----------------------
// Check for commutative operations with subtree operands,
// create clones and swap operands.
void ADLParser::matchrule_clone_and_swap(MatchRule* rule, const char* instr_ident, int& match_rules_cnt) {
  // Check for commutative operations with tree operands.
  int count = 0;
  rule->count_commutative_op(count);
  if (count > 0) {
    // Clone match rule and swap commutative operation's operands.
310
    rule->matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
D
duke 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  }
}

//------------------------------adjust_set_rule--------------------------------
// Check for "Set" form of chain rule
void ADLParser::adjust_set_rule(InstructForm *instr) {
  if (instr->_matrule == NULL || instr->_matrule->_rChild == NULL) return;
  const char *rch = instr->_matrule->_rChild->_opType;
  const Form *frm = _globalNames[rch];
  if( (! strcmp(instr->_matrule->_opType,"Set")) &&
      frm && frm->is_operand() && (! frm->ideal_only()) ) {
    // Previous implementation, which missed leaP*, but worked for loadCon*
    unsigned    position = 0;
    const char *result   = NULL;
    const char *name     = NULL;
    const char *optype   = NULL;
    MatchNode  *right    = instr->_matrule->_rChild;
    if (right->base_operand(position, _globalNames, result, name, optype)) {
      position = 1;
      const char *result2  = NULL;
      const char *name2    = NULL;
      const char *optype2  = NULL;
      // Can not have additional base operands in right side of match!
      if ( ! right->base_operand( position, _globalNames, result2, name2, optype2) ) {
335 336
        if (instr->_predicate != NULL)
          parse_err(SYNERR, "ADLC does not support instruction chain rules with predicates");
D
duke 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
        // Chain from input  _ideal_operand_type_,
        // Needed for shared roots of match-trees
        ChainList *lst = (ChainList *)_AD._chainRules[optype];
        if (lst == NULL) {
          lst = new ChainList();
          _AD._chainRules.Insert(optype, lst);
        }
        if (!lst->search(instr->_matrule->_lChild->_opType)) {
          const char *cost = instr->cost();
          if (cost == NULL) {
            cost = ((AttributeForm*)_globalNames[AttributeForm::_ins_cost])->_attrdef;
          }
          // The ADLC does not support chaining from the ideal operand type
          // of a predicated user-defined operand
          if( frm->is_operand() == NULL || frm->is_operand()->_predicate == NULL ) {
            lst->insert(instr->_matrule->_lChild->_opType,cost,instr->_ident);
          }
        }
        // Chain from input  _user_defined_operand_type_,
        lst = (ChainList *)_AD._chainRules[result];
        if (lst == NULL) {
          lst = new ChainList();
          _AD._chainRules.Insert(result, lst);
        }
        if (!lst->search(instr->_matrule->_lChild->_opType)) {
          const char *cost = instr->cost();
          if (cost == NULL) {
            cost = ((AttributeForm*)_globalNames[AttributeForm::_ins_cost])->_attrdef;
          }
          // It is safe to chain from the top-level user-defined operand even
          // if it has a predicate, since the predicate is checked before
          // the user-defined type is available.
          lst->insert(instr->_matrule->_lChild->_opType,cost,instr->_ident);
        }
      } else {
        // May have instruction chain rule if root of right-tree is an ideal
        OperandForm *rightOp = _globalNames[right->_opType]->is_operand();
        if( rightOp ) {
          const Form *rightRoot = _globalNames[rightOp->_matrule->_opType];
          if( rightRoot && rightRoot->ideal_only() ) {
            const char *chain_op = NULL;
            if( rightRoot->is_instruction() )
              chain_op = rightOp->_ident;
            if( chain_op ) {
              // Look-up the operation in chain rule table
              ChainList *lst = (ChainList *)_AD._chainRules[chain_op];
              if (lst == NULL) {
                lst = new ChainList();
                _AD._chainRules.Insert(chain_op, lst);
              }
              // if (!lst->search(instr->_matrule->_lChild->_opType)) {
              const char *cost = instr->cost();
              if (cost == NULL) {
                cost = ((AttributeForm*)_globalNames[AttributeForm::_ins_cost])->_attrdef;
              }
              // This chains from a top-level operand whose predicate, if any,
              // has been checked.
              lst->insert(instr->_matrule->_lChild->_opType,cost,instr->_ident);
              // }
            }
          }
        }
      } // end chain rule from right-tree's ideal root
    }
  }
}


//------------------------------oper_parse-------------------------------------
void ADLParser::oper_parse(void) {
  char          *ident;
  OperandForm   *oper;
  AttributeForm *attr;
  MatchRule     *rule;

  // First get the name of the operand
  skipws();
  if( (ident = get_unique_ident(_globalNames,"operand")) == NULL )
    return;
  oper = new OperandForm(ident);        // Create new operand form
417
  oper->_linenum = linenum();
D
duke 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
  _globalNames.Insert(ident, oper); // Add name to the name table

  // Debugging Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Parsing Operand Form %s\n", ident);

  // Get the component operands
  skipws();
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' in operand definition\n");
    return;
  }
  else get_oplist(oper->_parameters, oper->_localNames); // Parse the component operand list
  skipws();
  // Check for block delimiter
  if ((_curchar != '%') || (*(_ptr+1) != '{')) { // If not open block
433
    parse_err(SYNERR, "missing '%%{' in operand definition\n");
D
duke 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    return;
  }
  next_char(); next_char();        // Skip over "%{" symbol
  do {
    ident = get_ident();           // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at %c\n", _curchar);
      continue;
    }
    if      (!strcmp(ident, "predicate")) oper->_predicate = pred_parse();
    else if (!strcmp(ident, "match"))     {
      // Find the end of the match rule list
      rule = oper->_matrule;
      if (rule) {
        while (rule->_next) rule = rule->_next;
        // Add the new match rule to the list
        rule->_next = match_parse(oper->_localNames);
        if (rule->_next) {
          rule->_next->_result = oper->_ident;
        }
      }
      else {
        // This is first match rule encountered
        oper->_matrule = match_parse(oper->_localNames);
        if (oper->_matrule) {
          oper->_matrule->_result = oper->_ident;
        }
      }
    }
    else if (!strcmp(ident, "encode"))    oper->_interface = interface_parse();
    else if (!strcmp(ident, "ins_encode")) {
      parse_err(SYNERR, "Operands specify 'encode', not 'ins_encode'\n");
    }
    else if (!strcmp(ident, "opcode"))    {
      parse_err(SYNERR, "Operands do not specify an opcode\n");
    }
    else if (!strcmp(ident, "effect"))    {
      parse_err(SYNERR, "Operands do not specify an effect\n");
    }
    else if (!strcmp(ident, "expand"))    {
      parse_err(SYNERR, "Operands do not specify an expand\n");
    }
    else if (!strcmp(ident, "rewrite"))   {
      parse_err(SYNERR, "Operands do not specify a rewrite\n");
    }
    else if (!strcmp(ident, "constraint"))oper->_constraint= constraint_parse();
    else if (!strcmp(ident, "construct")) oper->_construct = construct_parse();
    else if (!strcmp(ident, "format"))    oper->_format    = format_parse();
    else if (!strcmp(ident, "interface")) oper->_interface = interface_parse();
    // Check identifier to see if it is the name of an attribute
    else if (((attr = _globalNames[ident]->is_attribute()) != NULL) &&
             (attr->_atype == OP_ATTR))   oper->_attribs   = attr_parse(ident);
    else {
      parse_err(SYNERR, "expected one of - constraint, predicate, match, encode, format, construct, or the name of a defined operand attribute at %s\n", ident);
    }
    skipws();
  } while(_curchar != '%');
  next_char();
  if (_curchar != '}') {
493
    parse_err(SYNERR, "missing '%%}' in operand definition\n");
D
duke 已提交
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    return;
  }
  // Add operand to tail of operand list
  _AD.addForm(oper);
}

//------------------------------opclass_parse----------------------------------
// Operand Classes are a block with a comma delimited list of operand names
void ADLParser::opclass_parse(void) {
  char          *ident;
  OpClassForm   *opc;
  OperandForm   *opForm;

  // First get the name of the operand class
  skipws();
  if( (ident = get_unique_ident(_globalNames,"opclass")) == NULL )
    return;
  opc = new OpClassForm(ident);             // Create new operand class form
  _globalNames.Insert(ident, opc);  // Add name to the name table

  // Debugging Stuff
  if (_AD._adl_debug > 1)
    fprintf(stderr,"Parsing Operand Class Form %s\n", ident);

  // Get the list of operands
  skipws();
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' in operand definition\n");
    return;
  }
  do {
    next_char();                            // Skip past open paren or comma
    ident = get_ident();                    // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at %c\n", _curchar);
      continue;
    }
    // Check identifier to see if it is the name of an operand
    const Form *form = _globalNames[ident];
    opForm     = form ? form->is_operand() : NULL;
    if ( opForm ) {
      opc->_oplst.addName(ident);           // Add operand to opclass list
      opForm->_classes.addName(opc->_ident);// Add opclass to operand list
    }
    else {
      parse_err(SYNERR, "expected name of a defined operand at %s\n", ident);
    }
    skipws();                               // skip trailing whitespace
  } while (_curchar == ',');                // Check for the comma
  // Check for closing ')'
  if (_curchar != ')') {
    parse_err(SYNERR, "missing ')' or ',' in opclass definition\n");
    return;
  }
  next_char();                              // Consume the ')'
  skipws();
  // Check for closing ';'
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in opclass definition\n");
    return;
  }
  next_char();                             // Consume the ';'
  // Add operand to tail of operand list
  _AD.addForm(opc);
}

//------------------------------ins_attr_parse---------------------------------
void ADLParser::ins_attr_parse(void) {
  char          *ident;
  char          *aexpr;
  AttributeForm *attrib;

  // get name for the instruction attribute
  skipws();                      // Skip leading whitespace
  if( (ident = get_unique_ident(_globalNames,"inst_attrib")) == NULL )
    return;
  // Debugging Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Parsing Ins_Attribute Form %s\n", ident);

  // Get default value of the instruction attribute
  skipws();                      // Skip whitespace
  if ((aexpr = get_paren_expr("attribute default expression string")) == NULL) {
    parse_err(SYNERR, "missing '(' in ins_attrib definition\n");
    return;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Attribute Expression: %s\n", aexpr);

  // Check for terminator
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in ins_attrib definition\n");
    return;
  }
  next_char();                    // Advance past the ';'

  // Construct the attribute, record global name, and store in ArchDesc
  attrib = new AttributeForm(ident, INS_ATTR, aexpr);
  _globalNames.Insert(ident, attrib);  // Add name to the name table
  _AD.addForm(attrib);
}

//------------------------------op_attr_parse----------------------------------
void ADLParser::op_attr_parse(void) {
  char          *ident;
  char          *aexpr;
  AttributeForm *attrib;

  // get name for the operand attribute
  skipws();                      // Skip leading whitespace
  if( (ident = get_unique_ident(_globalNames,"op_attrib")) == NULL )
    return;
  // Debugging Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Parsing Op_Attribute Form %s\n", ident);

  // Get default value of the instruction attribute
  skipws();                      // Skip whitespace
  if ((aexpr = get_paren_expr("attribute default expression string")) == NULL) {
    parse_err(SYNERR, "missing '(' in op_attrib definition\n");
    return;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Attribute Expression: %s\n", aexpr);

  // Check for terminator
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in op_attrib definition\n");
    return;
  }
  next_char();                    // Advance past the ';'

  // Construct the attribute, record global name, and store in ArchDesc
  attrib = new AttributeForm(ident, OP_ATTR, aexpr);
  _globalNames.Insert(ident, attrib);
  _AD.addForm(attrib);
}

//------------------------------definitions_parse-----------------------------------
void ADLParser::definitions_parse(void) {
  skipws();                       // Skip leading whitespace
  if (_curchar == '%' && *(_ptr+1) == '{') {
    next_char(); next_char();     // Skip "%{"
    skipws();
    while (_curchar != '%' && *(_ptr+1) != '}') {
      // Process each definition until finding closing string "%}"
      char *token = get_ident();
      if (token == NULL) {
        parse_err(SYNERR, "missing identifier inside definitions block.\n");
        return;
      }
      if (strcmp(token,"int_def")==0)     { int_def_parse(); }
      // if (strcmp(token,"str_def")==0)   { str_def_parse(); }
      skipws();
    }
  }
  else {
    parse_err(SYNERR, "Missing %%{ ... %%} block after definitions keyword.\n");
    return;
  }
}

//------------------------------int_def_parse----------------------------------
// Parse Example:
// int_def    MEMORY_REF_COST      (         200,  DEFAULT_COST * 2);
// <keyword>  <name>               ( <int_value>,   <description>  );
//
void ADLParser::int_def_parse(void) {
  char *name        = NULL;         // Name of definition
  char *value       = NULL;         // its value,
  int   int_value   = -1;           // positive values only
  char *description = NULL;         // textual description

  // Get definition name
  skipws();                      // Skip whitespace
  name = get_ident();
  if (name == NULL) {
    parse_err(SYNERR, "missing definition name after int_def\n");
    return;
  }

  // Check for value of int_def dname( integer_value [, string_expression ] )
  skipws();
  if (_curchar == '(') {

    // Parse the integer value.
    next_char();
    value = get_ident();
    if (value == NULL) {
      parse_err(SYNERR, "missing value in int_def\n");
      return;
    }
    if( !is_int_token(value, int_value) ) {
      parse_err(SYNERR, "value in int_def is not recognized as integer\n");
      return;
    }
    skipws();

    // Check for description
    if (_curchar == ',') {
      next_char();   // skip ','

      description = get_expr("int_def description", ")");
      if (description == NULL) {
        parse_err(SYNERR, "invalid or missing description in int_def\n");
        return;
      }
      trim(description);
    }

    if (_curchar != ')') {
      parse_err(SYNERR, "missing ')' in register definition statement\n");
      return;
    }
    next_char();
  }

  // Check for closing ';'
  skipws();
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' after int_def\n");
    return;
  }
  next_char();                   // move past ';'

  // Debug Stuff
  if (_AD._adl_debug > 1) {
    fprintf(stderr,"int_def: %s ( %s, %s )\n", name,
            (value), (description ? description : ""));
  }

  // Record new definition.
  Expr *expr     = new Expr(name, description, int_value, int_value);
  const Expr *old_expr = _AD.globalDefs().define(name, expr);
  if (old_expr != NULL) {
    parse_err(SYNERR, "Duplicate definition\n");
    return;
  }

  return;
}


//------------------------------source_parse-----------------------------------
void ADLParser::source_parse(void) {
  SourceForm *source;             // Encode class for instruction/operand
  char   *rule = NULL;            // String representation of encode rule

  skipws();                       // Skip leading whitespace
  if ( (rule = find_cpp_block("source block")) == NULL ) {
    parse_err(SYNERR, "incorrect or missing block for 'source'.\n");
    return;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Source Form: %s\n", rule);

  source = new SourceForm(rule);    // Build new Source object
  _AD.addForm(source);
  // skipws();
}

//------------------------------source_hpp_parse-------------------------------
// Parse a source_hpp %{ ... %} block.
// The code gets stuck into the ad_<arch>.hpp file.
// If the source_hpp block appears before the register block in the AD
// file, it goes up at the very top of the ad_<arch>.hpp file, so that
// it can be used by register encodings, etc.  Otherwise, it goes towards
// the bottom, where it's useful as a global definition to *.cpp files.
void ADLParser::source_hpp_parse(void) {
  char   *rule = NULL;            // String representation of encode rule

  skipws();                       // Skip leading whitespace
  if ( (rule = find_cpp_block("source_hpp block")) == NULL ) {
    parse_err(SYNERR, "incorrect or missing block for 'source_hpp'.\n");
    return;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Header Form: %s\n", rule);

  if (_AD.get_registers() == NULL) {
    // Very early in the file, before reg_defs, we collect pre-headers.
    PreHeaderForm* pre_header = new PreHeaderForm(rule);
    _AD.addForm(pre_header);
  } else {
    // Normally, we collect header info, placed at the bottom of the hpp file.
    HeaderForm* header = new HeaderForm(rule);
    _AD.addForm(header);
  }
}

//------------------------------reg_parse--------------------------------------
void ADLParser::reg_parse(void) {
784 785 786 787 788 789
  RegisterForm *regBlock = _AD.get_registers(); // Information about registers encoding
  if (regBlock == NULL) {
    // Create the RegisterForm for the architecture description.
    regBlock = new RegisterForm();    // Build new Source object
    _AD.addForm(regBlock);
  }
D
duke 已提交
790 791 792 793 794 795 796 797 798 799 800

  skipws();                       // Skip leading whitespace
  if (_curchar == '%' && *(_ptr+1) == '{') {
    next_char(); next_char();     // Skip "%{"
    skipws();
    while (_curchar != '%' && *(_ptr+1) != '}') {
      char *token = get_ident();
      if (token == NULL) {
        parse_err(SYNERR, "missing identifier inside register block.\n");
        return;
      }
801 802 803 804 805
      if (strcmp(token,"reg_def")==0)          { reg_def_parse(); }
      else if (strcmp(token,"reg_class")==0)   { reg_class_parse(); }
      else if (strcmp(token,"alloc_class")==0) { alloc_class_parse(); }
      else if (strcmp(token,"#define")==0)     { preproc_define(); }
      else { parse_err(SYNERR, "bad token %s inside register block.\n", token); break; }
D
duke 已提交
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
      skipws();
    }
  }
  else {
    parse_err(SYNERR, "Missing %c{ ... %c} block after register keyword.\n",'%','%');
    return;
  }
}

//------------------------------encode_parse-----------------------------------
void ADLParser::encode_parse(void) {
  EncodeForm *encBlock;         // Information about instruction/operand encoding

  _AD.getForm(&encBlock);
  if ( encBlock == NULL) {
    // Create the EncodeForm for the architecture description.
    encBlock = new EncodeForm();    // Build new Source object
    _AD.addForm(encBlock);
  }

  skipws();                       // Skip leading whitespace
  if (_curchar == '%' && *(_ptr+1) == '{') {
    next_char(); next_char();     // Skip "%{"
    skipws();
    while (_curchar != '%' && *(_ptr+1) != '}') {
      char *token = get_ident();
      if (token == NULL) {
            parse_err(SYNERR, "missing identifier inside encoding block.\n");
            return;
      }
      if (strcmp(token,"enc_class")==0)   { enc_class_parse(); }
      skipws();
    }
  }
  else {
    parse_err(SYNERR, "Missing %c{ ... %c} block after encode keyword.\n",'%','%');
    return;
  }
}

//------------------------------enc_class_parse--------------------------------
void ADLParser::enc_class_parse(void) {
  char       *ec_name;           // Name of encoding class being defined

  // Get encoding class name
  skipws();                      // Skip whitespace
  ec_name = get_ident();
  if (ec_name == NULL) {
    parse_err(SYNERR, "missing encoding class name after encode.\n");
    return;
  }

  EncClass  *encoding = _AD._encode->add_EncClass(ec_name);
859
  encoding->_linenum = linenum();
D
duke 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915

  skipws();                      // Skip leading whitespace
  // Check for optional parameter list
  if (_curchar == '(') {
    do {
      char *pType = NULL;        // parameter type
      char *pName = NULL;        // parameter name

      next_char();               // skip open paren & comma characters
      skipws();
      if (_curchar == ')') break;

      // Get parameter type
      pType = get_ident();
      if (pType == NULL) {
        parse_err(SYNERR, "parameter type expected at %c\n", _curchar);
        return;
      }

      skipws();
      // Get parameter name
      pName = get_ident();
      if (pName == NULL) {
        parse_err(SYNERR, "parameter name expected at %c\n", _curchar);
        return;
      }

      // Record parameter type and name
      encoding->add_parameter( pType, pName );

      skipws();
    } while(_curchar == ',');

    if (_curchar != ')') parse_err(SYNERR, "missing ')'\n");
    else {
      next_char();                  // Skip ')'
    }
  } // Done with parameter list

  skipws();
  // Check for block starting delimiters
  if ((_curchar != '%') || (*(_ptr+1) != '{')) { // If not open block
    parse_err(SYNERR, "missing '%c{' in enc_class definition\n", '%');
    return;
  }
  next_char();                      // Skip '%'
  next_char();                      // Skip '{'

  enc_class_parse_block(encoding, ec_name);
}


void ADLParser::enc_class_parse_block(EncClass* encoding, char* ec_name) {
  skipws_no_preproc();              // Skip leading whitespace
  // Prepend location descriptor, for debugging; cf. ADLParser::find_cpp_block
  if (_AD._adlocation_debug) {
916
    encoding->add_code(get_line_string());
D
duke 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
  }

  // Collect the parts of the encode description
  // (1) strings that are passed through to output
  // (2) replacement/substitution variable, preceeded by a '$'
  while ( (_curchar != '%') && (*(_ptr+1) != '}') ) {

    // (1)
    // Check if there is a string to pass through to output
    char *start = _ptr;       // Record start of the next string
    while ((_curchar != '$') && ((_curchar != '%') || (*(_ptr+1) != '}')) ) {
      // If at the start of a comment, skip past it
      if( (_curchar == '/') && ((*(_ptr+1) == '/') || (*(_ptr+1) == '*')) ) {
        skipws_no_preproc();
      } else {
        // ELSE advance to the next character, or start of the next line
        next_char_or_line();
      }
    }
    // If a string was found, terminate it and record in EncClass
    if ( start != _ptr ) {
      *_ptr  = '\0';          // Terminate the string
      encoding->add_code(start);
    }

    // (2)
    // If we are at a replacement variable,
    // copy it and record in EncClass
945
    if (_curchar == '$') {
D
duke 已提交
946
      // Found replacement Variable
947
      char* rep_var = get_rep_var_ident_dup();
D
duke 已提交
948 949 950 951 952 953 954 955 956
      // Add flag to _strings list indicating we should check _rep_vars
      encoding->add_rep_var(rep_var);
    }
  } // end while part of format description
  next_char();                      // Skip '%'
  next_char();                      // Skip '}'

  skipws();

957 958 959 960
  if (_AD._adlocation_debug) {
    encoding->add_code(end_line_marker());
  }

D
duke 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"EncodingClass Form: %s\n", ec_name);
}

//------------------------------frame_parse-----------------------------------
void ADLParser::frame_parse(void) {
  FrameForm  *frame;              // Information about stack-frame layout
  char       *desc = NULL;        // String representation of frame

  skipws();                       // Skip leading whitespace

  frame = new FrameForm();        // Build new Frame object
  // Check for open block sequence
  skipws();                       // Skip leading whitespace
  if (_curchar == '%' && *(_ptr+1) == '{') {
    next_char(); next_char();     // Skip "%{"
    skipws();
    while (_curchar != '%' && *(_ptr+1) != '}') {
      char *token = get_ident();
      if (token == NULL) {
            parse_err(SYNERR, "missing identifier inside frame block.\n");
            return;
      }
      if (strcmp(token,"stack_direction")==0) {
        stack_dir_parse(frame);
      }
      if (strcmp(token,"sync_stack_slots")==0) {
        sync_stack_slots_parse(frame);
      }
      if (strcmp(token,"frame_pointer")==0) {
        frame_pointer_parse(frame, false);
      }
      if (strcmp(token,"interpreter_frame_pointer")==0) {
        interpreter_frame_pointer_parse(frame, false);
      }
      if (strcmp(token,"inline_cache_reg")==0) {
        inline_cache_parse(frame, false);
      }
      if (strcmp(token,"compiler_method_oop_reg")==0) {
        parse_err(WARN, "Using obsolete Token, compiler_method_oop_reg");
        skipws();
      }
      if (strcmp(token,"interpreter_method_oop_reg")==0) {
        interpreter_method_oop_parse(frame, false);
      }
      if (strcmp(token,"cisc_spilling_operand_name")==0) {
        cisc_spilling_operand_name_parse(frame, false);
      }
      if (strcmp(token,"stack_alignment")==0) {
        stack_alignment_parse(frame);
      }
      if (strcmp(token,"return_addr")==0) {
        return_addr_parse(frame, false);
      }
      if (strcmp(token,"in_preserve_stack_slots")==0) {
        preserve_stack_parse(frame);
      }
      if (strcmp(token,"out_preserve_stack_slots")==0) {
        parse_err(WARN, "Using obsolete token, out_preserve_stack_slots");
        skipws();
      }
      if (strcmp(token,"varargs_C_out_slots_killed")==0) {
        frame->_varargs_C_out_slots_killed = parse_one_arg("varargs C out slots killed");
      }
      if (strcmp(token,"calling_convention")==0) {
        frame->_calling_convention = calling_convention_parse();
      }
      if (strcmp(token,"return_value")==0) {
        frame->_return_value = return_value_parse();
      }
      if (strcmp(token,"c_frame_pointer")==0) {
        frame_pointer_parse(frame, true);
      }
      if (strcmp(token,"c_return_addr")==0) {
        return_addr_parse(frame, true);
      }
      if (strcmp(token,"c_calling_convention")==0) {
        frame->_c_calling_convention = calling_convention_parse();
      }
      if (strcmp(token,"c_return_value")==0) {
        frame->_c_return_value = return_value_parse();
      }

      skipws();
    }
  }
  else {
    parse_err(SYNERR, "Missing %c{ ... %c} block after encode keyword.\n",'%','%');
    return;
  }
  // All Java versions are required, native versions are optional
  if(frame->_frame_pointer == NULL) {
    parse_err(SYNERR, "missing frame pointer definition in frame section.\n");
    return;
  }
  // !!!!! !!!!!
  // if(frame->_interpreter_frame_ptr_reg == NULL) {
  //   parse_err(SYNERR, "missing interpreter frame pointer definition in frame section.\n");
  //   return;
  // }
  if(frame->_alignment == NULL) {
    parse_err(SYNERR, "missing alignment definition in frame section.\n");
    return;
  }
  if(frame->_return_addr == NULL) {
    parse_err(SYNERR, "missing return address location in frame section.\n");
    return;
  }
  if(frame->_in_preserve_slots == NULL) {
    parse_err(SYNERR, "missing stack slot preservation definition in frame section.\n");
    return;
  }
  if(frame->_varargs_C_out_slots_killed == NULL) {
    parse_err(SYNERR, "missing varargs C out slots killed definition in frame section.\n");
    return;
  }
  if(frame->_calling_convention == NULL) {
    parse_err(SYNERR, "missing calling convention definition in frame section.\n");
    return;
  }
  if(frame->_return_value == NULL) {
    parse_err(SYNERR, "missing return value definition in frame section.\n");
    return;
  }
  // Fill natives in identically with the Java versions if not present.
  if(frame->_c_frame_pointer == NULL) {
    frame->_c_frame_pointer = frame->_frame_pointer;
  }
  if(frame->_c_return_addr == NULL) {
    frame->_c_return_addr = frame->_return_addr;
    frame->_c_return_addr_loc = frame->_return_addr_loc;
  }
  if(frame->_c_calling_convention == NULL) {
    frame->_c_calling_convention = frame->_calling_convention;
  }
  if(frame->_c_return_value == NULL) {
    frame->_c_return_value = frame->_return_value;
  }

  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Frame Form: %s\n", desc);

  // Create the EncodeForm for the architecture description.
  _AD.addForm(frame);
  // skipws();
}

//------------------------------stack_dir_parse--------------------------------
void ADLParser::stack_dir_parse(FrameForm *frame) {
  char *direction = parse_one_arg("stack direction entry");
  if (strcmp(direction, "TOWARDS_LOW") == 0) {
    frame->_direction = false;
  }
  else if (strcmp(direction, "TOWARDS_HIGH") == 0) {
    frame->_direction = true;
  }
  else {
    parse_err(SYNERR, "invalid value inside stack direction entry.\n");
    return;
  }
}

//------------------------------sync_stack_slots_parse-------------------------
void ADLParser::sync_stack_slots_parse(FrameForm *frame) {
    // Assign value into frame form
    frame->_sync_stack_slots = parse_one_arg("sync stack slots entry");
}

//------------------------------frame_pointer_parse----------------------------
void ADLParser::frame_pointer_parse(FrameForm *frame, bool native) {
  char *frame_pointer = parse_one_arg("frame pointer entry");
  // Assign value into frame form
  if (native) { frame->_c_frame_pointer = frame_pointer; }
  else        { frame->_frame_pointer   = frame_pointer; }
}

//------------------------------interpreter_frame_pointer_parse----------------------------
void ADLParser::interpreter_frame_pointer_parse(FrameForm *frame, bool native) {
  frame->_interpreter_frame_pointer_reg = parse_one_arg("interpreter frame pointer entry");
}

//------------------------------inline_cache_parse-----------------------------
void ADLParser::inline_cache_parse(FrameForm *frame, bool native) {
  frame->_inline_cache_reg = parse_one_arg("inline cache reg entry");
}

//------------------------------interpreter_method_oop_parse------------------
void ADLParser::interpreter_method_oop_parse(FrameForm *frame, bool native) {
  frame->_interpreter_method_oop_reg = parse_one_arg("method oop reg entry");
}

//------------------------------cisc_spilling_operand_parse---------------------
void ADLParser::cisc_spilling_operand_name_parse(FrameForm *frame, bool native) {
  frame->_cisc_spilling_operand_name = parse_one_arg("cisc spilling operand name");
}

//------------------------------stack_alignment_parse--------------------------
void ADLParser::stack_alignment_parse(FrameForm *frame) {
  char *alignment = parse_one_arg("stack alignment entry");
  // Assign value into frame
  frame->_alignment   = alignment;
}

//------------------------------parse_one_arg-------------------------------
char *ADLParser::parse_one_arg(const char *description) {
  char *token = NULL;
  if(_curchar == '(') {
    next_char();
    skipws();
    token = get_expr(description, ")");
    if (token == NULL) {
      parse_err(SYNERR, "missing value inside %s.\n", description);
      return NULL;
    }
    next_char();           // skip the close paren
    if(_curchar != ';') {  // check for semi-colon
      parse_err(SYNERR, "missing %c in.\n", ';', description);
      return NULL;
    }
    next_char();           // skip the semi-colon
  }
  else {
    parse_err(SYNERR, "Missing %c in.\n", '(', description);
    return NULL;
  }

  trim(token);
  return token;
}

//------------------------------return_addr_parse------------------------------
void ADLParser::return_addr_parse(FrameForm *frame, bool native) {
  bool in_register  = true;
  if(_curchar == '(') {
    next_char();
    skipws();
    char *token = get_ident();
    if (token == NULL) {
      parse_err(SYNERR, "missing value inside return address entry.\n");
      return;
    }
    // check for valid values for stack/register
    if (strcmp(token, "REG") == 0) {
      in_register = true;
    }
    else if (strcmp(token, "STACK") == 0) {
      in_register = false;
    }
    else {
      parse_err(SYNERR, "invalid value inside return_address entry.\n");
      return;
    }
    if (native) { frame->_c_return_addr_loc = in_register; }
    else        { frame->_return_addr_loc   = in_register; }

    // Parse expression that specifies register or stack position
    skipws();
    char *token2 = get_expr("return address entry", ")");
    if (token2 == NULL) {
      parse_err(SYNERR, "missing value inside return address entry.\n");
      return;
    }
    next_char();           // skip the close paren
    if (native) { frame->_c_return_addr = token2; }
    else        { frame->_return_addr   = token2; }

    if(_curchar != ';') {  // check for semi-colon
      parse_err(SYNERR, "missing %c in return address entry.\n", ';');
      return;
    }
    next_char();           // skip the semi-colon
  }
  else {
    parse_err(SYNERR, "Missing %c in return_address entry.\n", '(');
  }
}

//------------------------------preserve_stack_parse---------------------------
void ADLParser::preserve_stack_parse(FrameForm *frame) {
  if(_curchar == '(') {
    char *token = get_paren_expr("preserve_stack_slots");
    frame->_in_preserve_slots   = token;

    if(_curchar != ';') {  // check for semi-colon
      parse_err(SYNERR, "missing %c in preserve stack slot entry.\n", ';');
      return;
    }
    next_char();           // skip the semi-colon
  }
  else {
    parse_err(SYNERR, "Missing %c in preserve stack slot entry.\n", '(');
  }
}

//------------------------------calling_convention_parse-----------------------
char *ADLParser::calling_convention_parse() {
  char   *desc = NULL;          // String representation of calling_convention

  skipws();                     // Skip leading whitespace
  if ( (desc = find_cpp_block("calling convention block")) == NULL ) {
    parse_err(SYNERR, "incorrect or missing block for 'calling_convention'.\n");
  }
  return desc;
}

//------------------------------return_value_parse-----------------------------
char *ADLParser::return_value_parse() {
  char   *desc = NULL;          // String representation of calling_convention

  skipws();                     // Skip leading whitespace
  if ( (desc = find_cpp_block("return value block")) == NULL ) {
    parse_err(SYNERR, "incorrect or missing block for 'return_value'.\n");
  }
  return desc;
}

//------------------------------ins_pipe_parse---------------------------------
void ADLParser::ins_pipe_parse(InstructForm &instr) {
  char * ident;

  skipws();
  if ( _curchar != '(' ) {       // Check for delimiter
    parse_err(SYNERR, "missing \"(\" in ins_pipe definition\n");
    return;
  }

  next_char();
  ident = get_ident();           // Grab next identifier

  if (ident == NULL) {
    parse_err(SYNERR, "keyword identifier expected at %c\n", _curchar);
    return;
  }

  skipws();
  if ( _curchar != ')' ) {       // Check for delimiter
    parse_err(SYNERR, "missing \")\" in ins_pipe definition\n");
    return;
  }

  next_char();                   // skip the close paren
  if(_curchar != ';') {          // check for semi-colon
    parse_err(SYNERR, "missing %c in return value entry.\n", ';');
    return;
  }
  next_char();                   // skip the semi-colon

  // Check ident for validity
  if (_AD._pipeline && !_AD._pipeline->_classlist.search(ident)) {
    parse_err(SYNERR, "\"%s\" is not a valid pipeline class\n", ident);
    return;
  }

  // Add this instruction to the list in the pipeline class
  _AD._pipeline->_classdict[ident]->is_pipeclass()->_instructs.addName(instr._ident);

  // Set the name of the pipeline class in the instruction
  instr._ins_pipe = ident;
  return;
}

//------------------------------pipe_parse-------------------------------------
void ADLParser::pipe_parse(void) {
  PipelineForm *pipeline;         // Encode class for instruction/operand
  char * ident;

  pipeline = new PipelineForm();  // Build new Source object
  _AD.addForm(pipeline);

  skipws();                       // Skip leading whitespace
  // Check for block delimiter
  if ( (_curchar != '%')
       || ( next_char(),  (_curchar != '{')) ) {
1334
    parse_err(SYNERR, "missing '%%{' in pipeline definition\n");
D
duke 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    return;
  }
  next_char();                     // Maintain the invariant
  do {
    ident = get_ident();           // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at %c\n", _curchar);
      continue;
    }
    if      (!strcmp(ident, "resources" )) resource_parse(*pipeline);
    else if (!strcmp(ident, "pipe_desc" )) pipe_desc_parse(*pipeline);
    else if (!strcmp(ident, "pipe_class")) pipe_class_parse(*pipeline);
    else if (!strcmp(ident, "define")) {
      skipws();
      if ( (_curchar != '%')
           || ( next_char(),  (_curchar != '{')) ) {
1351
        parse_err(SYNERR, "expected '%%{'\n");
D
duke 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
        return;
      }
      next_char(); skipws();

      char *node_class = get_ident();
      if (node_class == NULL) {
        parse_err(SYNERR, "expected identifier, found \"%c\"\n", _curchar);
        return;
      }

      skipws();
      if (_curchar != ',' && _curchar != '=') {
        parse_err(SYNERR, "expected `=`, found '%c'\n", _curchar);
        break;
      }
      next_char(); skipws();

      char *pipe_class = get_ident();
      if (pipe_class == NULL) {
        parse_err(SYNERR, "expected identifier, found \"%c\"\n", _curchar);
        return;
      }
      if (_curchar != ';' ) {
        parse_err(SYNERR, "expected `;`, found '%c'\n", _curchar);
        break;
      }
      next_char();              // Skip over semi-colon

      skipws();
      if ( (_curchar != '%')
           || ( next_char(),  (_curchar != '}')) ) {
        parse_err(SYNERR, "expected '%%}', found \"%c\"\n", _curchar);
      }
      next_char();

      // Check ident for validity
      if (_AD._pipeline && !_AD._pipeline->_classlist.search(pipe_class)) {
        parse_err(SYNERR, "\"%s\" is not a valid pipeline class\n", pipe_class);
        return;
      }

      // Add this machine node to the list in the pipeline class
      _AD._pipeline->_classdict[pipe_class]->is_pipeclass()->_instructs.addName(node_class);

      MachNodeForm *machnode = new MachNodeForm(node_class); // Create new machnode form
      machnode->_machnode_pipe = pipe_class;

      _AD.addForm(machnode);
    }
    else if (!strcmp(ident, "attributes")) {
K
kvn 已提交
1402
      bool vsi_seen = false;
D
duke 已提交
1403 1404 1405 1406

      skipws();
      if ( (_curchar != '%')
           || ( next_char(),  (_curchar != '{')) ) {
1407
        parse_err(SYNERR, "expected '%%{'\n");
D
duke 已提交
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
        return;
      }
      next_char(); skipws();

      while (_curchar != '%') {
        ident = get_ident();
        if (ident == NULL)
          break;

        if (!strcmp(ident, "variable_size_instructions")) {
          skipws();
          if (_curchar == ';') {
            next_char(); skipws();
          }

          pipeline->_variableSizeInstrs = true;
          vsi_seen = true;
          continue;
        }

        if (!strcmp(ident, "fixed_size_instructions")) {
          skipws();
          if (_curchar == ';') {
            next_char(); skipws();
          }

          pipeline->_variableSizeInstrs = false;
          vsi_seen = true;
          continue;
        }

        if (!strcmp(ident, "branch_has_delay_slot")) {
          skipws();
          if (_curchar == ';') {
            next_char(); skipws();
          }

          pipeline->_branchHasDelaySlot = true;
          continue;
        }

        if (!strcmp(ident, "max_instructions_per_bundle")) {
          skipws();
          if (_curchar != '=') {
            parse_err(SYNERR, "expected `=`\n");
            break;
            }

          next_char(); skipws();
          pipeline->_maxInstrsPerBundle = get_int();
          skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        if (!strcmp(ident, "max_bundles_per_cycle")) {
          skipws();
          if (_curchar != '=') {
            parse_err(SYNERR, "expected `=`\n");
            break;
            }

          next_char(); skipws();
          pipeline->_maxBundlesPerCycle = get_int();
          skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        if (!strcmp(ident, "instruction_unit_size")) {
          skipws();
          if (_curchar != '=') {
            parse_err(SYNERR, "expected `=`, found '%c'\n", _curchar);
            break;
            }

          next_char(); skipws();
          pipeline->_instrUnitSize = get_int();
          skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        if (!strcmp(ident, "bundle_unit_size")) {
          skipws();
          if (_curchar != '=') {
            parse_err(SYNERR, "expected `=`, found '%c'\n", _curchar);
            break;
            }

          next_char(); skipws();
          pipeline->_bundleUnitSize = get_int();
          skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        if (!strcmp(ident, "instruction_fetch_unit_size")) {
          skipws();
          if (_curchar != '=') {
            parse_err(SYNERR, "expected `=`, found '%c'\n", _curchar);
            break;
            }

          next_char(); skipws();
          pipeline->_instrFetchUnitSize = get_int();
          skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        if (!strcmp(ident, "instruction_fetch_units")) {
          skipws();
          if (_curchar != '=') {
            parse_err(SYNERR, "expected `=`, found '%c'\n", _curchar);
            break;
            }

          next_char(); skipws();
          pipeline->_instrFetchUnits = get_int();
          skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        if (!strcmp(ident, "nops")) {
          skipws();
          if (_curchar != '(') {
            parse_err(SYNERR, "expected `(`, found '%c'\n", _curchar);
            break;
            }

          next_char(); skipws();

          while (_curchar != ')') {
            ident = get_ident();
            if (ident == NULL) {
              parse_err(SYNERR, "expected identifier for nop instruction, found '%c'\n", _curchar);
              break;
            }

            pipeline->_noplist.addName(ident);
            pipeline->_nopcnt++;
            skipws();

            if (_curchar == ',') {
              next_char(); skipws();
            }
          }

          next_char(); skipws();

          if (_curchar == ';') {
            next_char(); skipws();
          }

          continue;
        }

        parse_err(SYNERR, "unknown specifier \"%s\"\n", ident);
      }

      if ( (_curchar != '%')
           || ( next_char(),  (_curchar != '}')) ) {
1596
        parse_err(SYNERR, "expected '%%}', found \"%c\"\n", _curchar);
D
duke 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
      }
      next_char(); skipws();

      if (pipeline->_maxInstrsPerBundle == 0)
        parse_err(SYNERR, "\"max_instructions_per_bundle\" unspecified\n");
      if (pipeline->_instrUnitSize == 0 && pipeline->_bundleUnitSize == 0)
        parse_err(SYNERR, "\"instruction_unit_size\" and \"bundle_unit_size\" unspecified\n");
      if (pipeline->_instrFetchUnitSize == 0)
        parse_err(SYNERR, "\"instruction_fetch_unit_size\" unspecified\n");
      if (pipeline->_instrFetchUnits == 0)
        parse_err(SYNERR, "\"instruction_fetch_units\" unspecified\n");
      if (!vsi_seen)
        parse_err(SYNERR, "\"variable_size_instruction\" or \"fixed_size_instruction\" unspecified\n");
    }
    else {  // Done with staticly defined parts of instruction definition
      parse_err(SYNERR, "expected one of \"resources\", \"pipe_desc\", \"pipe_class\", found \"%s\"\n", ident);
      return;
    }
    skipws();
    if (_curchar == ';')
      skipws();
  } while(_curchar != '%');

  next_char();
  if (_curchar != '}') {
1622
    parse_err(SYNERR, "missing \"%%}\" in pipeline definition\n");
D
duke 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
    return;
  }

  next_char();
}

//------------------------------resource_parse----------------------------
void ADLParser::resource_parse(PipelineForm &pipeline) {
  ResourceForm *resource;
  char * ident;
  char * expr;
  unsigned mask;
  pipeline._rescount = 0;

  skipws();                       // Skip leading whitespace

  if (_curchar != '(') {
    parse_err(SYNERR, "missing \"(\" in resource definition\n");
    return;
  }

  do {
    next_char();                   // Skip "(" or ","
    ident = get_ident();           // Grab next identifier

K
kvn 已提交
1648 1649 1650 1651 1652 1653
    if (_AD._adl_debug > 1) {
      if (ident != NULL) {
        fprintf(stderr, "resource_parse: identifier: %s\n", ident);
      }
    }

D
duke 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at \"%c\"\n", _curchar);
      return;
    }
    skipws();

    if (_curchar != '=') {
      mask = (1 << pipeline._rescount++);
    }
    else {
      next_char(); skipws();
      expr = get_ident();          // Grab next identifier
      if (expr == NULL) {
        parse_err(SYNERR, "keyword identifier expected at \"%c\"\n", _curchar);
        return;
      }
      resource = (ResourceForm *) pipeline._resdict[expr];
      if (resource == NULL) {
        parse_err(SYNERR, "resource \"%s\" is not defined\n", expr);
        return;
      }
      mask = resource->mask();

      skipws();
      while (_curchar == '|') {
        next_char(); skipws();

        expr = get_ident();          // Grab next identifier
        if (expr == NULL) {
          parse_err(SYNERR, "keyword identifier expected at \"%c\"\n", _curchar);
          return;
        }

        resource = (ResourceForm *) pipeline._resdict[expr];   // Look up the value
        if (resource == NULL) {
          parse_err(SYNERR, "resource \"%s\" is not defined\n", expr);
          return;
        }

        mask |= resource->mask();
        skipws();
      }
    }

    resource = new ResourceForm(mask);

    pipeline._resdict.Insert(ident, resource);
    pipeline._reslist.addName(ident);
  } while (_curchar == ',');

  if (_curchar != ')') {
      parse_err(SYNERR, "\")\" expected at \"%c\"\n", _curchar);
      return;
  }

  next_char();                 // Skip ")"
  if (_curchar == ';')
    next_char();               // Skip ";"
}

//------------------------------resource_parse----------------------------
void ADLParser::pipe_desc_parse(PipelineForm &pipeline) {
  char * ident;

  skipws();                       // Skip leading whitespace

  if (_curchar != '(') {
    parse_err(SYNERR, "missing \"(\" in pipe_desc definition\n");
    return;
  }

  do {
    next_char();                   // Skip "(" or ","
    ident = get_ident();           // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at \"%c\"\n", _curchar);
      return;
    }

    // Add the name to the list
    pipeline._stages.addName(ident);
    pipeline._stagecnt++;

    skipws();
  } while (_curchar == ',');

  if (_curchar != ')') {
      parse_err(SYNERR, "\")\" expected at \"%c\"\n", _curchar);
      return;
  }

  next_char();                     // Skip ")"
  if (_curchar == ';')
    next_char();                   // Skip ";"
}

//------------------------------pipe_class_parse--------------------------
void ADLParser::pipe_class_parse(PipelineForm &pipeline) {
  PipeClassForm *pipe_class;
  char * ident;
  char * stage;
  char * read_or_write;
  int is_write;
  int is_read;
  OperandForm  *oper;

  skipws();                       // Skip leading whitespace

  ident = get_ident();            // Grab next identifier

  if (ident == NULL) {
    parse_err(SYNERR, "keyword identifier expected at \"%c\"\n", _curchar);
    return;
  }

  // Create a record for the pipe_class
  pipe_class = new PipeClassForm(ident, ++pipeline._classcnt);
  pipeline._classdict.Insert(ident, pipe_class);
  pipeline._classlist.addName(ident);

  // Then get the operands
  skipws();
  if (_curchar != '(') {
    parse_err(SYNERR, "missing \"(\" in pipe_class definition\n");
  }
  // Parse the operand list
  else get_oplist(pipe_class->_parameters, pipe_class->_localNames);
  skipws();                        // Skip leading whitespace
  // Check for block delimiter
  if ( (_curchar != '%')
       || ( next_char(),  (_curchar != '{')) ) {
1785
    parse_err(SYNERR, "missing \"%%{\" in pipe_class definition\n");
D
duke 已提交
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    return;
  }
  next_char();

  do {
    ident = get_ident();           // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "keyword identifier expected at \"%c\"\n", _curchar);
      continue;
    }
    skipws();

    if (!strcmp(ident, "fixed_latency")) {
      skipws();
      if (_curchar != '(') {
        parse_err(SYNERR, "missing \"(\" in latency definition\n");
        return;
      }
      next_char(); skipws();
      if( !isdigit(_curchar) ) {
        parse_err(SYNERR, "number expected for \"%c\" in latency definition\n", _curchar);
        return;
      }
      int fixed_latency = get_int();
      skipws();
      if (_curchar != ')') {
        parse_err(SYNERR, "missing \")\" in latency definition\n");
        return;
      }
      next_char(); skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" in latency definition\n");
        return;
      }

      pipe_class->setFixedLatency(fixed_latency);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "zero_instructions") ||
        !strcmp(ident, "no_instructions")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" in latency definition\n");
        return;
      }

      pipe_class->setInstructionCount(0);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "one_instruction_with_delay_slot") ||
        !strcmp(ident, "single_instruction_with_delay_slot")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" in latency definition\n");
        return;
      }

      pipe_class->setInstructionCount(1);
      pipe_class->setBranchDelay(true);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "one_instruction") ||
        !strcmp(ident, "single_instruction")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" in latency definition\n");
        return;
      }

      pipe_class->setInstructionCount(1);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "instructions_in_first_bundle") ||
        !strcmp(ident, "instruction_count")) {
      skipws();

      int number_of_instructions = 1;

      if (_curchar != '(') {
        parse_err(SYNERR, "\"(\" expected at \"%c\"\n", _curchar);
        continue;
      }

      next_char(); skipws();
      number_of_instructions = get_int();

      skipws();
      if (_curchar != ')') {
        parse_err(SYNERR, "\")\" expected at \"%c\"\n", _curchar);
        continue;
      }

      next_char(); skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" in latency definition\n");
        return;
      }

      pipe_class->setInstructionCount(number_of_instructions);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "multiple_bundles")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" after multiple bundles\n");
        return;
      }

      pipe_class->setMultipleBundles(true);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "has_delay_slot")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" after \"has_delay_slot\"\n");
        return;
      }

      pipe_class->setBranchDelay(true);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "force_serialization")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" after \"force_serialization\"\n");
        return;
      }

      pipe_class->setForceSerialization(true);
      next_char(); skipws();
      continue;
    }

    if (!strcmp(ident, "may_have_no_code")) {
      skipws();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing \";\" after \"may_have_no_code\"\n");
        return;
      }

      pipe_class->setMayHaveNoCode(true);
      next_char(); skipws();
      continue;
    }

    const Form *parm = pipe_class->_localNames[ident];
    if (parm != NULL) {
      oper = parm->is_operand();
      if (oper == NULL && !parm->is_opclass()) {
        parse_err(SYNERR, "operand name expected at %s\n", ident);
        continue;
      }

      if (_curchar != ':') {
        parse_err(SYNERR, "\":\" expected at \"%c\"\n", _curchar);
        continue;
      }
      next_char(); skipws();
      stage = get_ident();
      if (stage == NULL) {
        parse_err(SYNERR, "pipeline stage identifier expected at \"%c\"\n", _curchar);
        continue;
      }

      skipws();
      if (_curchar != '(') {
        parse_err(SYNERR, "\"(\" expected at \"%c\"\n", _curchar);
        continue;
      }

      next_char();
      read_or_write = get_ident();
      if (read_or_write == NULL) {
        parse_err(SYNERR, "\"read\" or \"write\" expected at \"%c\"\n", _curchar);
        continue;
      }

      is_read  = strcmp(read_or_write, "read")   == 0;
      is_write = strcmp(read_or_write, "write")  == 0;
      if (!is_read && !is_write) {
        parse_err(SYNERR, "\"read\" or \"write\" expected at \"%c\"\n", _curchar);
        continue;
      }

      skipws();
      if (_curchar != ')') {
        parse_err(SYNERR, "\")\" expected at \"%c\"\n", _curchar);
        continue;
      }

      next_char(); skipws();
      int more_instrs = 0;
      if (_curchar == '+') {
          next_char(); skipws();
          if (_curchar < '0' || _curchar > '9') {
            parse_err(SYNERR, "<number> expected at \"%c\"\n", _curchar);
            continue;
          }
          while (_curchar >= '0' && _curchar <= '9') {
            more_instrs *= 10;
            more_instrs += _curchar - '0';
            next_char();
          }
          skipws();
      }

      PipeClassOperandForm *pipe_operand = new PipeClassOperandForm(stage, is_write, more_instrs);
      pipe_class->_localUsage.Insert(ident, pipe_operand);

      if (_curchar == '%')
          continue;

      if (_curchar != ';') {
        parse_err(SYNERR, "\";\" expected at \"%c\"\n", _curchar);
        continue;
      }
      next_char(); skipws();
      continue;
    }

    // Scan for Resource Specifier
    const Form *res = pipeline._resdict[ident];
    if (res != NULL) {
      int cyclecnt = 1;
      if (_curchar != ':') {
        parse_err(SYNERR, "\":\" expected at \"%c\"\n", _curchar);
        continue;
      }
      next_char(); skipws();
      stage = get_ident();
      if (stage == NULL) {
        parse_err(SYNERR, "pipeline stage identifier expected at \"%c\"\n", _curchar);
        continue;
      }

      skipws();
      if (_curchar == '(') {
        next_char();
        cyclecnt = get_int();

        skipws();
        if (_curchar != ')') {
          parse_err(SYNERR, "\")\" expected at \"%c\"\n", _curchar);
          continue;
        }

        next_char(); skipws();
      }

      PipeClassResourceForm *resource = new PipeClassResourceForm(ident, stage, cyclecnt);
      int stagenum = pipeline._stages.index(stage);
      if (pipeline._maxcycleused < (stagenum+cyclecnt))
        pipeline._maxcycleused = (stagenum+cyclecnt);
      pipe_class->_resUsage.addForm(resource);

      if (_curchar == '%')
          continue;

      if (_curchar != ';') {
        parse_err(SYNERR, "\";\" expected at \"%c\"\n", _curchar);
        continue;
      }
      next_char(); skipws();
      continue;
    }

    parse_err(SYNERR, "resource expected at \"%s\"\n", ident);
    return;
  } while(_curchar != '%');

  next_char();
  if (_curchar != '}') {
2072
    parse_err(SYNERR, "missing \"%%}\" in pipe_class definition\n");
D
duke 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
    return;
  }

  next_char();
}

//------------------------------peep_parse-------------------------------------
void ADLParser::peep_parse(void) {
  Peephole  *peep;                // Pointer to current peephole rule form
  char      *desc = NULL;         // String representation of rule

  skipws();                       // Skip leading whitespace

  peep = new Peephole();          // Build new Peephole object
  // Check for open block sequence
  skipws();                       // Skip leading whitespace
  if (_curchar == '%' && *(_ptr+1) == '{') {
    next_char(); next_char();     // Skip "%{"
    skipws();
    while (_curchar != '%' && *(_ptr+1) != '}') {
      char *token = get_ident();
      if (token == NULL) {
        parse_err(SYNERR, "missing identifier inside peephole rule.\n");
        return;
      }
      // check for legal subsections of peephole rule
      if (strcmp(token,"peepmatch")==0) {
        peep_match_parse(*peep); }
      else if (strcmp(token,"peepconstraint")==0) {
        peep_constraint_parse(*peep); }
      else if (strcmp(token,"peepreplace")==0) {
        peep_replace_parse(*peep); }
      else {
        parse_err(SYNERR, "expected peepmatch, peepconstraint, or peepreplace for identifier %s.\n", token);
      }
      skipws();
    }
  }
  else {
    parse_err(SYNERR, "Missing %%{ ... %%} block after peephole keyword.\n");
    return;
  }
  next_char();                    // Skip past '%'
  next_char();                    // Skip past '}'
}

// ******************** Private Level 2 Parse Functions ********************
//------------------------------constraint_parse------------------------------
Constraint *ADLParser::constraint_parse(void) {
  char *func;
  char *arg;

  // Check for constraint expression
  skipws();
  if (_curchar != '(') {
    parse_err(SYNERR, "missing constraint expression, (...)\n");
    return NULL;
  }
  next_char();                    // Skip past '('

  // Get constraint function
  skipws();
  func = get_ident();
  if (func == NULL) {
    parse_err(SYNERR, "missing function in constraint expression.\n");
    return NULL;
  }
  if (strcmp(func,"ALLOC_IN_RC")==0
      || strcmp(func,"IS_R_CLASS")==0) {
    // Check for '(' before argument
    skipws();
    if (_curchar != '(') {
      parse_err(SYNERR, "missing '(' for constraint function's argument.\n");
      return NULL;
    }
    next_char();

    // Get it's argument
    skipws();
    arg = get_ident();
    if (arg == NULL) {
      parse_err(SYNERR, "missing argument for constraint function %s\n",func);
      return NULL;
    }
    // Check for ')' after argument
    skipws();
    if (_curchar != ')') {
      parse_err(SYNERR, "missing ')' after constraint function argument %s\n",arg);
      return NULL;
    }
    next_char();
  } else {
    parse_err(SYNERR, "Invalid constraint function %s\n",func);
    return NULL;
  }

  // Check for closing paren and ';'
  skipws();
  if (_curchar != ')') {
    parse_err(SYNERR, "Missing ')' for constraint function %s\n",func);
    return NULL;
  }
  next_char();
  skipws();
  if (_curchar != ';') {
    parse_err(SYNERR, "Missing ';' after constraint.\n");
    return NULL;
  }
  next_char();

  // Create new "Constraint"
  Constraint *constraint = new Constraint(func,arg);
  return constraint;
}

//------------------------------constr_parse-----------------------------------
ConstructRule *ADLParser::construct_parse(void) {
  return NULL;
}


//------------------------------reg_def_parse----------------------------------
void ADLParser::reg_def_parse(void) {
  char *rname;                   // Name of register being defined

  // Get register name
  skipws();                      // Skip whitespace
  rname = get_ident();
  if (rname == NULL) {
    parse_err(SYNERR, "missing register name after reg_def\n");
    return;
  }

  // Check for definition of register calling convention (save on call, ...),
  // register save type, and register encoding value.
  skipws();
  char *callconv  = NULL;
  char *c_conv    = NULL;
  char *idealtype = NULL;
  char *encoding  = NULL;
  char *concrete = NULL;
  if (_curchar == '(') {
    next_char();
    callconv = get_ident();
    // Parse the internal calling convention, must be NS, SOC, SOE, or AS.
    if (callconv == NULL) {
      parse_err(SYNERR, "missing register calling convention value\n");
      return;
    }
    if(strcmp(callconv, "SOC") && strcmp(callconv,"SOE") &&
       strcmp(callconv, "NS") && strcmp(callconv, "AS")) {
      parse_err(SYNERR, "invalid value for register calling convention\n");
    }
    skipws();
    if (_curchar != ',') {
      parse_err(SYNERR, "missing comma in register definition statement\n");
      return;
    }
    next_char();

    // Parse the native calling convention, must be NS, SOC, SOE, AS
    c_conv = get_ident();
    if (c_conv == NULL) {
      parse_err(SYNERR, "missing register native calling convention value\n");
      return;
    }
    if(strcmp(c_conv, "SOC") && strcmp(c_conv,"SOE") &&
       strcmp(c_conv, "NS") && strcmp(c_conv, "AS")) {
      parse_err(SYNERR, "invalid value for register calling convention\n");
    }
    skipws();
    if (_curchar != ',') {
      parse_err(SYNERR, "missing comma in register definition statement\n");
      return;
    }
    next_char();
    skipws();

    // Parse the ideal save type
    idealtype = get_ident();
    if (idealtype == NULL) {
      parse_err(SYNERR, "missing register save type value\n");
      return;
    }
    skipws();
    if (_curchar != ',') {
      parse_err(SYNERR, "missing comma in register definition statement\n");
      return;
    }
    next_char();
    skipws();

    // Parse the encoding value
    encoding = get_expr("encoding", ",");
    if (encoding == NULL) {
      parse_err(SYNERR, "missing register encoding value\n");
      return;
    }
    trim(encoding);
    if (_curchar != ',') {
      parse_err(SYNERR, "missing comma in register definition statement\n");
      return;
    }
    next_char();
    skipws();
    // Parse the concrete name type
    // concrete = get_ident();
    concrete = get_expr("concrete", ")");
    if (concrete == NULL) {
      parse_err(SYNERR, "missing vm register name value\n");
      return;
    }

    if (_curchar != ')') {
      parse_err(SYNERR, "missing ')' in register definition statement\n");
      return;
    }
    next_char();
  }

  // Check for closing ';'
  skipws();
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' after reg_def\n");
    return;
  }
  next_char();                   // move past ';'

  // Debug Stuff
  if (_AD._adl_debug > 1) {
    fprintf(stderr,"Register Definition: %s ( %s, %s %s )\n", rname,
            (callconv ? callconv : ""), (c_conv ? c_conv : ""), concrete);
  }

  // Record new register definition.
  _AD._register->addRegDef(rname, callconv, c_conv, idealtype, encoding, concrete);
  return;
}

//------------------------------reg_class_parse--------------------------------
void ADLParser::reg_class_parse(void) {
  char *cname;                    // Name of register class being defined

  // Get register class name
  skipws();                       // Skip leading whitespace
  cname = get_ident();
  if (cname == NULL) {
    parse_err(SYNERR, "missing register class name after 'reg_class'\n");
    return;
  }
  // Debug Stuff
  if (_AD._adl_debug >1) fprintf(stderr,"Register Class: %s\n", cname);

  RegClass *reg_class = _AD._register->addRegClass(cname);

  // Collect registers in class
  skipws();
  if (_curchar == '(') {
    next_char();                  // Skip '('
    skipws();
    while (_curchar != ')') {
      char *rname = get_ident();
      if (rname==NULL) {
        parse_err(SYNERR, "missing identifier inside reg_class list.\n");
        return;
      }
      RegDef *regDef = _AD._register->getRegDef(rname);
2340 2341 2342 2343 2344
      if (!regDef) {
        parse_err(SEMERR, "unknown identifier %s inside reg_class list.\n", rname);
      } else {
        reg_class->addReg(regDef); // add regDef to regClass
      }
D
duke 已提交
2345 2346 2347 2348 2349 2350 2351 2352 2353

      // Check for ',' and position to next token.
      skipws();
      if (_curchar == ',') {
        next_char();              // Skip trailing ','
        skipws();
      }
    }
    next_char();                  // Skip closing ')'
2354 2355 2356 2357 2358 2359 2360 2361
  } else if (_curchar == '%') {
    char *code = find_cpp_block("reg class");
    if (code == NULL) {
      parse_err(SYNERR, "missing code declaration for reg class.\n");
      return;
    }
    reg_class->_user_defined = code;
    return;
D
duke 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
  }

  // Check for terminating ';'
  skipws();
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' at end of reg_class definition.\n");
    return;
  }
  next_char();                    // Skip trailing ';'

  // Check RegClass size, must be <= 32 registers in class.

  return;
}

//------------------------------alloc_class_parse------------------------------
void ADLParser::alloc_class_parse(void) {
  char *name;                     // Name of allocation class being defined

  // Get allocation class name
  skipws();                       // Skip leading whitespace
  name = get_ident();
  if (name == NULL) {
    parse_err(SYNERR, "missing allocation class name after 'reg_class'\n");
    return;
  }
  // Debug Stuff
  if (_AD._adl_debug >1) fprintf(stderr,"Allocation Class: %s\n", name);

  AllocClass *alloc_class = _AD._register->addAllocClass(name);

  // Collect registers in class
  skipws();
  if (_curchar == '(') {
    next_char();                  // Skip '('
    skipws();
    while (_curchar != ')') {
      char *rname = get_ident();
      if (rname==NULL) {
        parse_err(SYNERR, "missing identifier inside reg_class list.\n");
        return;
      }
      // Check if name is a RegDef
      RegDef *regDef = _AD._register->getRegDef(rname);
      if (regDef) {
        alloc_class->addReg(regDef);   // add regDef to allocClass
      } else {

        // name must be a RegDef or a RegClass
        parse_err(SYNERR, "name %s should be a previously defined reg_def.\n", rname);
        return;
      }

      // Check for ',' and position to next token.
      skipws();
      if (_curchar == ',') {
        next_char();              // Skip trailing ','
        skipws();
      }
    }
    next_char();                  // Skip closing ')'
  }

  // Check for terminating ';'
  skipws();
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' at end of reg_class definition.\n");
    return;
  }
  next_char();                    // Skip trailing ';'

  return;
}

//------------------------------peep_match_child_parse-------------------------
InstructForm *ADLParser::peep_match_child_parse(PeepMatch &match, int parent, int &position, int input){
  char      *token  = NULL;
  int        lparen = 0;          // keep track of parenthesis nesting depth
  int        rparen = 0;          // position of instruction at this depth
  InstructForm *inst_seen  = NULL;

  // Walk the match tree,
  // Record <parent, position, instruction name, input position>
  while ( lparen >= rparen ) {
    skipws();
    // Left paren signals start of an input, collect with recursive call
    if (_curchar == '(') {
      ++lparen;
      next_char();
K
kvn 已提交
2451
      ( void ) peep_match_child_parse(match, parent, position, rparen);
D
duke 已提交
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
    }
    // Right paren signals end of an input, may be more
    else if (_curchar == ')') {
      ++rparen;
      if( rparen == lparen ) { // IF rparen matches an lparen I've seen
        next_char();           //    move past ')'
      } else {                 // ELSE leave ')' for parent
        assert( rparen == lparen + 1, "Should only see one extra ')'");
        // if an instruction was not specified for this paren-pair
        if( ! inst_seen ) {   // record signal entry
          match.add_instruction( parent, position, NameList::_signal, input );
          ++position;
        }
        // ++input;   // TEMPORARY
        return inst_seen;
      }
    }
    // if no parens, then check for instruction name
    // This instruction is the parent of a sub-tree
    else if ((token = get_ident_dup()) != NULL) {
      const Form *form = _AD._globalNames[token];
      if (form) {
        InstructForm *inst = form->is_instruction();
        // Record the first instruction at this level
        if( inst_seen == NULL ) {
          inst_seen = inst;
        }
        if (inst) {
          match.add_instruction( parent, position, token, input );
          parent = position;
          ++position;
        } else {
          parse_err(SYNERR, "instruction name expected at identifier %s.\n",
                    token);
          return inst_seen;
        }
      }
      else {
        parse_err(SYNERR, "missing identifier in peepmatch rule.\n");
        return NULL;
      }
    }
    else {
      parse_err(SYNERR, "missing identifier in peepmatch rule.\n");
      return NULL;
    }

  } // end while

  assert( false, "ShouldNotReachHere();");
  return NULL;
}

//------------------------------peep_match_parse-------------------------------
// Syntax for a peepmatch rule
//
// peepmatch ( root_instr_name [(instruction subtree)] [,(instruction subtree)]* );
//
void ADLParser::peep_match_parse(Peephole &peep) {

  skipws();
  // Check the structure of the rule
  // Check for open paren
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' at start of peepmatch rule.\n");
    return;
  }
  next_char();   // skip '('

  // Construct PeepMatch and parse the peepmatch rule.
  PeepMatch *match = new PeepMatch(_ptr);
  int  parent   = -1;                   // parent of root
  int  position = 0;                    // zero-based positions
  int  input    = 0;                    // input position in parent's operands
  InstructForm *root= peep_match_child_parse( *match, parent, position, input);
  if( root == NULL ) {
    parse_err(SYNERR, "missing instruction-name at start of peepmatch.\n");
    return;
  }

  if( _curchar != ')' ) {
    parse_err(SYNERR, "missing ')' at end of peepmatch.\n");
    return;
  }
  next_char();   // skip ')'

  // Check for closing semicolon
  skipws();
  if( _curchar != ';' ) {
    parse_err(SYNERR, "missing ';' at end of peepmatch.\n");
    return;
  }
  next_char();   // skip ';'

  // Store match into peep, and store peep into instruction
  peep.add_match(match);
  root->append_peephole(&peep);
}

//------------------------------peep_constraint_parse--------------------------
// Syntax for a peepconstraint rule
// A parenthesized list of relations between operands in peepmatch subtree
//
// peepconstraint %{
// (instruction_number.operand_name
//     relational_op
//  instruction_number.operand_name OR register_name
//  [, ...] );
//
// // instruction numbers are zero-based using topological order in peepmatch
//
void ADLParser::peep_constraint_parse(Peephole &peep) {

  skipws();
  // Check the structure of the rule
  // Check for open paren
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' at start of peepconstraint rule.\n");
    return;
  }
  else {
    next_char();                  // Skip '('
  }

  // Check for a constraint
  skipws();
  while( _curchar != ')' ) {
    // Get information on the left instruction and its operand
    // left-instructions's number
2581
    int left_inst = get_int();
D
duke 已提交
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
    // Left-instruction's operand
    skipws();
    if( _curchar != '.' ) {
      parse_err(SYNERR, "missing '.' in peepconstraint after instruction number.\n");
      return;
    }
    next_char();                  // Skip '.'
    char *left_op = get_ident_dup();

    skipws();
    // Collect relational operator
    char *relation = get_relation_dup();

    skipws();
    // Get information on the right instruction and its operand
2597
    int right_inst;        // Right-instructions's number
D
duke 已提交
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
    if( isdigit(_curchar) ) {
      right_inst = get_int();
      // Right-instruction's operand
      skipws();
      if( _curchar != '.' ) {
        parse_err(SYNERR, "missing '.' in peepconstraint after instruction number.\n");
        return;
      }
      next_char();              // Skip '.'
    } else {
      right_inst = -1;          // Flag as being a register constraint
    }

    char *right_op = get_ident_dup();

    // Construct the next PeepConstraint
    PeepConstraint *constraint = new PeepConstraint( left_inst, left_op,
                                                     relation,
                                                     right_inst, right_op );
    // And append it to the list for this peephole rule
    peep.append_constraint( constraint );

    // Check for another constraint, or end of rule
    skipws();
    if( _curchar == ',' ) {
      next_char();                // Skip ','
      skipws();
    }
    else if( _curchar != ')' ) {
      parse_err(SYNERR, "expected ',' or ')' after peephole constraint.\n");
      return;
    }
  } // end while( processing constraints )
  next_char();                    // Skip ')'

  // Check for terminating ';'
  skipws();
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' at end of peepconstraint.\n");
    return;
  }
  next_char();                    // Skip trailing ';'
}


//------------------------------peep_replace_parse-----------------------------
// Syntax for a peepreplace rule
// root instruction name followed by a
// parenthesized list of whitespace separated instruction.operand specifiers
//
// peepreplace ( instr_name  ( [instruction_number.operand_name]* ) );
//
//
void ADLParser::peep_replace_parse(Peephole &peep) {
  int          lparen = 0;        // keep track of parenthesis nesting depth
  int          rparen = 0;        // keep track of parenthesis nesting depth
  int          icount = 0;        // count of instructions in rule for naming
  char        *str    = NULL;
  char        *token  = NULL;

  skipws();
  // Check for open paren
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' at start of peepreplace rule.\n");
    return;
  }
  else {
    lparen++;
    next_char();
  }

  // Check for root instruction
  char       *inst = get_ident_dup();
  const Form *form = _AD._globalNames[inst];
  if( form == NULL || form->is_instruction() == NULL ) {
    parse_err(SYNERR, "Instruction name expected at start of peepreplace.\n");
    return;
  }

  // Store string representation of rule into replace
  PeepReplace *replace = new PeepReplace(str);
  replace->add_instruction( inst );

  skipws();
  // Start of root's operand-list
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' at peepreplace root's operand-list.\n");
    return;
  }
  else {
    lparen++;
    next_char();
  }

  skipws();
  // Get the list of operands
  while( _curchar != ')' ) {
    // Get information on an instruction and its operand
    // instructions's number
    int   inst_num = get_int();
    // Left-instruction's operand
    skipws();
    if( _curchar != '.' ) {
      parse_err(SYNERR, "missing '.' in peepreplace after instruction number.\n");
      return;
    }
    next_char();                  // Skip '.'
    char *inst_op = get_ident_dup();
    if( inst_op == NULL ) {
      parse_err(SYNERR, "missing operand identifier in peepreplace.\n");
      return;
    }

    // Record this operand's position in peepmatch
    replace->add_operand( inst_num, inst_op );
    skipws();
  }

  // Check for the end of operands list
  skipws();
  assert( _curchar == ')', "While loop should have advanced to ')'.");
  next_char();  // Skip ')'

  skipws();
  // Check for end of peepreplace
  if( _curchar != ')' ) {
    parse_err(SYNERR, "missing ')' at end of peepmatch.\n");
    parse_err(SYNERR, "Support one replacement instruction.\n");
    return;
  }
  next_char(); // Skip ')'

  // Check for closing semicolon
  skipws();
  if( _curchar != ';' ) {
    parse_err(SYNERR, "missing ';' at end of peepreplace.\n");
    return;
  }
  next_char();   // skip ';'

  // Store replace into peep
  peep.add_replace( replace );
}

//------------------------------pred_parse-------------------------------------
Predicate *ADLParser::pred_parse(void) {
  Predicate *predicate;           // Predicate class for operand
  char      *rule = NULL;         // String representation of predicate

  skipws();                       // Skip leading whitespace
2748 2749
  int line = linenum();
  if ( (rule = get_paren_expr("pred expression", true)) == NULL ) {
D
duke 已提交
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
    parse_err(SYNERR, "incorrect or missing expression for 'predicate'\n");
    return NULL;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Predicate: %s\n", rule);
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in predicate definition\n");
    return NULL;
  }
  next_char();                     // Point after the terminator

  predicate = new Predicate(rule); // Build new predicate object
  skipws();
  return predicate;
}


//------------------------------ins_encode_parse_block-------------------------
// Parse the block form of ins_encode.  See ins_encode_parse for more details
2769
void ADLParser::ins_encode_parse_block(InstructForm& inst) {
D
duke 已提交
2770 2771
  // Create a new encoding name based on the name of the instruction
  // definition, which should be unique.
2772 2773
  const char* prefix = "__ins_encode_";
  char* ec_name = (char*) malloc(strlen(inst._ident) + strlen(prefix) + 1);
D
duke 已提交
2774 2775 2776
  sprintf(ec_name, "%s%s", prefix, inst._ident);

  assert(_AD._encode->encClass(ec_name) == NULL, "shouldn't already exist");
2777
  EncClass* encoding = _AD._encode->add_EncClass(ec_name);
2778
  encoding->_linenum = linenum();
D
duke 已提交
2779 2780 2781

  // synthesize the arguments list for the enc_class from the
  // arguments to the instruct definition.
2782
  const char* param = NULL;
D
duke 已提交
2783 2784
  inst._parameters.reset();
  while ((param = inst._parameters.iter()) != NULL) {
2785
    OperandForm* opForm = (OperandForm*) inst._localNames[param];
D
duke 已提交
2786 2787 2788
    encoding->add_parameter(opForm->_ident, param);
  }

2789 2790 2791 2792 2793 2794 2795
  if (!inst._is_postalloc_expand) {
    // Define a MacroAssembler instance for use by the encoding.  The
    // name is chosen to match the __ idiom used for assembly in other
    // parts of hotspot and assumes the existence of the standard
    // #define __ _masm.
    encoding->add_code("    MacroAssembler _masm(&cbuf);\n");
  }
D
duke 已提交
2796 2797

  // Parse the following %{ }% block
2798
  ins_encode_parse_block_impl(inst, encoding, ec_name);
D
duke 已提交
2799 2800 2801

  // Build an encoding rule which invokes the encoding rule we just
  // created, passing all arguments that we received.
2802 2803
  InsEncode*   encrule = new InsEncode(); // Encode class for instruction
  NameAndList* params  = encrule->add_encode(ec_name);
D
duke 已提交
2804 2805 2806 2807 2808
  inst._parameters.reset();
  while ((param = inst._parameters.iter()) != NULL) {
    params->add_entry(param);
  }

2809 2810 2811 2812 2813 2814 2815
  // Check for duplicate ins_encode sections after parsing the block
  // so that parsing can continue and find any other errors.
  if (inst._insencode != NULL) {
    parse_err(SYNERR, "Multiple ins_encode sections defined\n");
    return;
  }

2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868
  // Set encode class of this instruction.
  inst._insencode = encrule;
}


void ADLParser::ins_encode_parse_block_impl(InstructForm& inst, EncClass* encoding, char* ec_name) {
  skipws_no_preproc();              // Skip leading whitespace
  // Prepend location descriptor, for debugging; cf. ADLParser::find_cpp_block
  if (_AD._adlocation_debug) {
    encoding->add_code(get_line_string());
  }

  // Collect the parts of the encode description
  // (1) strings that are passed through to output
  // (2) replacement/substitution variable, preceeded by a '$'
  while ((_curchar != '%') && (*(_ptr+1) != '}')) {

    // (1)
    // Check if there is a string to pass through to output
    char *start = _ptr;       // Record start of the next string
    while ((_curchar != '$') && ((_curchar != '%') || (*(_ptr+1) != '}')) ) {
      // If at the start of a comment, skip past it
      if( (_curchar == '/') && ((*(_ptr+1) == '/') || (*(_ptr+1) == '*')) ) {
        skipws_no_preproc();
      } else {
        // ELSE advance to the next character, or start of the next line
        next_char_or_line();
      }
    }
    // If a string was found, terminate it and record in EncClass
    if (start != _ptr) {
      *_ptr = '\0';          // Terminate the string
      encoding->add_code(start);
    }

    // (2)
    // If we are at a replacement variable,
    // copy it and record in EncClass
    if (_curchar == '$') {
      // Found replacement Variable
      char* rep_var = get_rep_var_ident_dup();

      // Add flag to _strings list indicating we should check _rep_vars
      encoding->add_rep_var(rep_var);

      skipws();

      // Check if this instruct is a MachConstantNode.
      if (strcmp(rep_var, "constanttablebase") == 0) {
        // This instruct is a MachConstantNode.
        inst.set_is_mach_constant(true);

        if (_curchar == '(')  {
2869 2870
          parse_err(SYNERR, "constanttablebase in instruct %s cannot have an argument "
                            "(only constantaddress and constantoffset)", ec_name);
2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
          return;
        }
      }
      else if ((strcmp(rep_var, "constantaddress")   == 0) ||
               (strcmp(rep_var, "constantoffset")    == 0)) {
        // This instruct is a MachConstantNode.
        inst.set_is_mach_constant(true);

        // If the constant keyword has an argument, parse it.
        if (_curchar == '(')  constant_parse(inst);
      }
    }
  } // end while part of format description
  next_char();                      // Skip '%'
  next_char();                      // Skip '}'

  skipws();

  if (_AD._adlocation_debug) {
    encoding->add_code(end_line_marker());
  }

  // Debug Stuff
  if (_AD._adl_debug > 1)  fprintf(stderr, "EncodingClass Form: %s\n", ec_name);
D
duke 已提交
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
}


//------------------------------ins_encode_parse-------------------------------
// Encode rules have the form
//   ins_encode( encode_class_name(parameter_list), ... );
//
// The "encode_class_name" must be defined in the encode section
// The parameter list contains $names that are locals.
//
// Alternatively it can be written like this:
//
//   ins_encode %{
//      ... // body
//   %}
//
// which synthesizes a new encoding class taking the same arguments as
// the InstructForm, and automatically prefixes the definition with:
//
//    MacroAssembler masm(&cbuf);\n");
//
//  making it more compact to take advantage of the MacroAssembler and
//  placing the assembly closer to it's use by instructions.
2918
void ADLParser::ins_encode_parse(InstructForm& inst) {
D
duke 已提交
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928

  // Parse encode class name
  skipws();                        // Skip whitespace
  if (_curchar != '(') {
    // Check for ins_encode %{ form
    if ((_curchar == '%') && (*(_ptr+1) == '{')) {
      next_char();                      // Skip '%'
      next_char();                      // Skip '{'

      // Parse the block form of ins_encode
2929 2930
      ins_encode_parse_block(inst);
      return;
D
duke 已提交
2931 2932 2933
    }

    parse_err(SYNERR, "missing '%%{' or '(' in ins_encode definition\n");
2934
    return;
D
duke 已提交
2935 2936 2937 2938 2939
  }
  next_char();                     // move past '('
  skipws();

  InsEncode *encrule  = new InsEncode(); // Encode class for instruction
2940
  encrule->_linenum = linenum();
D
duke 已提交
2941 2942 2943 2944 2945 2946
  char      *ec_name  = NULL;      // String representation of encode rule
  // identifier is optional.
  while (_curchar != ')') {
    ec_name = get_ident();
    if (ec_name == NULL) {
      parse_err(SYNERR, "Invalid encode class name after 'ins_encode('.\n");
2947
      return;
D
duke 已提交
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
    }
    // Check that encoding is defined in the encode section
    EncClass *encode_class = _AD._encode->encClass(ec_name);
    if (encode_class == NULL) {
      // Like to defer checking these till later...
      // parse_err(WARN, "Using an undefined encode class '%s' in 'ins_encode'.\n", ec_name);
    }

    // Get list for encode method's parameters
    NameAndList *params = encrule->add_encode(ec_name);

    // Parse the parameters to this encode method.
    skipws();
    if ( _curchar == '(' ) {
      next_char();                 // move past '(' for parameters

      // Parse the encode method's parameters
      while (_curchar != ')') {
        char *param = get_ident_or_literal_constant("encoding operand");
        if ( param != NULL ) {
          // Found a parameter:
          // Check it is a local name, add it to the list, then check for more
          // New: allow hex constants as parameters to an encode method.
          // New: allow parenthesized expressions as parameters.
          // New: allow "primary", "secondary", "tertiary" as parameters.
          // New: allow user-defined register name as parameter
          if ( (inst._localNames[param] == NULL) &&
               !ADLParser::is_literal_constant(param) &&
               (Opcode::as_opcode_type(param) == Opcode::NOT_AN_OPCODE) &&
               ((_AD._register == NULL ) || (_AD._register->getRegDef(param) == NULL)) ) {
            parse_err(SYNERR, "Using non-locally defined parameter %s for encoding %s.\n", param, ec_name);
2979
            return;
D
duke 已提交
2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
          }
          params->add_entry(param);

          skipws();
          if (_curchar == ',' ) {
            // More parameters to come
            next_char();           // move past ',' between parameters
            skipws();              // Skip to next parameter
          }
          else if (_curchar == ')') {
            // Done with parameter list
          }
          else {
            // Only ',' or ')' are valid after a parameter name
            parse_err(SYNERR, "expected ',' or ')' after parameter %s.\n",
                      ec_name);
2996
            return;
D
duke 已提交
2997 2998 2999 3000 3001 3002 3003
          }

        } else {
          skipws();
          // Did not find a parameter
          if (_curchar == ',') {
            parse_err(SYNERR, "Expected encode parameter before ',' in encoding %s.\n", ec_name);
3004
            return;
D
duke 已提交
3005 3006 3007
          }
          if (_curchar != ')') {
            parse_err(SYNERR, "Expected ')' after encode parameters.\n");
3008
            return;
D
duke 已提交
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
          }
        }
      } // WHILE loop collecting parameters
      next_char();                   // move past ')' at end of parameters
    } // done with parameter list for encoding

    // Check for ',' or ')' after encoding
    skipws();                      // move to character after parameters
    if ( _curchar == ',' ) {
      // Found a ','
      next_char();                 // move past ',' between encode methods
      skipws();
    }
    else if ( _curchar != ')' ) {
      // If not a ',' then only a ')' is allowed
      parse_err(SYNERR, "Expected ')' after encoding %s.\n", ec_name);
3025
      return;
D
duke 已提交
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
    }

    // Check for ',' separating parameters
    // if ( _curchar != ',' && _curchar != ')' ) {
    //   parse_err(SYNERR, "expected ',' or ')' after encode method inside ins_encode.\n");
    //   return NULL;
    // }

  } // done parsing ins_encode methods and their parameters
  if (_curchar != ')') {
    parse_err(SYNERR, "Missing ')' at end of ins_encode description.\n");
3037
    return;
D
duke 已提交
3038 3039 3040 3041 3042 3043
  }
  next_char();                     // move past ')'
  skipws();                        // Skip leading whitespace

  if ( _curchar != ';' ) {
    parse_err(SYNERR, "Missing ';' at end of ins_encode.\n");
3044
    return;
D
duke 已提交
3045 3046 3047 3048
  }
  next_char();                     // move past ';'
  skipws();                        // be friendly to oper_parse()

3049 3050 3051 3052 3053 3054 3055
  // Check for duplicate ins_encode sections after parsing the block
  // so that parsing can continue and find any other errors.
  if (inst._insencode != NULL) {
    parse_err(SYNERR, "Multiple ins_encode sections defined\n");
    return;
  }

D
duke 已提交
3056 3057 3058
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Instruction Encode: %s\n", ec_name);

3059 3060 3061 3062
  // Set encode class of this instruction.
  inst._insencode = encrule;
}

3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
//------------------------------postalloc_expand_parse---------------------------
// Encode rules have the form
//   postalloc_expand( encode_class_name(parameter_list) );
//
// The "encode_class_name" must be defined in the encode section.
// The parameter list contains $names that are locals.
//
// This is just a copy of ins_encode_parse without the loop.
void ADLParser::postalloc_expand_parse(InstructForm& inst) {
  inst._is_postalloc_expand = true;

  // Parse encode class name.
  skipws();                        // Skip whitespace.
  if (_curchar != '(') {
    // Check for postalloc_expand %{ form
    if ((_curchar == '%') && (*(_ptr+1) == '{')) {
      next_char();                      // Skip '%'
      next_char();                      // Skip '{'

      // Parse the block form of postalloc_expand
      ins_encode_parse_block(inst);
      return;
    }

    parse_err(SYNERR, "missing '(' in postalloc_expand definition\n");
    return;
  }
  next_char();                     // Move past '('.
  skipws();

  InsEncode *encrule = new InsEncode(); // Encode class for instruction.
  encrule->_linenum = linenum();
  char      *ec_name = NULL;       // String representation of encode rule.
  // identifier is optional.
  if (_curchar != ')') {
    ec_name = get_ident();
    if (ec_name == NULL) {
      parse_err(SYNERR, "Invalid postalloc_expand class name after 'postalloc_expand('.\n");
      return;
    }
    // Check that encoding is defined in the encode section.
    EncClass *encode_class = _AD._encode->encClass(ec_name);

    // Get list for encode method's parameters
    NameAndList *params = encrule->add_encode(ec_name);

    // Parse the parameters to this encode method.
    skipws();
    if (_curchar == '(') {
      next_char();                 // Move past '(' for parameters.

      // Parse the encode method's parameters.
      while (_curchar != ')') {
        char *param = get_ident_or_literal_constant("encoding operand");
        if (param != NULL) {
          // Found a parameter:

          // First check for constant table support.

          // Check if this instruct is a MachConstantNode.
          if (strcmp(param, "constanttablebase") == 0) {
            // This instruct is a MachConstantNode.
            inst.set_is_mach_constant(true);

            if (_curchar == '(') {
              parse_err(SYNERR, "constanttablebase in instruct %s cannot have an argument "
                        "(only constantaddress and constantoffset)", ec_name);
              return;
            }
          }
          else if ((strcmp(param, "constantaddress") == 0) ||
                   (strcmp(param, "constantoffset")  == 0))  {
            // This instruct is a MachConstantNode.
            inst.set_is_mach_constant(true);

            // If the constant keyword has an argument, parse it.
            if (_curchar == '(') constant_parse(inst);
          }

          // Else check it is a local name, add it to the list, then check for more.
          // New: allow hex constants as parameters to an encode method.
          // New: allow parenthesized expressions as parameters.
          // New: allow "primary", "secondary", "tertiary" as parameters.
          // New: allow user-defined register name as parameter.
          else if ((inst._localNames[param] == NULL) &&
                   !ADLParser::is_literal_constant(param) &&
                   (Opcode::as_opcode_type(param) == Opcode::NOT_AN_OPCODE) &&
                   ((_AD._register == NULL) || (_AD._register->getRegDef(param) == NULL))) {
            parse_err(SYNERR, "Using non-locally defined parameter %s for encoding %s.\n", param, ec_name);
            return;
          }
          params->add_entry(param);

          skipws();
          if (_curchar == ',') {
            // More parameters to come.
            next_char();           // Move past ',' between parameters.
            skipws();              // Skip to next parameter.
          } else if (_curchar == ')') {
            // Done with parameter list
          } else {
            // Only ',' or ')' are valid after a parameter name.
            parse_err(SYNERR, "expected ',' or ')' after parameter %s.\n", ec_name);
            return;
          }

        } else {
          skipws();
          // Did not find a parameter.
          if (_curchar == ',') {
            parse_err(SYNERR, "Expected encode parameter before ',' in postalloc_expand %s.\n", ec_name);
            return;
          }
          if (_curchar != ')') {
            parse_err(SYNERR, "Expected ')' after postalloc_expand parameters.\n");
            return;
          }
        }
      } // WHILE loop collecting parameters.
      next_char();                 // Move past ')' at end of parameters.
    } // Done with parameter list for encoding.

    // Check for ',' or ')' after encoding.
    skipws();                      // Move to character after parameters.
    if (_curchar != ')') {
      // Only a ')' is allowed.
      parse_err(SYNERR, "Expected ')' after postalloc_expand %s.\n", ec_name);
      return;
    }
  } // Done parsing postalloc_expand method and their parameters.
  if (_curchar != ')') {
    parse_err(SYNERR, "Missing ')' at end of postalloc_expand description.\n");
    return;
  }
  next_char();                     // Move past ')'.
  skipws();                        // Skip leading whitespace.

  if (_curchar != ';') {
    parse_err(SYNERR, "Missing ';' at end of postalloc_expand.\n");
    return;
  }
  next_char();                     // Move past ';'.
  skipws();                        // Be friendly to oper_parse().

  // Debug Stuff.
  if (_AD._adl_debug > 1) fprintf(stderr, "Instruction postalloc_expand: %s\n", ec_name);

  // Set encode class of this instruction.
  inst._insencode = encrule;
}

3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266

//------------------------------constant_parse---------------------------------
// Parse a constant expression.
void ADLParser::constant_parse(InstructForm& inst) {
  // Create a new encoding name based on the name of the instruction
  // definition, which should be unique.
  const char* prefix = "__constant_";
  char* ec_name = (char*) malloc(strlen(inst._ident) + strlen(prefix) + 1);
  sprintf(ec_name, "%s%s", prefix, inst._ident);

  assert(_AD._encode->encClass(ec_name) == NULL, "shouldn't already exist");
  EncClass* encoding = _AD._encode->add_EncClass(ec_name);
  encoding->_linenum = linenum();

  // synthesize the arguments list for the enc_class from the
  // arguments to the instruct definition.
  const char* param = NULL;
  inst._parameters.reset();
  while ((param = inst._parameters.iter()) != NULL) {
    OperandForm* opForm = (OperandForm*) inst._localNames[param];
    encoding->add_parameter(opForm->_ident, param);
  }

  // Parse the following ( ) expression.
  constant_parse_expression(encoding, ec_name);

  // Build an encoding rule which invokes the encoding rule we just
  // created, passing all arguments that we received.
  InsEncode*   encrule = new InsEncode(); // Encode class for instruction
  NameAndList* params  = encrule->add_encode(ec_name);
  inst._parameters.reset();
  while ((param = inst._parameters.iter()) != NULL) {
    params->add_entry(param);
  }

  // Set encode class of this instruction.
  inst._constant = encrule;
}


//------------------------------constant_parse_expression----------------------
void ADLParser::constant_parse_expression(EncClass* encoding, char* ec_name) {
  skipws();

  // Prepend location descriptor, for debugging; cf. ADLParser::find_cpp_block
  if (_AD._adlocation_debug) {
    encoding->add_code(get_line_string());
  }

  // Start code line.
  encoding->add_code("    _constant = C->constant_table().add");

  // Parse everything in ( ) expression.
3267
  encoding->add_code("(this, ");
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281
  next_char();  // Skip '('
  int parens_depth = 1;

  // Collect the parts of the constant expression.
  // (1) strings that are passed through to output
  // (2) replacement/substitution variable, preceeded by a '$'
  while (parens_depth > 0) {
    if (_curchar == '(') {
      parens_depth++;
      encoding->add_code("(");
      next_char();
    }
    else if (_curchar == ')') {
      parens_depth--;
3282 3283
      if (parens_depth > 0)
        encoding->add_code(")");
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309
      next_char();
    }
    else {
      // (1)
      // Check if there is a string to pass through to output
      char *start = _ptr;  // Record start of the next string
      while ((_curchar != '$') && (_curchar != '(') && (_curchar != ')')) {
        next_char();
      }
      // If a string was found, terminate it and record in EncClass
      if (start != _ptr) {
        *_ptr = '\0';  // Terminate the string
        encoding->add_code(start);
      }

      // (2)
      // If we are at a replacement variable, copy it and record in EncClass.
      if (_curchar == '$') {
        // Found replacement Variable
        char* rep_var = get_rep_var_ident_dup();
        encoding->add_rep_var(rep_var);
      }
    }
  }

  // Finish code line.
3310
  encoding->add_code(");");
3311 3312 3313 3314 3315 3316 3317

  if (_AD._adlocation_debug) {
    encoding->add_code(end_line_marker());
  }

  // Debug Stuff
  if (_AD._adl_debug > 1)  fprintf(stderr, "EncodingClass Form: %s\n", ec_name);
D
duke 已提交
3318 3319 3320 3321
}


//------------------------------size_parse-----------------------------------
K
kvn 已提交
3322 3323 3324
// Parse a 'size(<expr>)' attribute which specifies the size of the
// emitted instructions in bytes. <expr> can be a C++ expression,
// e.g. a constant.
D
duke 已提交
3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
char* ADLParser::size_parse(InstructForm *instr) {
  char* sizeOfInstr = NULL;

  // Get value of the instruction's size
  skipws();

  // Parse size
  sizeOfInstr = get_paren_expr("size expression");
  if (sizeOfInstr == NULL) {
     parse_err(SYNERR, "size of opcode expected at %c\n", _curchar);
     return NULL;
  }

  skipws();

  // Check for terminator
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in ins_attrib definition\n");
    return NULL;
  }
  next_char();                     // Advance past the ';'
  skipws();                        // necessary for instr_parse()

  // Debug Stuff
  if (_AD._adl_debug > 1) {
    if (sizeOfInstr != NULL) {
      fprintf(stderr,"size of opcode: %s\n", sizeOfInstr);
    }
  }

  return sizeOfInstr;
}


//------------------------------opcode_parse-----------------------------------
Opcode * ADLParser::opcode_parse(InstructForm *instr) {
  char *primary   = NULL;
  char *secondary = NULL;
  char *tertiary  = NULL;

  char   *val    = NULL;
  Opcode *opcode = NULL;

  // Get value of the instruction's opcode
  skipws();
  if (_curchar != '(') {         // Check for parenthesized operand list
    parse_err(SYNERR, "missing '(' in expand instruction declaration\n");
    return NULL;
  }
  next_char();                   // skip open paren
  skipws();
  if (_curchar != ')') {
    // Parse primary, secondary, and tertiary opcodes, if provided.
    if ( ((primary = get_ident_or_literal_constant("primary opcode")) == NULL) ) {
        parse_err(SYNERR, "primary hex opcode expected at %c\n", _curchar);
        return NULL;
    }
    skipws();
    if (_curchar == ',') {
      next_char();
      skipws();
      // Parse secondary opcode
      if ( ((secondary = get_ident_or_literal_constant("secondary opcode")) == NULL) ) {
        parse_err(SYNERR, "secondary hex opcode expected at %c\n", _curchar);
        return NULL;
      }
      skipws();
      if (_curchar == ',') {
        next_char();
        skipws();
        // Parse tertiary opcode
        if ( ((tertiary = get_ident_or_literal_constant("tertiary opcode")) == NULL) ) {
          parse_err(SYNERR,"tertiary hex opcode expected at %c\n", _curchar);
          return NULL;
        }
        skipws();
      }
    }
    skipws();
    if (_curchar != ')') {
      parse_err(SYNERR, "Missing ')' in opcode description\n");
      return NULL;
    }
  }
  next_char();                     // Skip ')'
  skipws();
  // Check for terminator
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in ins_attrib definition\n");
    return NULL;
  }
  next_char();                     // Advance past the ';'
  skipws();                        // necessary for instr_parse()

  // Debug Stuff
  if (_AD._adl_debug > 1) {
    if (primary   != NULL) fprintf(stderr,"primary   opcode: %s\n", primary);
    if (secondary != NULL) fprintf(stderr,"secondary opcode: %s\n", secondary);
    if (tertiary  != NULL) fprintf(stderr,"tertiary  opcode: %s\n", tertiary);
  }

  // Generate new object and return
  opcode = new Opcode(primary, secondary, tertiary);
  return opcode;
}


//------------------------------interface_parse--------------------------------
Interface *ADLParser::interface_parse(void) {
  char *iface_name  = NULL;      // Name of interface class being used
  char *iface_code  = NULL;      // Describe components of this class

  // Get interface class name
  skipws();                       // Skip whitespace
  if (_curchar != '(') {
    parse_err(SYNERR, "Missing '(' at start of interface description.\n");
    return NULL;
  }
  next_char();                    // move past '('
  skipws();
  iface_name = get_ident();
  if (iface_name == NULL) {
    parse_err(SYNERR, "missing interface name after 'interface'.\n");
    return NULL;
  }
  skipws();
  if (_curchar != ')') {
    parse_err(SYNERR, "Missing ')' after name of interface.\n");
    return NULL;
  }
  next_char();                    // move past ')'

  // Get details of the interface,
  // for the type of interface indicated by iface_name.
  Interface *inter = NULL;
  skipws();
  if ( _curchar != ';' ) {
    if ( strcmp(iface_name,"MEMORY_INTER") == 0 ) {
      inter = mem_interface_parse();
    }
    else if ( strcmp(iface_name,"COND_INTER") == 0 ) {
      inter = cond_interface_parse();
    }
    // The parse routines consume the "%}"

    // Check for probable extra ';' after defining block.
    if ( _curchar == ';' ) {
      parse_err(SYNERR, "Extra ';' after defining interface block.\n");
      next_char();                // Skip ';'
      return NULL;
    }
  } else {
    next_char();                  // move past ';'

    // Create appropriate interface object
    if ( strcmp(iface_name,"REG_INTER") == 0 ) {
      inter = new RegInterface();
    }
    else if ( strcmp(iface_name,"CONST_INTER") == 0 ) {
      inter = new ConstInterface();
    }
  }
  skipws();                       // be friendly to oper_parse()
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Interface Form: %s\n", iface_name);

  // Create appropriate interface object and return.
  return inter;
}


//------------------------------mem_interface_parse----------------------------
Interface *ADLParser::mem_interface_parse(void) {
  // Fields for MemInterface
  char *base        = NULL;
  char *index       = NULL;
  char *scale       = NULL;
  char *disp        = NULL;

  if (_curchar != '%') {
3505
    parse_err(SYNERR, "Missing '%%{' for 'interface' block.\n");
D
duke 已提交
3506 3507 3508 3509
    return NULL;
  }
  next_char();                  // Skip '%'
  if (_curchar != '{') {
3510
    parse_err(SYNERR, "Missing '%%{' for 'interface' block.\n");
D
duke 已提交
3511 3512 3513 3514 3515 3516 3517
    return NULL;
  }
  next_char();                  // Skip '{'
  skipws();
  do {
    char *field = get_ident();
    if (field == NULL) {
3518
      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
D
duke 已提交
3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
      return NULL;
    }
    if ( strcmp(field,"base") == 0 ) {
      base  = interface_field_parse();
    }
    else if ( strcmp(field,"index") == 0 ) {
      index = interface_field_parse();
    }
    else if ( strcmp(field,"scale") == 0 ) {
      scale = interface_field_parse();
    }
    else if ( strcmp(field,"disp") == 0 ) {
      disp  = interface_field_parse();
    }
    else {
3534
      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
D
duke 已提交
3535 3536 3537 3538 3539
      return NULL;
    }
  } while( _curchar != '%' );
  next_char();                  // Skip '%'
  if ( _curchar != '}' ) {
3540
    parse_err(SYNERR, "Missing '%%}' for 'interface' block.\n");
D
duke 已提交
3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
    return NULL;
  }
  next_char();                  // Skip '}'

  // Construct desired object and return
  Interface *inter = new MemInterface(base, index, scale, disp);
  return inter;
}


//------------------------------cond_interface_parse---------------------------
Interface *ADLParser::cond_interface_parse(void) {
  char *equal;
  char *not_equal;
  char *less;
  char *greater_equal;
  char *less_equal;
  char *greater;
3559 3560
  char *overflow;
  char *no_overflow;
3561 3562 3563 3564 3565 3566
  const char *equal_format = "eq";
  const char *not_equal_format = "ne";
  const char *less_format = "lt";
  const char *greater_equal_format = "ge";
  const char *less_equal_format = "le";
  const char *greater_format = "gt";
3567 3568
  const char *overflow_format = "o";
  const char *no_overflow_format = "no";
D
duke 已提交
3569 3570

  if (_curchar != '%') {
3571
    parse_err(SYNERR, "Missing '%%{' for 'cond_interface' block.\n");
D
duke 已提交
3572 3573 3574 3575
    return NULL;
  }
  next_char();                  // Skip '%'
  if (_curchar != '{') {
3576
    parse_err(SYNERR, "Missing '%%{' for 'cond_interface' block.\n");
D
duke 已提交
3577 3578 3579 3580 3581 3582 3583
    return NULL;
  }
  next_char();                  // Skip '{'
  skipws();
  do {
    char *field = get_ident();
    if (field == NULL) {
3584
      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
D
duke 已提交
3585 3586 3587
      return NULL;
    }
    if ( strcmp(field,"equal") == 0 ) {
3588
      equal  = interface_field_parse(&equal_format);
D
duke 已提交
3589 3590
    }
    else if ( strcmp(field,"not_equal") == 0 ) {
3591
      not_equal = interface_field_parse(&not_equal_format);
D
duke 已提交
3592 3593
    }
    else if ( strcmp(field,"less") == 0 ) {
3594
      less = interface_field_parse(&less_format);
D
duke 已提交
3595 3596
    }
    else if ( strcmp(field,"greater_equal") == 0 ) {
3597
      greater_equal  = interface_field_parse(&greater_equal_format);
D
duke 已提交
3598 3599
    }
    else if ( strcmp(field,"less_equal") == 0 ) {
3600
      less_equal = interface_field_parse(&less_equal_format);
D
duke 已提交
3601 3602
    }
    else if ( strcmp(field,"greater") == 0 ) {
3603
      greater = interface_field_parse(&greater_format);
D
duke 已提交
3604
    }
3605 3606 3607 3608 3609 3610
    else if ( strcmp(field,"overflow") == 0 ) {
      overflow = interface_field_parse(&overflow_format);
    }
    else if ( strcmp(field,"no_overflow") == 0 ) {
      no_overflow = interface_field_parse(&no_overflow_format);
    }
D
duke 已提交
3611
    else {
3612
      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
D
duke 已提交
3613 3614 3615 3616 3617
      return NULL;
    }
  } while( _curchar != '%' );
  next_char();                  // Skip '%'
  if ( _curchar != '}' ) {
3618
    parse_err(SYNERR, "Missing '%%}' for 'interface' block.\n");
D
duke 已提交
3619 3620 3621 3622 3623
    return NULL;
  }
  next_char();                  // Skip '}'

  // Construct desired object and return
3624 3625 3626 3627 3628
  Interface *inter = new CondInterface(equal,         equal_format,
                                       not_equal,     not_equal_format,
                                       less,          less_format,
                                       greater_equal, greater_equal_format,
                                       less_equal,    less_equal_format,
3629 3630 3631
                                       greater,       greater_format,
                                       overflow,      overflow_format,
                                       no_overflow,   no_overflow_format);
D
duke 已提交
3632 3633 3634 3635 3636
  return inter;
}


//------------------------------interface_field_parse--------------------------
3637
char *ADLParser::interface_field_parse(const char ** format) {
D
duke 已提交
3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
  char *iface_field = NULL;

  // Get interface field
  skipws();                      // Skip whitespace
  if (_curchar != '(') {
    parse_err(SYNERR, "Missing '(' at start of interface field.\n");
    return NULL;
  }
  next_char();                   // move past '('
  skipws();
  if ( _curchar != '0' && _curchar != '$' ) {
    parse_err(SYNERR, "missing or invalid interface field contents.\n");
    return NULL;
  }
  iface_field = get_rep_var_ident();
  if (iface_field == NULL) {
    parse_err(SYNERR, "missing or invalid interface field contents.\n");
    return NULL;
  }
  skipws();
3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
  if (format != NULL && _curchar == ',') {
    next_char();
    skipws();
    if (_curchar != '"') {
      parse_err(SYNERR, "Missing '\"' in field format .\n");
      return NULL;
    }
    next_char();
    char *start = _ptr;       // Record start of the next string
    while ((_curchar != '"') && (_curchar != '%') && (_curchar != '\n')) {
      if (_curchar == '\\')  next_char();  // superquote
      if (_curchar == '\n')  parse_err(SYNERR, "newline in string");  // unimplemented!
      next_char();
    }
    if (_curchar != '"') {
      parse_err(SYNERR, "Missing '\"' at end of field format .\n");
      return NULL;
    }
    // If a string was found, terminate it and record in FormatRule
    if ( start != _ptr ) {
      *_ptr  = '\0';          // Terminate the string
      *format = start;
    }
    next_char();
    skipws();
  }
D
duke 已提交
3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718
  if (_curchar != ')') {
    parse_err(SYNERR, "Missing ')' after interface field.\n");
    return NULL;
  }
  next_char();                   // move past ')'
  skipws();
  if ( _curchar != ';' ) {
    parse_err(SYNERR, "Missing ';' at end of interface field.\n");
    return NULL;
  }
  next_char();                    // move past ';'
  skipws();                       // be friendly to interface_parse()

  return iface_field;
}


//------------------------------match_parse------------------------------------
MatchRule *ADLParser::match_parse(FormDict &operands) {
  MatchRule *match;               // Match Rule class for instruction/operand
  char      *cnstr = NULL;        // Code for constructor
  int        depth = 0;           // Counter for matching parentheses
  int        numleaves = 0;       // Counter for number of leaves in rule

  // Parse the match rule tree
  MatchNode *mnode = matchNode_parse(operands, depth, numleaves, true);

  // Either there is a block with a constructor, or a ';' here
  skipws();                       // Skip whitespace
  if ( _curchar == ';' ) {        // Semicolon is valid terminator
    cnstr = NULL;                 // no constructor for this form
    next_char();                  // Move past the ';', replaced with '\0'
  }
  else if ((cnstr = find_cpp_block("match constructor")) == NULL ) {
    parse_err(SYNERR, "invalid construction of match rule\n"
3719
              "Missing ';' or invalid '%%{' and '%%}' constructor\n");
D
duke 已提交
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
    return NULL;                  // No MatchRule to return
  }
  if (_AD._adl_debug > 1)
    if (cnstr) fprintf(stderr,"Match Constructor: %s\n", cnstr);
  // Build new MatchRule object
  match = new MatchRule(_AD, mnode, depth, cnstr, numleaves);
  skipws();                       // Skip any trailing whitespace
  return match;                   // Return MatchRule object
}

//------------------------------format_parse-----------------------------------
FormatRule* ADLParser::format_parse(void) {
  char       *desc   = NULL;
  FormatRule *format = (new FormatRule(desc));

  // Without expression form, MUST have a code block;
  skipws();                       // Skip whitespace
  if ( _curchar == ';' ) {        // Semicolon is valid terminator
    desc  = NULL;                 // no constructor for this form
    next_char();                  // Move past the ';', replaced with '\0'
  }
  else if ( _curchar == '%' && *(_ptr+1) == '{') {
    next_char();                  // Move past the '%'
    next_char();                  // Move past the '{'

    skipws();
3746 3747 3748 3749 3750 3751
    if (_curchar == '$') {
      char* ident = get_rep_var_ident();
      if (strcmp(ident, "$$template") == 0) return template_parse();
      parse_err(SYNERR, "Unknown \"%s\" directive in format", ident);
      return NULL;
    }
D
duke 已提交
3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
    // Check for the opening '"' inside the format description
    if ( _curchar == '"' ) {
      next_char();              // Move past the initial '"'
      if( _curchar == '"' ) {   // Handle empty format string case
        *_ptr = '\0';           // Terminate empty string
        format->_strings.addName(_ptr);
      }

      // Collect the parts of the format description
      // (1) strings that are passed through to tty->print
      // (2) replacement/substitution variable, preceeded by a '$'
      // (3) multi-token ANSIY C style strings
      while ( true ) {
        if ( _curchar == '%' || _curchar == '\n' ) {
          if ( _curchar != '"' ) {
            parse_err(SYNERR, "missing '\"' at end of format block");
            return NULL;
          }
        }

        // (1)
        // Check if there is a string to pass through to output
        char *start = _ptr;       // Record start of the next string
        while ((_curchar != '$') && (_curchar != '"') && (_curchar != '%') && (_curchar != '\n')) {
3776 3777 3778 3779 3780 3781
          if (_curchar == '\\') {
            next_char();  // superquote
            if ((_curchar == '$') || (_curchar == '%'))
              // hack to avoid % escapes and warnings about undefined \ escapes
              *(_ptr-1) = _curchar;
          }
D
duke 已提交
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
          if (_curchar == '\n')  parse_err(SYNERR, "newline in string");  // unimplemented!
          next_char();
        }
        // If a string was found, terminate it and record in FormatRule
        if ( start != _ptr ) {
          *_ptr  = '\0';          // Terminate the string
          format->_strings.addName(start);
        }

        // (2)
        // If we are at a replacement variable,
        // copy it and record in FormatRule
        if ( _curchar == '$' ) {
          next_char();          // Move past the '$'
          char* rep_var = get_ident(); // Nil terminate the variable name
          rep_var = strdup(rep_var);// Copy the string
          *_ptr   = _curchar;     // and replace Nil with original character
          format->_rep_vars.addName(rep_var);
          // Add flag to _strings list indicating we should check _rep_vars
          format->_strings.addName(NameList::_signal);
        }

        // (3)
        // Allow very long strings to be broken up,
        // using the ANSI C syntax "foo\n" <newline> "bar"
        if ( _curchar == '"') {
          next_char();           // Move past the '"'
          skipws();              // Skip white space before next string token
          if ( _curchar != '"') {
            break;
          } else {
            // Found one.  Skip both " and the whitespace in between.
            next_char();
          }
        }
      } // end while part of format description

      // Check for closing '"' and '%}' in format description
      skipws();                   // Move to closing '%}'
      if ( _curchar != '%' ) {
3822
        parse_err(SYNERR, "non-blank characters between closing '\"' and '%%' in format");
D
duke 已提交
3823 3824 3825 3826 3827 3828 3829
        return NULL;
      }
    } // Done with format description inside

    skipws();
    // Past format description, at '%'
    if ( _curchar != '%' || *(_ptr+1) != '}' ) {
3830
      parse_err(SYNERR, "missing '%%}' at end of format block");
D
duke 已提交
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
      return NULL;
    }
    next_char();                  // Move past the '%'
    next_char();                  // Move past the '}'
  }
  else {  // parameter list alone must terminate with a ';'
    parse_err(SYNERR, "missing ';' after Format expression");
    return NULL;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Format Rule: %s\n", desc);

  skipws();
  return format;
}


3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
//------------------------------template_parse-----------------------------------
FormatRule* ADLParser::template_parse(void) {
  char       *desc   = NULL;
  FormatRule *format = (new FormatRule(desc));

  skipws();
  while ( (_curchar != '%') && (*(_ptr+1) != '}') ) {

    // (1)
    // Check if there is a string to pass through to output
3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874
    {
      char *start = _ptr;       // Record start of the next string
      while ((_curchar != '$') && ((_curchar != '%') || (*(_ptr+1) != '}')) ) {
        // If at the start of a comment, skip past it
        if( (_curchar == '/') && ((*(_ptr+1) == '/') || (*(_ptr+1) == '*')) ) {
          skipws_no_preproc();
        } else {
          // ELSE advance to the next character, or start of the next line
          next_char_or_line();
        }
      }
      // If a string was found, terminate it and record in EncClass
      if ( start != _ptr ) {
        *_ptr  = '\0';          // Terminate the string
        // Add flag to _strings list indicating we should check _rep_vars
        format->_strings.addName(NameList::_signal2);
        format->_strings.addName(start);
3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925
      }
    }

    // (2)
    // If we are at a replacement variable,
    // copy it and record in EncClass
    if ( _curchar == '$' ) {
      // Found replacement Variable
      char *rep_var = get_rep_var_ident_dup();
      if (strcmp(rep_var, "$emit") == 0) {
        // switch to normal format parsing
        next_char();
        next_char();
        skipws();
        // Check for the opening '"' inside the format description
        if ( _curchar == '"' ) {
          next_char();              // Move past the initial '"'
          if( _curchar == '"' ) {   // Handle empty format string case
            *_ptr = '\0';           // Terminate empty string
            format->_strings.addName(_ptr);
          }

          // Collect the parts of the format description
          // (1) strings that are passed through to tty->print
          // (2) replacement/substitution variable, preceeded by a '$'
          // (3) multi-token ANSIY C style strings
          while ( true ) {
            if ( _curchar == '%' || _curchar == '\n' ) {
              parse_err(SYNERR, "missing '\"' at end of format block");
              return NULL;
            }

            // (1)
            // Check if there is a string to pass through to output
            char *start = _ptr;       // Record start of the next string
            while ((_curchar != '$') && (_curchar != '"') && (_curchar != '%') && (_curchar != '\n')) {
              if (_curchar == '\\')  next_char();  // superquote
              if (_curchar == '\n')  parse_err(SYNERR, "newline in string");  // unimplemented!
              next_char();
            }
            // If a string was found, terminate it and record in FormatRule
            if ( start != _ptr ) {
              *_ptr  = '\0';          // Terminate the string
              format->_strings.addName(start);
            }

            // (2)
            // If we are at a replacement variable,
            // copy it and record in FormatRule
            if ( _curchar == '$' ) {
              next_char();          // Move past the '$'
3926 3927
              char* next_rep_var = get_ident(); // Nil terminate the variable name
              next_rep_var = strdup(next_rep_var);// Copy the string
3928
              *_ptr   = _curchar;     // and replace Nil with original character
3929
              format->_rep_vars.addName(next_rep_var);
3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960
              // Add flag to _strings list indicating we should check _rep_vars
              format->_strings.addName(NameList::_signal);
            }

            // (3)
            // Allow very long strings to be broken up,
            // using the ANSI C syntax "foo\n" <newline> "bar"
            if ( _curchar == '"') {
              next_char();           // Move past the '"'
              skipws();              // Skip white space before next string token
              if ( _curchar != '"') {
                break;
              } else {
                // Found one.  Skip both " and the whitespace in between.
                next_char();
              }
            }
          } // end while part of format description
        }
      } else {
        // Add flag to _strings list indicating we should check _rep_vars
        format->_rep_vars.addName(rep_var);
        // Add flag to _strings list indicating we should check _rep_vars
        format->_strings.addName(NameList::_signal3);
      }
    } // end while part of format description
  }

  skipws();
  // Past format description, at '%'
  if ( _curchar != '%' || *(_ptr+1) != '}' ) {
3961
    parse_err(SYNERR, "missing '%%}' at end of format block");
3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
    return NULL;
  }
  next_char();                  // Move past the '%'
  next_char();                  // Move past the '}'

  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Format Rule: %s\n", desc);

  skipws();
  return format;
}


D
duke 已提交
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
//------------------------------effect_parse-----------------------------------
void ADLParser::effect_parse(InstructForm *instr) {
  char* desc   = NULL;

  skipws();                      // Skip whitespace
  if (_curchar != '(') {
    parse_err(SYNERR, "missing '(' in effect definition\n");
    return;
  }
  // Get list of effect-operand pairs and insert into dictionary
3985
  else get_effectlist(instr->_effects, instr->_localNames, instr->_has_call);
D
duke 已提交
3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001

  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Effect description: %s\n", desc);
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in Effect definition\n");
  }
  next_char();                  // Skip ';'

}

//------------------------------expand_parse-----------------------------------
ExpandRule* ADLParser::expand_parse(InstructForm *instr) {
  char         *ident, *ident2;
  NameAndList  *instr_and_operands = NULL;
  ExpandRule   *exp = new ExpandRule();

4002 4003
  // Expand is a block containing an ordered list of operands with initializers,
  // or instructions, each of which has an ordered list of operands.
D
duke 已提交
4004 4005 4006 4007
  // Check for block delimiter
  skipws();                        // Skip leading whitespace
  if ((_curchar != '%')
      || (next_char(), (_curchar != '{')) ) { // If not open block
4008
    parse_err(SYNERR, "missing '%%{' in expand definition\n");
D
duke 已提交
4009 4010 4011 4012 4013 4014 4015 4016
    return(NULL);
  }
  next_char();                     // Maintain the invariant
  do {
    ident = get_ident();           // Grab next identifier
    if (ident == NULL) {
      parse_err(SYNERR, "identifier expected at %c\n", _curchar);
      continue;
4017 4018 4019
    }

    // Check whether we should parse an instruction or operand.
D
duke 已提交
4020
    const Form *form = _globalNames[ident];
4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038
    bool parse_oper = false;
    bool parse_ins  = false;
    if (form == NULL) {
      skipws();
      // Check whether this looks like an instruction specification.  If so,
      // just parse the instruction.  The declaration of the instruction is
      // not needed here.
      if (_curchar == '(') parse_ins = true;
    } else if (form->is_instruction()) {
      parse_ins = true;
    } else if (form->is_operand()) {
      parse_oper = true;
    } else {
      parse_err(SYNERR, "instruction/operand name expected at %s\n", ident);
      continue;
    }

    if (parse_oper) {
D
duke 已提交
4039
      // This is a new operand
4040
      OperandForm *oper = form->is_operand();
D
duke 已提交
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074
      if (oper == NULL) {
        parse_err(SYNERR, "instruction/operand name expected at %s\n", ident);
        continue;
      }
      // Throw the operand on the _newopers list
      skipws();
      ident = get_unique_ident(instr->_localNames,"Operand");
      if (ident == NULL) {
        parse_err(SYNERR, "identifier expected at %c\n", _curchar);
        continue;
      }
      exp->_newopers.addName(ident);
      // Add new operand to LocalNames
      instr->_localNames.Insert(ident, oper);
      // Grab any constructor code and save as a string
      char *c = NULL;
      skipws();
      if (_curchar == '%') { // Need a constructor for the operand
        c = find_cpp_block("Operand Constructor");
        if (c == NULL) {
          parse_err(SYNERR, "Invalid code block for operand constructor\n", _curchar);
          continue;
        }
        // Add constructor to _newopconst Dict
        exp->_newopconst.Insert(ident, c);
      }
      else if (_curchar != ';') { // If no constructor, need a ;
        parse_err(SYNERR, "Missing ; in expand rule operand declaration\n");
        continue;
      }
      else next_char(); // Skip the ;
      skipws();
    }
    else {
4075
      assert(parse_ins, "sanity");
D
duke 已提交
4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093
      // Add instruction to list
      instr_and_operands = new NameAndList(ident);
      // Grab operands, build nameList of them, and then put into dictionary
      skipws();
      if (_curchar != '(') {         // Check for parenthesized operand list
        parse_err(SYNERR, "missing '(' in expand instruction declaration\n");
        continue;
      }
      do {
        next_char();                 // skip open paren & comma characters
        skipws();
        if (_curchar == ')') break;
        ident2 = get_ident();
        skipws();
        if (ident2 == NULL) {
          parse_err(SYNERR, "identifier expected at %c\n", _curchar);
          continue;
        }                            // Check that you have a valid operand
4094 4095
        const Form *form2 = instr->_localNames[ident2];
        if (!form2) {
D
duke 已提交
4096 4097 4098
          parse_err(SYNERR, "operand name expected at %s\n", ident2);
          continue;
        }
4099
        OperandForm *oper = form2->is_operand();
4100
        if (oper == NULL && !form2->is_opclass()) {
D
duke 已提交
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
          parse_err(SYNERR, "operand name expected at %s\n", ident2);
          continue;
        }                            // Add operand to list
        instr_and_operands->add_entry(ident2);
      } while(_curchar == ',');
      if (_curchar != ')') {
        parse_err(SYNERR, "missing ')'in expand instruction declaration\n");
        continue;
      }
      next_char();
      if (_curchar != ';') {
        parse_err(SYNERR, "missing ';'in expand instruction declaration\n");
        continue;
      }
      next_char();

      // Record both instruction name and its operand list
      exp->add_instruction(instr_and_operands);

      skipws();
    }

  } while(_curchar != '%');
  next_char();
  if (_curchar != '}') {
4126
    parse_err(SYNERR, "missing '%%}' in expand rule definition\n");
D
duke 已提交
4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334
    return(NULL);
  }
  next_char();

  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Expand Rule:\n");

  skipws();
  return (exp);
}

//------------------------------rewrite_parse----------------------------------
RewriteRule* ADLParser::rewrite_parse(void) {
  char* params = NULL;
  char* desc   = NULL;


  // This feature targeted for second generation description language.

  skipws();                      // Skip whitespace
  // Get parameters for rewrite
  if ((params = get_paren_expr("rewrite parameters")) == NULL) {
    parse_err(SYNERR, "missing '(' in rewrite rule\n");
    return NULL;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Rewrite parameters: %s\n", params);

  // For now, grab entire block;
  skipws();
  if ( (desc = find_cpp_block("rewrite block")) == NULL ) {
    parse_err(SYNERR, "incorrect or missing block for 'rewrite'.\n");
    return NULL;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Rewrite Rule: %s\n", desc);

  skipws();
  return (new RewriteRule(params,desc));
}

//------------------------------attr_parse-------------------------------------
Attribute *ADLParser::attr_parse(char* ident) {
  Attribute *attrib;              // Attribute class
  char      *cost = NULL;         // String representation of cost attribute

  skipws();                       // Skip leading whitespace
  if ( (cost = get_paren_expr("attribute")) == NULL ) {
    parse_err(SYNERR, "incorrect or missing expression for 'attribute'\n");
    return NULL;
  }
  // Debug Stuff
  if (_AD._adl_debug > 1) fprintf(stderr,"Attribute: %s\n", cost);
  if (_curchar != ';') {
    parse_err(SYNERR, "missing ';' in attribute definition\n");
    return NULL;
  }
  next_char();                   // Point after the terminator

  skipws();
  attrib = new Attribute(ident,cost,INS_ATTR); // Build new predicate object
  return attrib;
}


//------------------------------matchNode_parse--------------------------------
MatchNode *ADLParser::matchNode_parse(FormDict &operands, int &depth, int &numleaves, bool atroot) {
  // Count depth of parenthesis nesting for both left and right children
  int   lParens = depth;
  int   rParens = depth;

  // MatchNode objects for left, right, and root of subtree.
  MatchNode *lChild = NULL;
  MatchNode *rChild = NULL;
  char      *token;               // Identifier which may be opcode or operand

  // Match expression starts with a '('
  if (cur_char() != '(')
    return NULL;

  next_char();                    // advance past '('

  // Parse the opcode
  token = get_ident();            // Get identifier, opcode
  if (token == NULL) {
    parse_err(SYNERR, "missing opcode in match expression\n");
    return NULL;
  }

  // Take note if we see one of a few special operations - those that are
  // treated differently on different architectures in the sense that on
  // one architecture there is a match rule and on another there isn't (so
  // a call will eventually be generated).

  for (int i = _last_machine_leaf + 1; i < _last_opcode; i++) {
    if (strcmp(token, NodeClassNames[i]) == 0) {
      _AD.has_match_rule(i, true);
    }
  }

  // Lookup the root value in the operands dict to perform substitution
  const char  *result    = NULL;  // Result type will be filled in later
  const char  *name      = token; // local name associated with this node
  const char  *operation = token; // remember valid operation for later
  const Form  *form      = operands[token];
  OpClassForm *opcForm = form ? form->is_opclass() : NULL;
  if (opcForm != NULL) {
    // If this token is an entry in the local names table, record its type
    if (!opcForm->ideal_only()) {
      operation = opcForm->_ident;
      result = operation;         // Operands result in their own type
    }
    // Otherwise it is an ideal type, and so, has no local name
    else                        name = NULL;
  }

  // Parse the operands
  skipws();
  if (cur_char() != ')') {

    // Parse the left child
    if (strcmp(operation,"Set"))
      lChild = matchChild_parse(operands, lParens, numleaves, false);
    else
      lChild = matchChild_parse(operands, lParens, numleaves, true);

    skipws();
    if (cur_char() != ')' ) {
      if(strcmp(operation, "Set"))
        rChild = matchChild_parse(operands,rParens,numleaves,false);
      else
        rChild = matchChild_parse(operands,rParens,numleaves,true);
    }
  }

  // Check for required ')'
  skipws();
  if (cur_char() != ')') {
    parse_err(SYNERR, "missing ')' in match expression\n");
    return NULL;
  }
  next_char();                    // skip the ')'

  MatchNode* mroot = new MatchNode(_AD,result,name,operation,lChild,rChild);

  // If not the root, reduce this subtree to an internal operand
  if (!atroot) {
    mroot->build_internalop();
  }
  // depth is greater of left and right paths.
  depth = (lParens > rParens) ? lParens : rParens;

  return mroot;
}


//------------------------------matchChild_parse-------------------------------
MatchNode *ADLParser::matchChild_parse(FormDict &operands, int &parens, int &numleaves, bool atroot) {
  MatchNode  *child  = NULL;
  const char *result = NULL;
  const char *token  = NULL;
  const char *opType = NULL;

  if (cur_char() == '(') {         // child is an operation
    ++parens;
    child = matchNode_parse(operands, parens, numleaves, atroot);
  }
  else {                           // child is an operand
    token = get_ident();
    const Form  *form    = operands[token];
    OpClassForm *opcForm = form ? form->is_opclass() : NULL;
    if (opcForm != NULL) {
      opType = opcForm->_ident;
      result = opcForm->_ident;    // an operand's result matches its type
    } else {
      parse_err(SYNERR, "undefined operand %s in match rule\n", token);
      return NULL;
    }

    if (opType == NULL) {
      parse_err(SYNERR, "missing type for argument '%s'\n", token);
    }

    child = new MatchNode(_AD, result, token, opType);
    ++numleaves;
  }

  return child;
}



// ******************** Private Utility Functions *************************


char* ADLParser::find_cpp_block(const char* description) {
  char *next;                     // Pointer for finding block delimiters
  char* cppBlock = NULL;          // Beginning of C++ code block

  if (_curchar == '%') {          // Encoding is a C++ expression
    next_char();
    if (_curchar != '{') {
      parse_err(SYNERR, "missing '{' in %s \n", description);
      return NULL;
    }
    next_char();                  // Skip block delimiter
    skipws_no_preproc();          // Skip leading whitespace
    cppBlock = _ptr;              // Point to start of expression
4335
    int line = linenum();
D
duke 已提交
4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349
    next = _ptr + 1;
    while(((_curchar != '%') || (*next != '}')) && (_curchar != '\0')) {
      next_char_or_line();
      next = _ptr+1;              // Maintain the next pointer
    }                             // Grab string
    if (_curchar == '\0') {
      parse_err(SYNERR, "invalid termination of %s \n", description);
      return NULL;
    }
    *_ptr = '\0';                 // Terminate string
    _ptr += 2;                    // Skip block delimiter
    _curchar = *_ptr;             // Maintain invariant

    // Prepend location descriptor, for debugging.
4350 4351 4352 4353 4354 4355 4356 4357 4358 4359
    if (_AD._adlocation_debug) {
      char* location = get_line_string(line);
      char* end_loc  = end_line_marker();
      char* result = (char *)malloc(strlen(location) + strlen(cppBlock) + strlen(end_loc) + 1);
      strcpy(result, location);
      strcat(result, cppBlock);
      strcat(result, end_loc);
      cppBlock = result;
      free(location);
    }
D
duke 已提交
4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428
  }

  return cppBlock;
}

// Move to the closing token of the expression we are currently at,
// as defined by stop_chars.  Match parens and quotes.
char* ADLParser::get_expr(const char *desc, const char *stop_chars) {
  char* expr = NULL;
  int   paren = 0;

  expr = _ptr;
  while (paren > 0 || !strchr(stop_chars, _curchar)) {
    if (_curchar == '(') {        // Down level of nesting
      paren++;                    // Bump the parenthesis counter
      next_char();                // maintain the invariant
    }
    else if (_curchar == ')') {   // Up one level of nesting
      if (paren == 0) {
        // Paren underflow:  We didn't encounter the required stop-char.
        parse_err(SYNERR, "too many )'s, did not find %s after %s\n",
                  stop_chars, desc);
        return NULL;
      }
      paren--;                    // Drop the parenthesis counter
      next_char();                // Maintain the invariant
    }
    else if (_curchar == '"' || _curchar == '\'') {
      int qchar = _curchar;
      while (true) {
        next_char();
        if (_curchar == qchar) { next_char(); break; }
        if (_curchar == '\\')  next_char();  // superquote
        if (_curchar == '\n' || _curchar == '\0') {
          parse_err(SYNERR, "newline in string in %s\n", desc);
          return NULL;
        }
      }
    }
    else if (_curchar == '%' && (_ptr[1] == '{' || _ptr[1] == '}')) {
      // Make sure we do not stray into the next ADLC-level form.
      parse_err(SYNERR, "unexpected %%%c in %s\n", _ptr[1], desc);
      return NULL;
    }
    else if (_curchar == '\0') {
      parse_err(SYNERR, "unexpected EOF in %s\n", desc);
      return NULL;
    }
    else {
      // Always walk over whitespace, comments, preprocessor directives, etc.
      char* pre_skip_ptr = _ptr;
      skipws();
      // If the parser declined to make progress on whitespace,
      // skip the next character, which is therefore NOT whitespace.
      if (pre_skip_ptr == _ptr) {
        next_char();
      } else if (pre_skip_ptr+strlen(pre_skip_ptr) != _ptr+strlen(_ptr)) {
        parse_err(SYNERR, "unimplemented: preprocessor must not elide subexpression in %s", desc);
      }
    }
  }

  assert(strchr(stop_chars, _curchar), "non-null return must be at stop-char");
  *_ptr = '\0';               // Replace ')' or other stop-char with '\0'
  return expr;
}

// Helper function around get_expr
// Sets _curchar to '(' so that get_paren_expr will search for a matching ')'
4429 4430
char *ADLParser::get_paren_expr(const char *description, bool include_location) {
  int line = linenum();
D
duke 已提交
4431 4432 4433 4434 4435 4436
  if (_curchar != '(')            // Escape if not valid starting position
    return NULL;
  next_char();                    // Skip the required initial paren.
  char *token2 = get_expr(description, ")");
  if (_curchar == ')')
    next_char();                  // Skip required final paren.
4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448
  int junk = 0;
  if (include_location && _AD._adlocation_debug && !is_int_token(token2, junk)) {
    // Prepend location descriptor, for debugging.
    char* location = get_line_string(line);
    char* end_loc  = end_line_marker();
    char* result = (char *)malloc(strlen(location) + strlen(token2) + strlen(end_loc) + 1);
    strcpy(result, location);
    strcat(result, token2);
    strcat(result, end_loc);
    token2 = result;
    free(location);
  }
D
duke 已提交
4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473
  return token2;
}

//------------------------------get_ident_common-------------------------------
// Looks for an identifier in the buffer, and turns it into a null terminated
// string(still inside the file buffer).  Returns a pointer to the string or
// NULL if some other token is found instead.
char *ADLParser::get_ident_common(bool do_preproc) {
  register char c;
  char *start;                    // Pointer to start of token
  char *end;                      // Pointer to end of token

  if( _curline == NULL )          // Return NULL at EOF.
    return NULL;

  skipws_common(do_preproc);      // Skip whitespace before identifier
  start = end = _ptr;             // Start points at first character
  end--;                          // unwind end by one to prepare for loop
  do {
    end++;                        // Increment end pointer
    c = *end;                     // Grab character to test
  } while ( ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'))
            || ((c >= '0') && (c <= '9'))
            || ((c == '_')) || ((c == ':')) || ((c == '#')) );
  if (start == end) {             // We popped out on the first try
K
kvn 已提交
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484
    // It can occur that `start' contains the rest of the input file.
    // In this case the output should be truncated.
    if (strlen(start) > 24) {
      char buf[32];
      strncpy(buf, start, 20);
      buf[20] = '\0';
      strcat(buf, "[...]");
      parse_err(SYNERR, "Identifier expected, but found '%s'.", buf);
    } else {
      parse_err(SYNERR, "Identifier expected, but found '%s'.", start);
    }
D
duke 已提交
4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497
    start = NULL;
  }
  else {
    _curchar = c;                 // Save the first character of next token
    *end = '\0';                  // NULL terminate the string in place
  }
  _ptr = end;                     // Reset _ptr to point to next char after token

  // Make sure we do not try to use #defined identifiers.  If start is
  // NULL an error was already reported.
  if (do_preproc && start != NULL) {
    const char* def = _AD.get_preproc_def(start);
    if (def != NULL && strcmp(def, start)) {
4498 4499 4500 4501 4502 4503 4504 4505 4506 4507
      const char* def1 = def;
      const char* def2 = _AD.get_preproc_def(def1);
      // implement up to 2 levels of #define
      if (def2 != NULL && strcmp(def2, def1)) {
        def = def2;
        const char* def3 = _AD.get_preproc_def(def2);
        if (def3 != NULL && strcmp(def3, def2) && strcmp(def3, def1)) {
          parse_err(SYNERR, "unimplemented: using %s defined as %s => %s => %s",
                    start, def1, def2, def3);
        }
D
duke 已提交
4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660
      }
      start = strdup(def);
    }
  }

  return start;                   // Pointer to token in filebuf
}

//------------------------------get_ident_dup----------------------------------
// Looks for an identifier in the buffer, and returns a duplicate
// or NULL if some other token is found instead.
char *ADLParser::get_ident_dup(void) {
  char *ident = get_ident();

  // Duplicate an identifier before returning and restore string.
  if( ident != NULL ) {
    ident = strdup(ident);  // Copy the string
    *_ptr   = _curchar;         // and replace Nil with original character
  }

  return ident;
}

//----------------------get_ident_or_literal_constant--------------------------
// Looks for an identifier in the buffer, or a parenthesized expression.
char *ADLParser::get_ident_or_literal_constant(const char* description) {
  char* param = NULL;
  skipws();
  if (_curchar == '(') {
    // Grab a constant expression.
    param = get_paren_expr(description);
    if (param[0] != '(') {
      char* buf = (char*) malloc(strlen(param) + 3);
      sprintf(buf, "(%s)", param);
      param = buf;
    }
    assert(is_literal_constant(param),
           "expr must be recognizable as a constant");
  } else {
    param = get_ident();
  }
  return param;
}

//------------------------------get_rep_var_ident-----------------------------
// Do NOT duplicate,
// Leave nil terminator in buffer
// Preserve initial '$'(s) in string
char *ADLParser::get_rep_var_ident(void) {
  // Remember starting point
  char *rep_var = _ptr;

  // Check for replacement variable indicator '$' and pass if present
  if ( _curchar == '$' ) {
    next_char();
  }
  // Check for a subfield indicator, a second '$', and pass if present
  if ( _curchar == '$' ) {
    next_char();
  }

  // Check for a control indicator, a third '$':
  if ( _curchar == '$' ) {
    next_char();
  }

  // Check for more than three '$'s in sequence, SYNERR
  if( _curchar == '$' ) {
    parse_err(SYNERR, "Replacement variables and field specifiers can not start with '$$$$'");
    next_char();
    return NULL;
  }

  // Nil terminate the variable name following the '$'
  char *rep_var_name = get_ident();
  assert( rep_var_name != NULL,
          "Missing identifier after replacement variable indicator '$'");

  return rep_var;
}



//------------------------------get_rep_var_ident_dup-------------------------
// Return the next replacement variable identifier, skipping first '$'
// given a pointer into a line of the buffer.
// Null terminates string, still inside the file buffer,
// Returns a pointer to a copy of the string, or NULL on failure
char *ADLParser::get_rep_var_ident_dup(void) {
  if( _curchar != '$' ) return NULL;

  next_char();                // Move past the '$'
  char *rep_var = _ptr;       // Remember starting point

  // Check for a subfield indicator, a second '$':
  if ( _curchar == '$' ) {
    next_char();
  }

  // Check for a control indicator, a third '$':
  if ( _curchar == '$' ) {
    next_char();
  }

  // Check for more than three '$'s in sequence, SYNERR
  if( _curchar == '$' ) {
    parse_err(SYNERR, "Replacement variables and field specifiers can not start with '$$$$'");
    next_char();
    return NULL;
  }

  // Nil terminate the variable name following the '$'
  char *rep_var_name = get_ident();
  assert( rep_var_name != NULL,
          "Missing identifier after replacement variable indicator '$'");
  rep_var = strdup(rep_var);  // Copy the string
  *_ptr   = _curchar;         // and replace Nil with original character

  return rep_var;
}


//------------------------------get_unique_ident------------------------------
// Looks for an identifier in the buffer, terminates it with a NULL,
// and checks that it is unique
char *ADLParser::get_unique_ident(FormDict& dict, const char* nameDescription){
  char* ident = get_ident();

  if (ident == NULL) {
    parse_err(SYNERR, "missing %s identifier at %c\n", nameDescription, _curchar);
  }
  else {
    if (dict[ident] != NULL) {
      parse_err(SYNERR, "duplicate name %s for %s\n", ident, nameDescription);
      ident = NULL;
    }
  }

  return ident;
}


//------------------------------get_int----------------------------------------
// Looks for a character string integer in the buffer, and turns it into an int
// invokes a parse_err if the next token is not an integer.
// This routine does not leave the integer null-terminated.
int ADLParser::get_int(void) {
  register char c;
  char         *start;            // Pointer to start of token
  char         *end;              // Pointer to end of token
  int           result;           // Storage for integer result

  if( _curline == NULL )          // Return NULL at EOF.
4661
    return 0;
D
duke 已提交
4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789

  skipws();                       // Skip whitespace before identifier
  start = end = _ptr;             // Start points at first character
  c = *end;                       // Grab character to test
  while ((c >= '0') && (c <= '9')
         || ((c == '-') && (end == start))) {
    end++;                        // Increment end pointer
    c = *end;                     // Grab character to test
  }
  if (start == end) {             // We popped out on the first try
    parse_err(SYNERR, "integer expected at %c\n", c);
    result = 0;
  }
  else {
    _curchar = c;                 // Save the first character of next token
    *end = '\0';                  // NULL terminate the string in place
    result = atoi(start);         // Convert the string to an integer
    *end = _curchar;              // Restore buffer to original condition
  }

  // Reset _ptr to next char after token
  _ptr = end;

  return result;                   // integer
}


//------------------------------get_relation_dup------------------------------
// Looks for a relational operator in the buffer
// invokes a parse_err if the next token is not a relation
// This routine creates a duplicate of the string in the buffer.
char *ADLParser::get_relation_dup(void) {
  char         *result = NULL;    // relational operator being returned

  if( _curline == NULL )          // Return NULL at EOF.
    return  NULL;

  skipws();                       // Skip whitespace before relation
  char *start = _ptr;             // Store start of relational operator
  char first  = *_ptr;            // the first character
  if( (first == '=') || (first == '!') || (first == '<') || (first == '>') ) {
    next_char();
    char second = *_ptr;          // the second character
    if( (second == '=') ) {
      next_char();
      char tmp  = *_ptr;
      *_ptr = '\0';               // NULL terminate
      result = strdup(start);     // Duplicate the string
      *_ptr = tmp;                // restore buffer
    } else {
      parse_err(SYNERR, "relational operator expected at %s\n", _ptr);
    }
  } else {
    parse_err(SYNERR, "relational operator expected at %s\n", _ptr);
  }

  return result;
}



//------------------------------get_oplist-------------------------------------
// Looks for identifier pairs where first must be the name of an operand, and
// second must be a name unique in the scope of this instruction.  Stores the
// names with a pointer to the OpClassForm of their type in a local name table.
void ADLParser::get_oplist(NameList &parameters, FormDict &operands) {
  OpClassForm *opclass = NULL;
  char        *ident   = NULL;

  do {
    next_char();             // skip open paren & comma characters
    skipws();
    if (_curchar == ')') break;

    // Get operand type, and check it against global name table
    ident = get_ident();
    if (ident == NULL) {
      parse_err(SYNERR, "optype identifier expected at %c\n", _curchar);
      return;
    }
    else {
      const Form  *form = _globalNames[ident];
      if( form == NULL ) {
        parse_err(SYNERR, "undefined operand type %s\n", ident);
        return;
      }

      // Check for valid operand type
      OpClassForm *opc  = form->is_opclass();
      OperandForm *oper = form->is_operand();
      if((oper == NULL) && (opc == NULL)) {
        parse_err(SYNERR, "identifier %s not operand type\n", ident);
        return;
      }
      opclass = opc;
    }
    // Debugging Stuff
    if (_AD._adl_debug > 1) fprintf(stderr, "\tOperand Type: %s\t", ident);

    // Get name of operand and add it to local name table
    if( (ident = get_unique_ident(operands, "operand")) == NULL) {
      return;
    }
    // Parameter names must not be global names.
    if( _globalNames[ident] != NULL ) {
         parse_err(SYNERR, "Reuse of global name %s as operand.\n",ident);
         return;
    }
    operands.Insert(ident, opclass);
    parameters.addName(ident);

    // Debugging Stuff
    if (_AD._adl_debug > 1) fprintf(stderr, "\tOperand Name: %s\n", ident);
    skipws();
  } while(_curchar == ',');

  if (_curchar != ')') parse_err(SYNERR, "missing ')'\n");
  else {
    next_char();  // set current character position past the close paren
  }
}


//------------------------------get_effectlist---------------------------------
// Looks for identifier pairs where first must be the name of a pre-defined,
// effect, and the second must be the name of an operand defined in the
// operand list of this instruction.  Stores the names with a pointer to the
// effect form in a local effects table.
4790
void ADLParser::get_effectlist(FormDict &effects, FormDict &operands, bool& has_call) {
D
duke 已提交
4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822
  OperandForm *opForm;
  Effect      *eForm;
  char        *ident;

  do {
    next_char();             // skip open paren & comma characters
    skipws();
    if (_curchar == ')') break;

    // Get effect type, and check it against global name table
    ident = get_ident();
    if (ident == NULL) {
      parse_err(SYNERR, "effect type identifier expected at %c\n", _curchar);
      return;
    }
    else {
      // Check for valid effect type
      const Form *form = _globalNames[ident];
      if( form == NULL ) {
        parse_err(SYNERR, "undefined effect type %s\n", ident);
        return;
      }
      else {
        if( (eForm = form->is_effect()) == NULL) {
          parse_err(SYNERR, "identifier %s not effect type\n", ident);
          return;
        }
      }
    }
      // Debugging Stuff
    if (_AD._adl_debug > 1) fprintf(stderr, "\tEffect Type: %s\t", ident);
    skipws();
4823 4824 4825 4826 4827 4828 4829 4830
    if (eForm->is(Component::CALL)) {
      if (_AD._adl_debug > 1) fprintf(stderr, "\n");
      has_call = true;
    } else {
      // Get name of operand and check that it is in the local name table
      if( (ident = get_unique_ident(effects, "effect")) == NULL) {
        parse_err(SYNERR, "missing operand identifier in effect list\n");
        return;
D
duke 已提交
4831
      }
4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846
      const Form *form = operands[ident];
      opForm = form ? form->is_operand() : NULL;
      if( opForm == NULL ) {
        if( form && form->is_opclass() ) {
          const char* cname = form->is_opclass()->_ident;
          parse_err(SYNERR, "operand classes are illegal in effect lists (found %s %s)\n", cname, ident);
        } else {
          parse_err(SYNERR, "undefined operand %s in effect list\n", ident);
        }
        return;
      }
      // Add the pair to the effects table
      effects.Insert(ident, eForm);
      // Debugging Stuff
      if (_AD._adl_debug > 1) fprintf(stderr, "\tOperand Name: %s\n", ident);
D
duke 已提交
4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857
    }
    skipws();
  } while(_curchar == ',');

  if (_curchar != ')') parse_err(SYNERR, "missing ')'\n");
  else {
    next_char();  // set current character position past the close paren
  }
}


4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886
//-------------------------------preproc_line----------------------------------
// A "#line" keyword has been seen, so parse the rest of the line.
void ADLParser::preproc_line(void) {
  int line = get_int();
  skipws_no_preproc();
  const char* file = NULL;
  if (_curchar == '"') {
    next_char();              // Move past the initial '"'
    file = _ptr;
    while (true) {
      if (_curchar == '\n') {
        parse_err(SYNERR, "missing '\"' at end of #line directive");
        return;
      }
      if (_curchar == '"') {
        *_ptr  = '\0';          // Terminate the string
        next_char();
        skipws_no_preproc();
        break;
      }
      next_char();
    }
  }
  ensure_end_of_line();
  if (file != NULL)
    _AD._ADL_file._name = file;
  _buf.set_linenum(line);
}

D
duke 已提交
4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918
//------------------------------preproc_define---------------------------------
// A "#define" keyword has been seen, so parse the rest of the line.
void ADLParser::preproc_define(void) {
  char* flag = get_ident_no_preproc();
  skipws_no_preproc();
  // only #define x y is supported for now
  char* def = get_ident_no_preproc();
  _AD.set_preproc_def(flag, def);
  skipws_no_preproc();
  if (_curchar != '\n') {
    parse_err(SYNERR, "non-identifier in preprocessor definition\n");
  }
}

//------------------------------preproc_undef----------------------------------
// An "#undef" keyword has been seen, so parse the rest of the line.
void ADLParser::preproc_undef(void) {
  char* flag = get_ident_no_preproc();
  skipws_no_preproc();
  ensure_end_of_line();
  _AD.set_preproc_def(flag, NULL);
}



//------------------------------parse_err--------------------------------------
// Issue a parser error message, and skip to the end of the current line
void ADLParser::parse_err(int flag, const char *fmt, ...) {
  va_list args;

  va_start(args, fmt);
  if (flag == 1)
4919
    _AD._syntax_errs += _AD.emit_msg(0, flag, linenum(), fmt, args);
D
duke 已提交
4920
  else if (flag == 2)
4921
    _AD._semantic_errs += _AD.emit_msg(0, flag, linenum(), fmt, args);
D
duke 已提交
4922
  else
4923
    _AD._warnings += _AD.emit_msg(0, flag, linenum(), fmt, args);
D
duke 已提交
4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947

  int error_char = _curchar;
  char* error_ptr = _ptr+1;
  for(;*_ptr != '\n'; _ptr++) ; // Skip to the end of the current line
  _curchar = '\n';
  va_end(args);
  _AD._no_output = 1;

  if (flag == 1) {
    char* error_tail = strchr(error_ptr, '\n');
    char tem = *error_ptr;
    error_ptr[-1] = '\0';
    char* error_head = error_ptr-1;
    while (error_head > _curline && *error_head)  --error_head;
    if (error_tail)  *error_tail = '\0';
    fprintf(stderr, "Error Context:  %s>>>%c<<<%s\n",
            error_head, error_char, error_ptr);
    if (error_tail)  *error_tail = '\n';
    error_ptr[-1] = tem;
  }
}

//---------------------------ensure_start_of_line------------------------------
// A preprocessor directive has been encountered.  Be sure it has fallen at
T
twisti 已提交
4948
// the beginning of a line, or else report an error.
D
duke 已提交
4949
void ADLParser::ensure_start_of_line(void) {
4950
  if (_curchar == '\n') { next_line(); return; }
D
duke 已提交
4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118
  assert( _ptr >= _curline && _ptr < _curline+strlen(_curline),
          "Must be able to find which line we are in" );

  for (char *s = _curline; s < _ptr; s++) {
    if (*s > ' ') {
      parse_err(SYNERR, "'%c' must be at beginning of line\n", _curchar);
      break;
    }
  }
}

//---------------------------ensure_end_of_line--------------------------------
// A preprocessor directive has been parsed.  Be sure there is no trailing
// garbage at the end of this line.  Set the scan point to the beginning of
// the next line.
void ADLParser::ensure_end_of_line(void) {
  skipws_no_preproc();
  if (_curchar != '\n' && _curchar != '\0') {
    parse_err(SYNERR, "garbage char '%c' at end of line\n", _curchar);
  } else {
    next_char_or_line();
  }
}

//---------------------------handle_preproc------------------------------------
// The '#' character introducing a preprocessor directive has been found.
// Parse the whole directive name (e.g., #define, #endif) and take appropriate
// action.  If we are in an "untaken" span of text, simply keep track of
// #ifdef nesting structure, so we can find out when to start taking text
// again.  (In this state, we "sort of support" C's #if directives, enough
// to disregard their associated #else and #endif lines.)  If we are in a
// "taken" span of text, there are two cases:  "#define" and "#undef"
// directives are preserved and passed up to the caller, which eventually
// passes control to the top-level parser loop, which handles #define and
// #undef directly.  (This prevents these directives from occurring in
// arbitrary positions in the AD file--we require better structure than C.)
// In the other case, and #ifdef, #ifndef, #else, or #endif is silently
// processed as whitespace, with the "taken" state of the text correctly
// updated.  This routine returns "false" exactly in the case of a "taken"
// #define or #undef, which tells the caller that a preprocessor token
// has appeared which must be handled explicitly by the parse loop.
bool ADLParser::handle_preproc_token() {
  assert(*_ptr == '#', "must be at start of preproc");
  ensure_start_of_line();
  next_char();
  skipws_no_preproc();
  char* start_ident = _ptr;
  char* ident = (_curchar == '\n') ? NULL : get_ident_no_preproc();
  if (ident == NULL) {
    parse_err(SYNERR, "expected preprocessor command, got end of line\n");
  } else if (!strcmp(ident, "ifdef") ||
             !strcmp(ident, "ifndef")) {
    char* flag = get_ident_no_preproc();
    ensure_end_of_line();
    // Test the identifier only if we are already in taken code:
    bool flag_def  = preproc_taken() && (_AD.get_preproc_def(flag) != NULL);
    bool now_taken = !strcmp(ident, "ifdef") ? flag_def : !flag_def;
    begin_if_def(now_taken);
  } else if (!strcmp(ident, "if")) {
    if (preproc_taken())
      parse_err(SYNERR, "unimplemented: #%s %s", ident, _ptr+1);
    next_line();
    // Intelligently skip this nested C preprocessor directive:
    begin_if_def(true);
  } else if (!strcmp(ident, "else")) {
    ensure_end_of_line();
    invert_if_def();
  } else if (!strcmp(ident, "endif")) {
    ensure_end_of_line();
    end_if_def();
  } else if (preproc_taken()) {
    // pass this token up to the main parser as "#define" or "#undef"
    _ptr = start_ident;
    _curchar = *--_ptr;
    if( _curchar != '#' ) {
      parse_err(SYNERR, "no space allowed after # in #define or #undef");
      assert(_curchar == '#', "no space allowed after # in #define or #undef");
    }
    return false;
  }
  return true;
}

//---------------------------skipws_common-------------------------------------
// Skip whitespace, including comments and newlines, while keeping an accurate
// line count.
// Maybe handle certain preprocessor constructs: #ifdef, #ifndef, #else, #endif
void ADLParser::skipws_common(bool do_preproc) {
  char *start = _ptr;
  char *next = _ptr + 1;

  if (*_ptr == '\0') {
    // Check for string terminator
    if (_curchar > ' ')  return;
    if (_curchar == '\n') {
      if (!do_preproc)  return;            // let caller handle the newline
      next_line();
      _ptr = _curline; next = _ptr + 1;
    }
    else if (_curchar == '#' ||
        (_curchar == '/' && (*next == '/' || *next == '*'))) {
      parse_err(SYNERR, "unimplemented: comment token in a funny place");
    }
  }
  while(_curline != NULL) {                // Check for end of file
    if (*_ptr == '\n') {                   // keep proper track of new lines
      if (!do_preproc)  break;             // let caller handle the newline
      next_line();
      _ptr = _curline; next = _ptr + 1;
    }
    else if ((*_ptr == '/') && (*next == '/'))      // C++ comment
      do { _ptr++; next++; } while(*_ptr != '\n');  // So go to end of line
    else if ((*_ptr == '/') && (*next == '*')) {    // C comment
      _ptr++; next++;
      do {
        _ptr++; next++;
        if (*_ptr == '\n') {               // keep proper track of new lines
          next_line();                     // skip newlines within comments
          if (_curline == NULL) {          // check for end of file
            parse_err(SYNERR, "end-of-file detected inside comment\n");
            break;
          }
          _ptr = _curline; next = _ptr + 1;
        }
      } while(!((*_ptr == '*') && (*next == '/'))); // Go to end of comment
      _ptr = ++next; next++;               // increment _ptr past comment end
    }
    else if (do_preproc && *_ptr == '#') {
      // Note that this calls skipws_common(false) recursively!
      bool preproc_handled = handle_preproc_token();
      if (!preproc_handled) {
        if (preproc_taken()) {
          return;  // short circuit
        }
        ++_ptr;    // skip the preprocessor character
      }
      next = _ptr+1;
    } else if(*_ptr > ' ' && !(do_preproc && !preproc_taken())) {
      break;
    }
    else if (*_ptr == '"' || *_ptr == '\'') {
      assert(do_preproc, "only skip strings if doing preproc");
      // skip untaken quoted string
      int qchar = *_ptr;
      while (true) {
        ++_ptr;
        if (*_ptr == qchar) { ++_ptr; break; }
        if (*_ptr == '\\')  ++_ptr;
        if (*_ptr == '\n' || *_ptr == '\0') {
          parse_err(SYNERR, "newline in string");
          break;
        }
      }
      next = _ptr + 1;
    }
    else { ++_ptr; ++next; }
  }
  if( _curline != NULL )            // at end of file _curchar isn't valid
    _curchar = *_ptr;               // reset _curchar to maintain invariant
}

//---------------------------cur_char-----------------------------------------
char ADLParser::cur_char() {
  return (_curchar);
}

//---------------------------next_char-----------------------------------------
void ADLParser::next_char() {
5119
  if (_curchar == '\n')  parse_err(WARN, "must call next_line!");
D
duke 已提交
5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
  _curchar = *++_ptr;
  // if ( _curchar == '\n' ) {
  //   next_line();
  // }
}

//---------------------------next_char_or_line---------------------------------
void ADLParser::next_char_or_line() {
  if ( _curchar != '\n' ) {
    _curchar = *++_ptr;
  } else {
    next_line();
    _ptr = _curline;
    _curchar = *_ptr;  // maintain invariant
  }
}

//---------------------------next_line-----------------------------------------
void ADLParser::next_line() {
5139
  _curline = _buf.get_line();
5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151
  _curchar = ' ';
}

//------------------------get_line_string--------------------------------------
// Prepended location descriptor, for debugging.
// Must return a malloced string (that can be freed if desired).
char* ADLParser::get_line_string(int linenum) {
  const char* file = _AD._ADL_file._name;
  int         line = linenum ? linenum : this->linenum();
  char* location = (char *)malloc(strlen(file) + 100);
  sprintf(location, "\n#line %d \"%s\"\n", line, file);
  return location;
D
duke 已提交
5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191
}

//-------------------------is_literal_constant---------------------------------
bool ADLParser::is_literal_constant(const char *param) {
  if (param[0] == 0)     return false;  // null string
  if (param[0] == '(')   return true;   // parenthesized expression
  if (param[0] == '0' && (param[1] == 'x' || param[1] == 'X')) {
    // Make sure it's a hex constant.
    int i = 2;
    do {
      if( !ADLParser::is_hex_digit(*(param+i)) )  return false;
      ++i;
    } while( *(param+i) != 0 );
    return true;
  }
  return false;
}

//---------------------------is_hex_digit--------------------------------------
bool ADLParser::is_hex_digit(char digit) {
  return ((digit >= '0') && (digit <= '9'))
       ||((digit >= 'a') && (digit <= 'f'))
       ||((digit >= 'A') && (digit <= 'F'));
}

//---------------------------is_int_token--------------------------------------
bool ADLParser::is_int_token(const char* token, int& intval) {
  const char* cp = token;
  while (*cp != '\0' && *cp <= ' ')  cp++;
  if (*cp == '-')  cp++;
  int ndigit = 0;
  while (*cp >= '0' && *cp <= '9')  { cp++; ndigit++; }
  while (*cp != '\0' && *cp <= ' ')  cp++;
  if (ndigit == 0 || *cp != '\0') {
    return false;
  }
  intval = atoi(token);
  return true;
}

5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251
static const char* skip_expr_ws(const char* str) {
  const char * cp = str;
  while (cp[0]) {
    if (cp[0] <= ' ') {
      ++cp;
    } else if (cp[0] == '#') {
      ++cp;
      while (cp[0] == ' ')  ++cp;
      assert(0 == strncmp(cp, "line", 4), "must be a #line directive");
      const char* eol = strchr(cp, '\n');
      assert(eol != NULL, "must find end of line");
      if (eol == NULL)  eol = cp + strlen(cp);
      cp = eol;
    } else {
      break;
    }
  }
  return cp;
}

//-----------------------equivalent_expressions--------------------------------
bool ADLParser::equivalent_expressions(const char* str1, const char* str2) {
  if (str1 == str2)
    return true;
  else if (str1 == NULL || str2 == NULL)
    return false;
  const char* cp1 = str1;
  const char* cp2 = str2;
  char in_quote = '\0';
  while (cp1[0] && cp2[0]) {
    if (!in_quote) {
      // skip spaces and/or cpp directives
      const char* cp1a = skip_expr_ws(cp1);
      const char* cp2a = skip_expr_ws(cp2);
      if (cp1a > cp1 && cp2a > cp2) {
        cp1 = cp1a; cp2 = cp2a;
        continue;
      }
      if (cp1a > cp1 || cp2a > cp2)  break; // fail
    }
    // match one non-space char
    if (cp1[0] != cp2[0])  break; // fail
    char ch = cp1[0];
    cp1++; cp2++;
    // watch for quotes
    if (in_quote && ch == '\\') {
      if (cp1[0] != cp2[0])  break; // fail
      if (!cp1[0])  break;
      cp1++; cp2++;
    }
    if (in_quote && ch == in_quote) {
      in_quote = '\0';
    } else if (!in_quote && (ch == '"' || ch == '\'')) {
      in_quote = ch;
    }
  }
  return (!cp1[0] && !cp2[0]);
}


D
duke 已提交
5252 5253 5254 5255 5256 5257 5258
//-------------------------------trim------------------------------------------
void ADLParser::trim(char* &token) {
  while (*token <= ' ')  token++;
  char* end = token + strlen(token);
  while (end > token && *(end-1) <= ' ')  --end;
  *end = '\0';
}