1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)output_c.cpp 1.185 07/07/02 16:50:40 JVM"
   3 #endif
   4 /*
   5  * Copyright 1998-2008 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 // output_c.cpp - Class CPP file output routines for architecture definition
  29 
  30 #include "adlc.hpp"
  31 
  32 // Utilities to characterize effect statements
  33 static bool is_def(int usedef) {
  34   switch(usedef) {
  35   case Component::DEF:
  36   case Component::USE_DEF: return true; break;
  37   }
  38   return false;
  39 }
  40 
  41 static bool is_use(int usedef) {
  42   switch(usedef) {
  43   case Component::USE:
  44   case Component::USE_DEF:
  45   case Component::USE_KILL: return true; break;
  46   }
  47   return false;
  48 }
  49 
  50 static bool is_kill(int usedef) {
  51   switch(usedef) {
  52   case Component::KILL:
  53   case Component::USE_KILL: return true; break;
  54   }
  55   return false;
  56 }
  57 
  58 // Define  an array containing the machine register names, strings.
  59 static void defineRegNames(FILE *fp, RegisterForm *registers) {
  60   if (registers) {
  61     fprintf(fp,"\n");
  62     fprintf(fp,"// An array of character pointers to machine register names.\n");
  63     fprintf(fp,"const char *Matcher::regName[REG_COUNT] = {\n");
  64 
  65     // Output the register name for each register in the allocation classes
  66     RegDef *reg_def = NULL;
  67     RegDef *next = NULL;
  68     registers->reset_RegDefs();
  69     for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
  70       next = registers->iter_RegDefs();
  71       const char *comma = (next != NULL) ? "," : " // no trailing comma";
  72       fprintf(fp,"  \"%s\"%s\n", 
  73                  reg_def->_regname, comma );
  74     }
  75 
  76     // Finish defining enumeration
  77     fprintf(fp,"};\n");
  78 
  79     fprintf(fp,"\n");
  80     fprintf(fp,"// An array of character pointers to machine register names.\n");
  81     fprintf(fp,"const VMReg OptoReg::opto2vm[REG_COUNT] = {\n");
  82     reg_def = NULL;
  83     next = NULL;
  84     registers->reset_RegDefs();
  85     for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
  86       next = registers->iter_RegDefs();
  87       const char *comma = (next != NULL) ? "," : " // no trailing comma";
  88       fprintf(fp,"\t%s%s\n", reg_def->_concrete, comma );
  89     }
  90     // Finish defining array
  91     fprintf(fp,"\t};\n");
  92     fprintf(fp,"\n");
  93 
  94     fprintf(fp," OptoReg::Name OptoReg::vm2opto[ConcreteRegisterImpl::number_of_registers];\n");
  95 
  96   }
  97 }
  98 
  99 // Define an array containing the machine register encoding values
 100 static void defineRegEncodes(FILE *fp, RegisterForm *registers) {
 101   if (registers) {
 102     fprintf(fp,"\n");
 103     fprintf(fp,"// An array of the machine register encode values\n");
 104     fprintf(fp,"const unsigned char Matcher::_regEncode[REG_COUNT] = {\n");
 105 
 106     // Output the register encoding for each register in the allocation classes
 107     RegDef *reg_def = NULL;
 108     RegDef *next    = NULL;
 109     registers->reset_RegDefs();
 110     for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
 111       next = registers->iter_RegDefs();
 112       const char* register_encode = reg_def->register_encode();
 113       const char *comma = (next != NULL) ? "," : " // no trailing comma";
 114       int encval;
 115       if (!ADLParser::is_int_token(register_encode, encval)) {
 116         fprintf(fp,"  %s%s  // %s\n", 
 117                 register_encode, comma, reg_def->_regname );
 118       } else {
 119         // Output known constants in hex char format (backward compatibility).
 120         assert(encval < 256, "Exceeded supported width for register encoding");
 121         fprintf(fp,"  (unsigned char)'\\x%X'%s  // %s\n", 
 122                 encval,          comma, reg_def->_regname );
 123       }
 124     }
 125     // Finish defining enumeration
 126     fprintf(fp,"};\n");
 127 
 128   } // Done defining array
 129 }
 130 
 131 // Output an enumeration of register class names
 132 static void defineRegClassEnum(FILE *fp, RegisterForm *registers) {
 133   if (registers) {
 134     // Output an enumeration of register class names
 135     fprintf(fp,"\n");
 136     fprintf(fp,"// Enumeration of register class names\n");
 137     fprintf(fp, "enum machRegisterClass {\n");
 138     registers->_rclasses.reset();
 139     for( const char *class_name = NULL; 
 140          (class_name = registers->_rclasses.iter()) != NULL; ) {
 141       fprintf(fp,"  %s,\n", toUpper( class_name ));
 142     }
 143     // Finish defining enumeration
 144     fprintf(fp, "  _last_Mach_Reg_Class\n");
 145     fprintf(fp, "};\n");
 146   }
 147 }
 148 
 149 // Declare an enumeration of user-defined register classes
 150 // and a list of register masks, one for each class.
 151 void ArchDesc::declare_register_masks(FILE *fp_hpp) {
 152   const char  *rc_name;
 153 
 154   if( _register ) {
 155     // Build enumeration of user-defined register classes.
 156     defineRegClassEnum(fp_hpp, _register);
 157 
 158     // Generate a list of register masks, one for each class.
 159     fprintf(fp_hpp,"\n");
 160     fprintf(fp_hpp,"// Register masks, one for each register class.\n");
 161     _register->_rclasses.reset();
 162     for( rc_name = NULL; 
 163          (rc_name = _register->_rclasses.iter()) != NULL; ) {
 164       const char *prefix    = "";
 165       RegClass   *reg_class = _register->getRegClass(rc_name);
 166       assert( reg_class, "Using an undefined register class");
 167 
 168       int len = RegisterForm::RegMask_Size();
 169       fprintf(fp_hpp, "extern const RegMask %s%s_mask;\n", prefix, toUpper( rc_name ) );
 170       
 171       if( reg_class->_stack_or_reg ) {
 172         fprintf(fp_hpp, "extern const RegMask %sSTACK_OR_%s_mask;\n", prefix, toUpper( rc_name ) );
 173       }
 174     }
 175   }
 176 }
 177 
 178 // Generate an enumeration of user-defined register classes
 179 // and a list of register masks, one for each class.
 180 void ArchDesc::build_register_masks(FILE *fp_cpp) {
 181   const char  *rc_name;
 182 
 183   if( _register ) {
 184     // Generate a list of register masks, one for each class.
 185     fprintf(fp_cpp,"\n");
 186     fprintf(fp_cpp,"// Register masks, one for each register class.\n");
 187     _register->_rclasses.reset();
 188     for( rc_name = NULL; 
 189          (rc_name = _register->_rclasses.iter()) != NULL; ) {
 190       const char *prefix    = "";
 191       RegClass   *reg_class = _register->getRegClass(rc_name);
 192       assert( reg_class, "Using an undefined register class");
 193 
 194       int len = RegisterForm::RegMask_Size();
 195       fprintf(fp_cpp, "const RegMask %s%s_mask(", prefix, toUpper( rc_name ) );
 196       { int i;
 197         for( i = 0; i < len-1; i++ )
 198           fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i,false));
 199         fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i,false));
 200       }
 201       
 202       if( reg_class->_stack_or_reg ) {
 203         int i;
 204         fprintf(fp_cpp, "const RegMask %sSTACK_OR_%s_mask(", prefix, toUpper( rc_name ) );
 205         for( i = 0; i < len-1; i++ ) 
 206           fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i,true));
 207         fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i,true));
 208       }
 209     }
 210   }
 211 }
 212 
 213 // Compute an index for an array in the pipeline_reads_NNN arrays
 214 static int pipeline_reads_initializer(FILE *fp_cpp, NameList &pipeline_reads, PipeClassForm *pipeclass)
 215 {
 216   int templen = 1;
 217   int paramcount = 0;
 218   const char *paramname;
 219 
 220   if (pipeclass->_parameters.count() == 0)
 221     return -1;
 222 
 223   pipeclass->_parameters.reset();
 224   paramname = pipeclass->_parameters.iter();
 225   const PipeClassOperandForm *pipeopnd =
 226     (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 227   if (pipeopnd && !pipeopnd->isWrite() && strcmp(pipeopnd->_stage, "Universal"))
 228     pipeclass->_parameters.reset();
 229 
 230   while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
 231     const PipeClassOperandForm *pipeopnd =
 232         (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 233 
 234     if (pipeopnd)
 235       templen += 10 + (int)strlen(pipeopnd->_stage);
 236     else
 237       templen += 19;
 238 
 239     paramcount++;
 240   }
 241 
 242   // See if the count is zero
 243   if (paramcount == 0) {
 244     return -1;
 245   }
 246 
 247   char *operand_stages = new char [templen];
 248   operand_stages[0] = 0;
 249   int i = 0;
 250   templen = 0;
 251 
 252   pipeclass->_parameters.reset();
 253   paramname = pipeclass->_parameters.iter();
 254   pipeopnd = (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 255   if (pipeopnd && !pipeopnd->isWrite() && strcmp(pipeopnd->_stage, "Universal"))
 256     pipeclass->_parameters.reset();
 257 
 258   while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
 259     const PipeClassOperandForm *pipeopnd =
 260         (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 261     templen += sprintf(&operand_stages[templen], "  stage_%s%c\n",
 262       pipeopnd ? pipeopnd->_stage : "undefined",
 263       (++i < paramcount ? ',' : ' ') );
 264   }
 265 
 266   // See if the same string is in the table
 267   int ndx = pipeline_reads.index(operand_stages);
 268 
 269   // No, add it to the table
 270   if (ndx < 0) {
 271     pipeline_reads.addName(operand_stages);
 272     ndx = pipeline_reads.index(operand_stages);
 273 
 274     fprintf(fp_cpp, "static const enum machPipelineStages pipeline_reads_%03d[%d] = {\n%s};\n\n",
 275       ndx+1, paramcount, operand_stages);
 276   }
 277   else
 278     delete [] operand_stages;
 279 
 280   return (ndx);
 281 }
 282 
 283 // Compute an index for an array in the pipeline_res_stages_NNN arrays
 284 static int pipeline_res_stages_initializer(
 285   FILE *fp_cpp,
 286   PipelineForm *pipeline,
 287   NameList &pipeline_res_stages,
 288   PipeClassForm *pipeclass)
 289 {
 290   const PipeClassResourceForm *piperesource;
 291   int * res_stages = new int [pipeline->_rescount];
 292   int i;
 293 
 294   for (i = 0; i < pipeline->_rescount; i++)
 295      res_stages[i] = 0;
 296 
 297   for (pipeclass->_resUsage.reset();
 298        (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 299     int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 300     for (i = 0; i < pipeline->_rescount; i++)
 301       if ((1 << i) & used_mask) {
 302         int stage = pipeline->_stages.index(piperesource->_stage);
 303         if (res_stages[i] < stage+1)
 304           res_stages[i] = stage+1;
 305       }
 306   }
 307 
 308   // Compute the length needed for the resource list
 309   int commentlen = 0;
 310   int max_stage = 0;
 311   for (i = 0; i < pipeline->_rescount; i++) {
 312     if (res_stages[i] == 0) {
 313       if (max_stage < 9)
 314         max_stage = 9;
 315     }
 316     else {
 317       int stagelen = (int)strlen(pipeline->_stages.name(res_stages[i]-1));
 318       if (max_stage < stagelen)
 319         max_stage = stagelen;
 320     }
 321 
 322     commentlen += (int)strlen(pipeline->_reslist.name(i));
 323   }
 324 
 325   int templen = 1 + commentlen + pipeline->_rescount * (max_stage + 14);
 326 
 327   // Allocate space for the resource list
 328   char * resource_stages = new char [templen];
 329 
 330   templen = 0;
 331   for (i = 0; i < pipeline->_rescount; i++) {
 332     const char * const resname =
 333       res_stages[i] == 0 ? "undefined" : pipeline->_stages.name(res_stages[i]-1);
 334 
 335     templen += sprintf(&resource_stages[templen], "  stage_%s%-*s // %s\n",
 336       resname, max_stage - (int)strlen(resname) + 1,
 337       (i < pipeline->_rescount-1) ? "," : "",
 338       pipeline->_reslist.name(i));
 339   }
 340 
 341   // See if the same string is in the table
 342   int ndx = pipeline_res_stages.index(resource_stages);
 343 
 344   // No, add it to the table
 345   if (ndx < 0) {
 346     pipeline_res_stages.addName(resource_stages);
 347     ndx = pipeline_res_stages.index(resource_stages);
 348 
 349     fprintf(fp_cpp, "static const enum machPipelineStages pipeline_res_stages_%03d[%d] = {\n%s};\n\n",
 350       ndx+1, pipeline->_rescount, resource_stages);
 351   }
 352   else
 353     delete [] resource_stages;
 354 
 355   delete [] res_stages;
 356 
 357   return (ndx);
 358 }
 359 
 360 // Compute an index for an array in the pipeline_res_cycles_NNN arrays
 361 static int pipeline_res_cycles_initializer(
 362   FILE *fp_cpp,
 363   PipelineForm *pipeline,
 364   NameList &pipeline_res_cycles,
 365   PipeClassForm *pipeclass)
 366 {
 367   const PipeClassResourceForm *piperesource;
 368   int * res_cycles = new int [pipeline->_rescount];
 369   int i;
 370 
 371   for (i = 0; i < pipeline->_rescount; i++)
 372      res_cycles[i] = 0;
 373 
 374   for (pipeclass->_resUsage.reset();
 375        (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 376     int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 377     for (i = 0; i < pipeline->_rescount; i++)
 378       if ((1 << i) & used_mask) {
 379         int cycles = piperesource->_cycles;
 380         if (res_cycles[i] < cycles)
 381           res_cycles[i] = cycles;
 382       }
 383   }
 384 
 385   // Pre-compute the string length
 386   int templen;
 387   int cyclelen = 0, commentlen = 0;
 388   int max_cycles = 0;
 389   char temp[32];
 390 
 391   for (i = 0; i < pipeline->_rescount; i++) {
 392     if (max_cycles < res_cycles[i])
 393       max_cycles = res_cycles[i];
 394     templen = sprintf(temp, "%d", res_cycles[i]);
 395     if (cyclelen < templen)
 396       cyclelen = templen;
 397     commentlen += (int)strlen(pipeline->_reslist.name(i));
 398   }
 399 
 400   templen = 1 + commentlen + (cyclelen + 8) * pipeline->_rescount;
 401 
 402   // Allocate space for the resource list
 403   char * resource_cycles = new char [templen];
 404 
 405   templen = 0;
 406 
 407   for (i = 0; i < pipeline->_rescount; i++) {
 408     templen += sprintf(&resource_cycles[templen], "  %*d%c // %s\n",
 409       cyclelen, res_cycles[i], (i < pipeline->_rescount-1) ? ',' : ' ', pipeline->_reslist.name(i));
 410   }
 411 
 412   // See if the same string is in the table
 413   int ndx = pipeline_res_cycles.index(resource_cycles);
 414 
 415   // No, add it to the table
 416   if (ndx < 0) {
 417     pipeline_res_cycles.addName(resource_cycles);
 418     ndx = pipeline_res_cycles.index(resource_cycles);
 419 
 420     fprintf(fp_cpp, "static const uint pipeline_res_cycles_%03d[%d] = {\n%s};\n\n",
 421       ndx+1, pipeline->_rescount, resource_cycles);
 422   }
 423   else
 424     delete [] resource_cycles;
 425 
 426   delete [] res_cycles;
 427 
 428   return (ndx);
 429 }
 430 
 431 //typedef unsigned long long uint64_t;
 432 
 433 // Compute an index for an array in the pipeline_res_mask_NNN arrays
 434 static int pipeline_res_mask_initializer(
 435   FILE *fp_cpp,
 436   PipelineForm *pipeline,
 437   NameList &pipeline_res_mask,
 438   NameList &pipeline_res_args,
 439   PipeClassForm *pipeclass)
 440 {
 441   const PipeClassResourceForm *piperesource;
 442   const uint rescount      = pipeline->_rescount;
 443   const uint maxcycleused  = pipeline->_maxcycleused;
 444   const uint cyclemasksize = (maxcycleused + 31) >> 5;
 445 
 446   int i, j;
 447   int element_count = 0;
 448   uint *res_mask = new uint [cyclemasksize];
 449   uint resources_used             = 0;
 450   uint resources_used_exclusively = 0;
 451 
 452   for (pipeclass->_resUsage.reset();
 453        (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; )
 454     element_count++;
 455 
 456   // Pre-compute the string length
 457   int templen;
 458   int commentlen = 0;
 459   int max_cycles = 0;
 460 
 461   int cyclelen = ((maxcycleused + 3) >> 2);
 462   int masklen = (rescount + 3) >> 2;
 463 
 464   int cycledigit = 0;
 465   for (i = maxcycleused; i > 0; i /= 10)
 466     cycledigit++;
 467 
 468   int maskdigit = 0;
 469   for (i = rescount; i > 0; i /= 10)
 470     maskdigit++;
 471 
 472   static const char * pipeline_use_cycle_mask = "Pipeline_Use_Cycle_Mask";
 473   static const char * pipeline_use_element    = "Pipeline_Use_Element";
 474 
 475   templen = 1 + 
 476     (int)(strlen(pipeline_use_cycle_mask) + (int)strlen(pipeline_use_element) +
 477      (cyclemasksize * 12) + masklen + (cycledigit * 2) + 30) * element_count;
 478 
 479   // Allocate space for the resource list
 480   char * resource_mask = new char [templen];
 481   char * last_comma = NULL;
 482 
 483   templen = 0;
 484 
 485   for (pipeclass->_resUsage.reset();
 486        (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 487     int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 488 
 489     if (!used_mask)
 490       fprintf(stderr, "*** used_mask is 0 ***\n");
 491 
 492     resources_used |= used_mask;
 493 
 494     uint lb, ub;
 495 
 496     for (lb =  0; (used_mask & (1 << lb)) == 0; lb++);
 497     for (ub = 31; (used_mask & (1 << ub)) == 0; ub--);
 498 
 499     if (lb == ub)
 500       resources_used_exclusively |= used_mask;
 501 
 502     int formatlen =
 503       sprintf(&resource_mask[templen], "  %s(0x%0*x, %*d, %*d, %s %s(",
 504         pipeline_use_element,
 505         masklen, used_mask,
 506         cycledigit, lb, cycledigit, ub,
 507         ((used_mask & (used_mask-1)) != 0) ? "true, " : "false,",
 508         pipeline_use_cycle_mask);
 509 
 510     templen += formatlen;
 511 
 512     memset(res_mask, 0, cyclemasksize * sizeof(uint));
 513 
 514     int cycles = piperesource->_cycles;
 515     uint stage          = pipeline->_stages.index(piperesource->_stage);
 516     uint upper_limit    = stage+cycles-1;
 517     uint lower_limit    = stage-1;
 518     uint upper_idx      = upper_limit >> 5;
 519     uint lower_idx      = lower_limit >> 5;
 520     uint upper_position = upper_limit & 0x1f;
 521     uint lower_position = lower_limit & 0x1f;
 522 
 523     uint mask = (((uint)1) << upper_position) - 1;
 524 
 525     while ( upper_idx > lower_idx ) {
 526       res_mask[upper_idx--] |= mask;
 527       mask = (uint)-1;
 528     }
 529 
 530     mask -= (((uint)1) << lower_position) - 1;
 531     res_mask[upper_idx] |= mask;
 532  
 533     for (j = cyclemasksize-1; j >= 0; j--) {
 534       formatlen = 
 535         sprintf(&resource_mask[templen], "0x%08x%s", res_mask[j], j > 0 ? ", " : "");
 536       templen += formatlen;
 537     }
 538 
 539     resource_mask[templen++] = ')';
 540     resource_mask[templen++] = ')';
 541     last_comma = &resource_mask[templen];
 542     resource_mask[templen++] = ',';
 543     resource_mask[templen++] = '\n';
 544   }
 545 
 546   resource_mask[templen] = 0;
 547   if (last_comma)
 548     last_comma[0] = ' ';
 549 
 550   // See if the same string is in the table
 551   int ndx = pipeline_res_mask.index(resource_mask);
 552 
 553   // No, add it to the table
 554   if (ndx < 0) {
 555     pipeline_res_mask.addName(resource_mask);
 556     ndx = pipeline_res_mask.index(resource_mask);
 557 
 558     if (strlen(resource_mask) > 0)
 559       fprintf(fp_cpp, "static const Pipeline_Use_Element pipeline_res_mask_%03d[%d] = {\n%s};\n\n",
 560         ndx+1, element_count, resource_mask);
 561 
 562     char * args = new char [9 + 2*masklen + maskdigit];
 563 
 564     sprintf(args, "0x%0*x, 0x%0*x, %*d",
 565       masklen, resources_used, 
 566       masklen, resources_used_exclusively,
 567       maskdigit, element_count);
 568 
 569     pipeline_res_args.addName(args);
 570   }
 571   else
 572     delete [] resource_mask;
 573 
 574   delete [] res_mask;
 575 //delete [] res_masks;
 576 
 577   return (ndx);
 578 }
 579 
 580 void ArchDesc::build_pipe_classes(FILE *fp_cpp) {
 581   const char *classname;
 582   const char *resourcename;
 583   int resourcenamelen = 0;
 584   NameList pipeline_reads;
 585   NameList pipeline_res_stages;
 586   NameList pipeline_res_cycles;
 587   NameList pipeline_res_masks;
 588   NameList pipeline_res_args;
 589   const int default_latency = 1;
 590   const int non_operand_latency = 0;
 591   const int node_latency = 0;
 592 
 593   if (!_pipeline) {
 594     fprintf(fp_cpp, "uint Node::latency(uint i) const {\n");
 595     fprintf(fp_cpp, "  // assert(false, \"pipeline functionality is not defined\");\n");
 596     fprintf(fp_cpp, "  return %d;\n", non_operand_latency);
 597     fprintf(fp_cpp, "}\n");
 598     return;
 599   }
 600 
 601   fprintf(fp_cpp, "\n");
 602   fprintf(fp_cpp, "//------------------Pipeline Methods-----------------------------------------\n");
 603   fprintf(fp_cpp, "#ifndef PRODUCT\n");
 604   fprintf(fp_cpp, "const char * Pipeline::stageName(uint s) {\n");
 605   fprintf(fp_cpp, "  static const char * const _stage_names[] = {\n");
 606   fprintf(fp_cpp, "    \"undefined\"");
 607 
 608   for (int s = 0; s < _pipeline->_stagecnt; s++)
 609     fprintf(fp_cpp, ", \"%s\"", _pipeline->_stages.name(s));
 610 
 611   fprintf(fp_cpp, "\n  };\n\n");
 612   fprintf(fp_cpp, "  return (s <= %d ? _stage_names[s] : \"???\");\n",
 613     _pipeline->_stagecnt);
 614   fprintf(fp_cpp, "}\n");
 615   fprintf(fp_cpp, "#endif\n\n");
 616 
 617   fprintf(fp_cpp, "uint Pipeline::functional_unit_latency(uint start, const Pipeline *pred) const {\n");
 618   fprintf(fp_cpp, "  // See if the functional units overlap\n");
 619 #if 0
 620   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 621   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 622   fprintf(fp_cpp, "    tty->print(\"#   functional_unit_latency: start == %%d, this->exclusively == 0x%%03x, pred->exclusively == 0x%%03x\\n\", start, resourcesUsedExclusively(), pred->resourcesUsedExclusively());\n");
 623   fprintf(fp_cpp, "  }\n");
 624   fprintf(fp_cpp, "#endif\n\n");
 625 #endif
 626   fprintf(fp_cpp, "  uint mask = resourcesUsedExclusively() & pred->resourcesUsedExclusively();\n");
 627   fprintf(fp_cpp, "  if (mask == 0)\n    return (start);\n\n");
 628 #if 0
 629   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 630   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 631   fprintf(fp_cpp, "    tty->print(\"#   functional_unit_latency: mask == 0x%%x\\n\", mask);\n");
 632   fprintf(fp_cpp, "  }\n");
 633   fprintf(fp_cpp, "#endif\n\n");
 634 #endif
 635   fprintf(fp_cpp, "  for (uint i = 0; i < pred->resourceUseCount(); i++) {\n");
 636   fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred->resourceUseElement(i);\n");
 637   fprintf(fp_cpp, "    if (predUse->multiple())\n");
 638   fprintf(fp_cpp, "      continue;\n\n");
 639   fprintf(fp_cpp, "    for (uint j = 0; j < resourceUseCount(); j++) {\n");
 640   fprintf(fp_cpp, "      const Pipeline_Use_Element *currUse = resourceUseElement(j);\n");
 641   fprintf(fp_cpp, "      if (currUse->multiple())\n");
 642   fprintf(fp_cpp, "        continue;\n\n");
 643   fprintf(fp_cpp, "      if (predUse->used() & currUse->used()) {\n");
 644   fprintf(fp_cpp, "        Pipeline_Use_Cycle_Mask x = predUse->mask();\n");
 645   fprintf(fp_cpp, "        Pipeline_Use_Cycle_Mask y = currUse->mask();\n\n");
 646   fprintf(fp_cpp, "        for ( y <<= start; x.overlaps(y); start++ )\n");
 647   fprintf(fp_cpp, "          y <<= 1;\n");
 648   fprintf(fp_cpp, "      }\n");
 649   fprintf(fp_cpp, "    }\n");
 650   fprintf(fp_cpp, "  }\n\n");
 651   fprintf(fp_cpp, "  // There is the potential for overlap\n");
 652   fprintf(fp_cpp, "  return (start);\n");
 653   fprintf(fp_cpp, "}\n\n");
 654   fprintf(fp_cpp, "// The following two routines assume that the root Pipeline_Use entity\n");
 655   fprintf(fp_cpp, "// consists of exactly 1 element for each functional unit\n");
 656   fprintf(fp_cpp, "// start is relative to the current cycle; used for latency-based info\n");
 657   fprintf(fp_cpp, "uint Pipeline_Use::full_latency(uint delay, const Pipeline_Use &pred) const {\n");
 658   fprintf(fp_cpp, "  for (uint i = 0; i < pred._count; i++) {\n");
 659   fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred.element(i);\n");
 660   fprintf(fp_cpp, "    if (predUse->_multiple) {\n");
 661   fprintf(fp_cpp, "      uint min_delay = %d;\n",
 662     _pipeline->_maxcycleused+1);
 663   fprintf(fp_cpp, "      // Multiple possible functional units, choose first unused one\n");
 664   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 665   fprintf(fp_cpp, "        const Pipeline_Use_Element *currUse = element(j);\n");
 666   fprintf(fp_cpp, "        uint curr_delay = delay;\n");
 667   fprintf(fp_cpp, "        if (predUse->_used & currUse->_used) {\n");
 668   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask x = predUse->_mask;\n");
 669   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask y = currUse->_mask;\n\n");
 670   fprintf(fp_cpp, "          for ( y <<= curr_delay; x.overlaps(y); curr_delay++ )\n");
 671   fprintf(fp_cpp, "            y <<= 1;\n");
 672   fprintf(fp_cpp, "        }\n");
 673   fprintf(fp_cpp, "        if (min_delay > curr_delay)\n          min_delay = curr_delay;\n");
 674   fprintf(fp_cpp, "      }\n");
 675   fprintf(fp_cpp, "      if (delay < min_delay)\n      delay = min_delay;\n");
 676   fprintf(fp_cpp, "    }\n");
 677   fprintf(fp_cpp, "    else {\n");
 678   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 679   fprintf(fp_cpp, "        const Pipeline_Use_Element *currUse = element(j);\n");
 680   fprintf(fp_cpp, "        if (predUse->_used & currUse->_used) {\n");
 681   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask x = predUse->_mask;\n");
 682   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask y = currUse->_mask;\n\n");
 683   fprintf(fp_cpp, "          for ( y <<= delay; x.overlaps(y); delay++ )\n");
 684   fprintf(fp_cpp, "            y <<= 1;\n");
 685   fprintf(fp_cpp, "        }\n");
 686   fprintf(fp_cpp, "      }\n");
 687   fprintf(fp_cpp, "    }\n");
 688   fprintf(fp_cpp, "  }\n\n");
 689   fprintf(fp_cpp, "  return (delay);\n");
 690   fprintf(fp_cpp, "}\n\n");
 691   fprintf(fp_cpp, "void Pipeline_Use::add_usage(const Pipeline_Use &pred) {\n");
 692   fprintf(fp_cpp, "  for (uint i = 0; i < pred._count; i++) {\n");
 693   fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred.element(i);\n");
 694   fprintf(fp_cpp, "    if (predUse->_multiple) {\n");
 695   fprintf(fp_cpp, "      // Multiple possible functional units, choose first unused one\n");
 696   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 697   fprintf(fp_cpp, "        Pipeline_Use_Element *currUse = element(j);\n");
 698   fprintf(fp_cpp, "        if ( !predUse->_mask.overlaps(currUse->_mask) ) {\n");
 699   fprintf(fp_cpp, "          currUse->_used |= (1 << j);\n");
 700   fprintf(fp_cpp, "          _resources_used |= (1 << j);\n");
 701   fprintf(fp_cpp, "          currUse->_mask.Or(predUse->_mask);\n");
 702   fprintf(fp_cpp, "          break;\n");
 703   fprintf(fp_cpp, "        }\n");
 704   fprintf(fp_cpp, "      }\n");
 705   fprintf(fp_cpp, "    }\n");
 706   fprintf(fp_cpp, "    else {\n");
 707   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 708   fprintf(fp_cpp, "        Pipeline_Use_Element *currUse = element(j);\n");
 709   fprintf(fp_cpp, "        currUse->_used |= (1 << j);\n");
 710   fprintf(fp_cpp, "        _resources_used |= (1 << j);\n");
 711   fprintf(fp_cpp, "        currUse->_mask.Or(predUse->_mask);\n");
 712   fprintf(fp_cpp, "      }\n");
 713   fprintf(fp_cpp, "    }\n");
 714   fprintf(fp_cpp, "  }\n");
 715   fprintf(fp_cpp, "}\n\n");
 716 
 717   fprintf(fp_cpp, "uint Pipeline::operand_latency(uint opnd, const Pipeline *pred) const {\n");
 718   fprintf(fp_cpp, "  int const default_latency = 1;\n");
 719   fprintf(fp_cpp, "\n");
 720 #if 0
 721   fprintf(fp_cpp, "#ifndef PRODUCT\n");
 722   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 723   fprintf(fp_cpp, "    tty->print(\"#   operand_latency(%%d), _read_stage_count = %%d\\n\", opnd, _read_stage_count);\n");
 724   fprintf(fp_cpp, "  }\n");
 725   fprintf(fp_cpp, "#endif\n\n");
 726 #endif
 727   fprintf(fp_cpp, "  assert(this, \"NULL pipeline info\")\n");
 728   fprintf(fp_cpp, "  assert(pred, \"NULL predecessor pipline info\")\n\n");
 729   fprintf(fp_cpp, "  if (pred->hasFixedLatency())\n    return (pred->fixedLatency());\n\n");
 730   fprintf(fp_cpp, "  // If this is not an operand, then assume a dependence with 0 latency\n");
 731   fprintf(fp_cpp, "  if (opnd > _read_stage_count)\n    return (0);\n\n");
 732   fprintf(fp_cpp, "  uint writeStage = pred->_write_stage;\n");
 733   fprintf(fp_cpp, "  uint readStage  = _read_stages[opnd-1];\n");
 734 #if 0
 735   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 736   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 737   fprintf(fp_cpp, "    tty->print(\"#   operand_latency: writeStage=%%s readStage=%%s, opnd=%%d\\n\", stageName(writeStage), stageName(readStage), opnd);\n");
 738   fprintf(fp_cpp, "  }\n");
 739   fprintf(fp_cpp, "#endif\n\n");
 740 #endif
 741   fprintf(fp_cpp, "\n");
 742   fprintf(fp_cpp, "  if (writeStage == stage_undefined || readStage == stage_undefined)\n");
 743   fprintf(fp_cpp, "    return (default_latency);\n");
 744   fprintf(fp_cpp, "\n");
 745   fprintf(fp_cpp, "  int delta = writeStage - readStage;\n");
 746   fprintf(fp_cpp, "  if (delta < 0) delta = 0;\n\n");
 747 #if 0
 748   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 749   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 750   fprintf(fp_cpp, "    tty->print(\"# operand_latency: delta=%%d\\n\", delta);\n");
 751   fprintf(fp_cpp, "  }\n");
 752   fprintf(fp_cpp, "#endif\n\n");
 753 #endif
 754   fprintf(fp_cpp, "  return (delta);\n");
 755   fprintf(fp_cpp, "}\n\n");
 756 
 757   if (!_pipeline)
 758     /* Do Nothing */;
 759 
 760   else if (_pipeline->_maxcycleused <= 
 761 #ifdef SPARC
 762     64
 763 #else
 764     32
 765 #endif
 766       ) {
 767     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 768     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(in1._mask & in2._mask);\n");
 769     fprintf(fp_cpp, "}\n\n");
 770     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 771     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(in1._mask | in2._mask);\n");
 772     fprintf(fp_cpp, "}\n\n");
 773   }
 774   else {
 775     uint l;
 776     uint masklen = (_pipeline->_maxcycleused + 31) >> 5;
 777     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 778     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(");
 779     for (l = 1; l <= masklen; l++)
 780       fprintf(fp_cpp, "in1._mask%d & in2._mask%d%s\n", l, l, l < masklen ? ", " : "");
 781     fprintf(fp_cpp, ");\n");
 782     fprintf(fp_cpp, "}\n\n");
 783     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 784     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(");
 785     for (l = 1; l <= masklen; l++)
 786       fprintf(fp_cpp, "in1._mask%d | in2._mask%d%s", l, l, l < masklen ? ", " : "");
 787     fprintf(fp_cpp, ");\n");
 788     fprintf(fp_cpp, "}\n\n");
 789     fprintf(fp_cpp, "void Pipeline_Use_Cycle_Mask::Or(const Pipeline_Use_Cycle_Mask &in2) {\n ");
 790     for (l = 1; l <= masklen; l++)
 791       fprintf(fp_cpp, " _mask%d |= in2._mask%d;", l, l);
 792     fprintf(fp_cpp, "\n}\n\n");
 793   }
 794 
 795   /* Get the length of all the resource names */
 796   for (_pipeline->_reslist.reset(), resourcenamelen = 0;
 797        (resourcename = _pipeline->_reslist.iter()) != NULL;
 798        resourcenamelen += (int)strlen(resourcename));
 799 
 800   // Create the pipeline class description
 801 
 802   fprintf(fp_cpp, "static const Pipeline pipeline_class_Zero_Instructions(0, 0, true, 0, 0, false, false, false, false, NULL, NULL, NULL, Pipeline_Use(0, 0, 0, NULL));\n\n");
 803   fprintf(fp_cpp, "static const Pipeline pipeline_class_Unknown_Instructions(0, 0, true, 0, 0, false, true, true, false, NULL, NULL, NULL, Pipeline_Use(0, 0, 0, NULL));\n\n");
 804 
 805   fprintf(fp_cpp, "const Pipeline_Use_Element Pipeline_Use::elaborated_elements[%d] = {\n", _pipeline->_rescount);
 806   for (int i1 = 0; i1 < _pipeline->_rescount; i1++) {
 807     fprintf(fp_cpp, "  Pipeline_Use_Element(0, %d, %d, false, Pipeline_Use_Cycle_Mask(", i1, i1);
 808     uint masklen = (_pipeline->_maxcycleused + 31) >> 5;
 809     for (int i2 = masklen-1; i2 >= 0; i2--)
 810       fprintf(fp_cpp, "0%s", i2 > 0 ? ", " : "");
 811     fprintf(fp_cpp, "))%s\n", i1 < (_pipeline->_rescount-1) ? "," : "");
 812   }
 813   fprintf(fp_cpp, "};\n\n");
 814 
 815   fprintf(fp_cpp, "const Pipeline_Use Pipeline_Use::elaborated_use(0, 0, %d, (Pipeline_Use_Element *)&elaborated_elements[0]);\n\n",
 816     _pipeline->_rescount);
 817 
 818   for (_pipeline->_classlist.reset(); (classname = _pipeline->_classlist.iter()) != NULL; ) {
 819     fprintf(fp_cpp, "\n");
 820     fprintf(fp_cpp, "// Pipeline Class \"%s\"\n", classname);
 821     PipeClassForm *pipeclass = _pipeline->_classdict[classname]->is_pipeclass();
 822     int maxWriteStage = -1;
 823     int maxMoreInstrs = 0;
 824     int paramcount = 0;
 825     int i = 0;
 826     const char *paramname;
 827     int resource_count = (_pipeline->_rescount + 3) >> 2;
 828 
 829     // Scan the operands, looking for last output stage and number of inputs
 830     for (pipeclass->_parameters.reset(); (paramname = pipeclass->_parameters.iter()) != NULL; ) {
 831       const PipeClassOperandForm *pipeopnd =
 832           (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 833       if (pipeopnd) {
 834         if (pipeopnd->_iswrite) {
 835            int stagenum  = _pipeline->_stages.index(pipeopnd->_stage);
 836            int moreinsts = pipeopnd->_more_instrs;
 837           if ((maxWriteStage+maxMoreInstrs) < (stagenum+moreinsts)) {
 838             maxWriteStage = stagenum;
 839             maxMoreInstrs = moreinsts;
 840           }
 841         }
 842       }
 843 
 844       if (i++ > 0 || (pipeopnd && !pipeopnd->isWrite()))
 845         paramcount++;
 846     }
 847 
 848     // Create the list of stages for the operands that are read
 849     // Note that we will build a NameList to reduce the number of copies
 850 
 851     int pipeline_reads_index = pipeline_reads_initializer(fp_cpp, pipeline_reads, pipeclass);
 852 
 853     int pipeline_res_stages_index = pipeline_res_stages_initializer(
 854       fp_cpp, _pipeline, pipeline_res_stages, pipeclass);
 855 
 856     int pipeline_res_cycles_index = pipeline_res_cycles_initializer(
 857       fp_cpp, _pipeline, pipeline_res_cycles, pipeclass);
 858 
 859     int pipeline_res_mask_index = pipeline_res_mask_initializer(
 860       fp_cpp, _pipeline, pipeline_res_masks, pipeline_res_args, pipeclass);
 861 
 862 #if 0
 863     // Process the Resources
 864     const PipeClassResourceForm *piperesource;
 865 
 866     unsigned resources_used = 0;
 867     unsigned exclusive_resources_used = 0;
 868     unsigned resource_groups = 0;
 869     for (pipeclass->_resUsage.reset();
 870          (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 871       int used_mask = _pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 872       if (used_mask)
 873         resource_groups++;
 874       resources_used |= used_mask;
 875       if ((used_mask & (used_mask-1)) == 0)
 876         exclusive_resources_used |= used_mask;
 877     }
 878 
 879     if (resource_groups > 0) {
 880       fprintf(fp_cpp, "static const uint pipeline_res_or_masks_%03d[%d] = {",
 881         pipeclass->_num, resource_groups);
 882       for (pipeclass->_resUsage.reset(), i = 1;
 883            (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL;
 884            i++ ) {
 885         int used_mask = _pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 886         if (used_mask) {
 887           fprintf(fp_cpp, " 0x%0*x%c", resource_count, used_mask, i < (int)resource_groups ? ',' : ' ');
 888         }
 889       }
 890       fprintf(fp_cpp, "};\n\n");
 891     }
 892 #endif
 893 
 894     // Create the pipeline class description
 895     fprintf(fp_cpp, "static const Pipeline pipeline_class_%03d(",
 896       pipeclass->_num);
 897     if (maxWriteStage < 0)
 898       fprintf(fp_cpp, "(uint)stage_undefined");
 899     else if (maxMoreInstrs == 0)
 900       fprintf(fp_cpp, "(uint)stage_%s", _pipeline->_stages.name(maxWriteStage));
 901     else
 902       fprintf(fp_cpp, "((uint)stage_%s)+%d", _pipeline->_stages.name(maxWriteStage), maxMoreInstrs);
 903     fprintf(fp_cpp, ", %d, %s, %d, %d, %s, %s, %s, %s,\n",
 904       paramcount,
 905       pipeclass->hasFixedLatency() ? "true" : "false",
 906       pipeclass->fixedLatency(),
 907       pipeclass->InstructionCount(),
 908       pipeclass->hasBranchDelay() ? "true" : "false",
 909       pipeclass->hasMultipleBundles() ? "true" : "false",
 910       pipeclass->forceSerialization() ? "true" : "false",
 911       pipeclass->mayHaveNoCode() ? "true" : "false" );
 912     if (paramcount > 0) {
 913       fprintf(fp_cpp, "\n  (enum machPipelineStages * const) pipeline_reads_%03d,\n ",
 914         pipeline_reads_index+1);
 915     }
 916     else
 917       fprintf(fp_cpp, " NULL,");
 918     fprintf(fp_cpp, "  (enum machPipelineStages * const) pipeline_res_stages_%03d,\n",
 919       pipeline_res_stages_index+1);
 920     fprintf(fp_cpp, "  (uint * const) pipeline_res_cycles_%03d,\n",
 921       pipeline_res_cycles_index+1);
 922     fprintf(fp_cpp, "  Pipeline_Use(%s, (Pipeline_Use_Element *)",
 923       pipeline_res_args.name(pipeline_res_mask_index));
 924     if (strlen(pipeline_res_masks.name(pipeline_res_mask_index)) > 0)
 925       fprintf(fp_cpp, "&pipeline_res_mask_%03d[0]",
 926         pipeline_res_mask_index+1);
 927     else
 928       fprintf(fp_cpp, "NULL");
 929     fprintf(fp_cpp, "));\n");
 930   }
 931 
 932   // Generate the Node::latency method if _pipeline defined
 933   fprintf(fp_cpp, "\n");
 934   fprintf(fp_cpp, "//------------------Inter-Instruction Latency--------------------------------\n");
 935   fprintf(fp_cpp, "uint Node::latency(uint i) {\n");
 936   if (_pipeline) {
 937 #if 0
 938     fprintf(fp_cpp, "#ifndef PRODUCT\n");
 939     fprintf(fp_cpp, " if (TraceOptoOutput) {\n");
 940     fprintf(fp_cpp, "    tty->print(\"# %%4d->latency(%%d)\\n\", _idx, i);\n");
 941     fprintf(fp_cpp, " }\n");
 942     fprintf(fp_cpp, "#endif\n");
 943 #endif
 944     fprintf(fp_cpp, "  uint j;\n");
 945     fprintf(fp_cpp, "  // verify in legal range for inputs\n");
 946     fprintf(fp_cpp, "  assert(i < len(), \"index not in range\");\n\n");
 947     fprintf(fp_cpp, "  // verify input is not null\n");
 948     fprintf(fp_cpp, "  Node *pred = in(i);\n");
 949     fprintf(fp_cpp, "  if (!pred)\n    return %d;\n\n",
 950       non_operand_latency);
 951     fprintf(fp_cpp, "  if (pred->is_Proj())\n    pred = pred->in(0);\n\n");
 952     fprintf(fp_cpp, "  // if either node does not have pipeline info, use default\n");
 953     fprintf(fp_cpp, "  const Pipeline *predpipe = pred->pipeline();\n");
 954     fprintf(fp_cpp, "  assert(predpipe, \"no predecessor pipeline info\");\n\n");
 955     fprintf(fp_cpp, "  if (predpipe->hasFixedLatency())\n    return predpipe->fixedLatency();\n\n");
 956     fprintf(fp_cpp, "  const Pipeline *currpipe = pipeline();\n");
 957     fprintf(fp_cpp, "  assert(currpipe, \"no pipeline info\");\n\n");
 958     fprintf(fp_cpp, "  if (!is_Mach())\n    return %d;\n\n",
 959       node_latency);
 960     fprintf(fp_cpp, "  const MachNode *m = as_Mach();\n");
 961     fprintf(fp_cpp, "  j = m->oper_input_base();\n");
 962     fprintf(fp_cpp, "  if (i < j)\n    return currpipe->functional_unit_latency(%d, predpipe);\n\n",
 963       non_operand_latency);
 964     fprintf(fp_cpp, "  // determine which operand this is in\n");
 965     fprintf(fp_cpp, "  uint n = m->num_opnds();\n");
 966     fprintf(fp_cpp, "  int delta = %d;\n\n",
 967       non_operand_latency);
 968     fprintf(fp_cpp, "  uint k;\n");
 969     fprintf(fp_cpp, "  for (k = 1; k < n; k++) {\n");
 970     fprintf(fp_cpp, "    j += m->_opnds[k]->num_edges();\n");
 971     fprintf(fp_cpp, "    if (i < j)\n");
 972     fprintf(fp_cpp, "      break;\n");
 973     fprintf(fp_cpp, "  }\n");
 974     fprintf(fp_cpp, "  if (k < n)\n");
 975     fprintf(fp_cpp, "    delta = currpipe->operand_latency(k,predpipe);\n\n");
 976     fprintf(fp_cpp, "  return currpipe->functional_unit_latency(delta, predpipe);\n");
 977   }
 978   else {
 979     fprintf(fp_cpp, "  // assert(false, \"pipeline functionality is not defined\");\n");
 980     fprintf(fp_cpp, "  return %d;\n",
 981       non_operand_latency);
 982   }
 983   fprintf(fp_cpp, "}\n\n");
 984 
 985   // Output the list of nop nodes
 986   fprintf(fp_cpp, "// Descriptions for emitting different functional unit nops\n");
 987   const char *nop;
 988   int nopcnt = 0;
 989   for ( _pipeline->_noplist.reset(); (nop = _pipeline->_noplist.iter()) != NULL; nopcnt++ );
 990 
 991   fprintf(fp_cpp, "void Bundle::initialize_nops(MachNode * nop_list[%d], Compile *C) {\n", nopcnt);
 992   int i = 0;
 993   for ( _pipeline->_noplist.reset(); (nop = _pipeline->_noplist.iter()) != NULL; i++ ) {
 994     fprintf(fp_cpp, "  nop_list[%d] = (MachNode *) new (C) %sNode();\n", i, nop);
 995   }
 996   fprintf(fp_cpp, "};\n\n");
 997   fprintf(fp_cpp, "#ifndef PRODUCT\n");
 998   fprintf(fp_cpp, "void Bundle::dump() const {\n");
 999   fprintf(fp_cpp, "  static const char * bundle_flags[] = {\n");
1000   fprintf(fp_cpp, "    \"\",\n");
1001   fprintf(fp_cpp, "    \"use nop delay\",\n");
1002   fprintf(fp_cpp, "    \"use unconditional delay\",\n");
1003   fprintf(fp_cpp, "    \"use conditional delay\",\n");
1004   fprintf(fp_cpp, "    \"used in conditional delay\",\n");
1005   fprintf(fp_cpp, "    \"used in unconditional delay\",\n");
1006   fprintf(fp_cpp, "    \"used in all conditional delays\",\n");
1007   fprintf(fp_cpp, "  };\n\n");
1008 
1009   fprintf(fp_cpp, "  static const char *resource_names[%d] = {", _pipeline->_rescount);
1010   for (i = 0; i < _pipeline->_rescount; i++)
1011     fprintf(fp_cpp, " \"%s\"%c", _pipeline->_reslist.name(i), i < _pipeline->_rescount-1 ? ',' : ' ');
1012   fprintf(fp_cpp, "};\n\n");
1013 
1014   // See if the same string is in the table
1015   fprintf(fp_cpp, "  bool needs_comma = false;\n\n");
1016   fprintf(fp_cpp, "  if (_flags) {\n");
1017   fprintf(fp_cpp, "    tty->print(\"%%s\", bundle_flags[_flags]);\n");
1018   fprintf(fp_cpp, "    needs_comma = true;\n");
1019   fprintf(fp_cpp, "  };\n");
1020   fprintf(fp_cpp, "  if (instr_count()) {\n");
1021   fprintf(fp_cpp, "    tty->print(\"%%s%%d instr%%s\", needs_comma ? \", \" : \"\", instr_count(), instr_count() != 1 ? \"s\" : \"\");\n");
1022   fprintf(fp_cpp, "    needs_comma = true;\n");
1023   fprintf(fp_cpp, "  };\n");
1024   fprintf(fp_cpp, "  uint r = resources_used();\n");
1025   fprintf(fp_cpp, "  if (r) {\n");
1026   fprintf(fp_cpp, "    tty->print(\"%%sresource%%s:\", needs_comma ? \", \" : \"\", (r & (r-1)) != 0 ? \"s\" : \"\");\n");
1027   fprintf(fp_cpp, "    for (uint i = 0; i < %d; i++)\n", _pipeline->_rescount);
1028   fprintf(fp_cpp, "      if ((r & (1 << i)) != 0)\n");
1029   fprintf(fp_cpp, "        tty->print(\" %%s\", resource_names[i]);\n");
1030   fprintf(fp_cpp, "    needs_comma = true;\n");
1031   fprintf(fp_cpp, "  };\n");
1032   fprintf(fp_cpp, "  tty->print(\"\\n\");\n");
1033   fprintf(fp_cpp, "}\n");
1034   fprintf(fp_cpp, "#endif\n");
1035 }
1036 
1037 // ---------------------------------------------------------------------------
1038 //------------------------------Utilities to build Instruction Classes--------
1039 // ---------------------------------------------------------------------------
1040 
1041 static void defineOut_RegMask(FILE *fp, const char *node, const char *regMask) {
1042   fprintf(fp,"const RegMask &%sNode::out_RegMask() const { return (%s); }\n",
1043           node, regMask);
1044 }
1045 
1046 // Scan the peepmatch and output a test for each instruction
1047 static void check_peepmatch_instruction_tree(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
1048   intptr_t   parent        = -1;
1049   intptr_t   inst_position = 0;
1050   const char *inst_name    = NULL;
1051   intptr_t   input         = 0;
1052   fprintf(fp, "      // Check instruction sub-tree\n");
1053   pmatch->reset();
1054   for( pmatch->next_instruction( parent, inst_position, inst_name, input ); 
1055        inst_name != NULL;
1056        pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
1057     // If this is not a placeholder
1058     if( ! pmatch->is_placeholder() ) {
1059       // Define temporaries 'inst#', based on parent and parent's input index
1060       if( parent != -1 ) {                // root was initialized
1061         fprintf(fp, "  inst%ld = inst%ld->in(%ld);\n", 
1062                 inst_position, parent, input);
1063       }
1064 
1065       // When not the root
1066       // Test we have the correct instruction by comparing the rule
1067       if( parent != -1 ) {
1068         fprintf(fp, "  matches = matches &&  ( inst%ld->rule() == %s_rule );",
1069                 inst_position, inst_name);
1070       }
1071     } else {
1072       // Check that user did not try to constrain a placeholder
1073       assert( ! pconstraint->constrains_instruction(inst_position),
1074               "fatal(): Can not constrain a placeholder instruction");
1075     }
1076   }
1077 }
1078 
1079 static void print_block_index(FILE *fp, intptr_t inst_position) {
1080   assert( inst_position >= 0, "Instruction number less than zero");
1081   fprintf(fp, "block_index");
1082   if( inst_position != 0 ) {
1083     fprintf(fp, " - %ld", inst_position);
1084   }
1085 }
1086 
1087 // Scan the peepmatch and output a test for each instruction
1088 static void check_peepmatch_instruction_sequence(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
1089   intptr_t   parent        = -1;
1090   intptr_t   inst_position = 0;
1091   const char *inst_name    = NULL;
1092   intptr_t   input         = 0;
1093   fprintf(fp, "  // Check instruction sub-tree\n");
1094   pmatch->reset();
1095   for( pmatch->next_instruction( parent, inst_position, inst_name, input ); 
1096        inst_name != NULL;
1097        pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
1098     // If this is not a placeholder
1099     if( ! pmatch->is_placeholder() ) {
1100       // Define temporaries 'inst#', based on parent and parent's input index
1101       if( parent != -1 ) {                // root was initialized
1102         fprintf(fp, "  // Identify previous instruction if inside this block\n");
1103         fprintf(fp, "  if( ");
1104         print_block_index(fp, inst_position);
1105         fprintf(fp, " > 0 ) {\n    Node *n = block->_nodes.at(");
1106         print_block_index(fp, inst_position);
1107         fprintf(fp, ");\n    inst%ld = (n->is_Mach()) ? ", inst_position);
1108         fprintf(fp, "n->as_Mach() : NULL;\n  }\n");
1109       }
1110 
1111       // When not the root
1112       // Test we have the correct instruction by comparing the rule.
1113       if( parent != -1 ) {
1114         fprintf(fp, "  matches = matches && (inst%ld != NULL) && (inst%ld->rule() == %s_rule);\n",
1115                 inst_position, inst_position, inst_name);
1116       }
1117     } else {
1118       // Check that user did not try to constrain a placeholder
1119       assert( ! pconstraint->constrains_instruction(inst_position),
1120               "fatal(): Can not constrain a placeholder instruction");
1121     }
1122   }
1123 }
1124 
1125 // Build mapping for register indices, num_edges to input
1126 static void build_instruction_index_mapping( FILE *fp, FormDict &globals, PeepMatch *pmatch ) {
1127   intptr_t   parent        = -1;
1128   intptr_t   inst_position = 0;
1129   const char *inst_name    = NULL;
1130   intptr_t   input         = 0;
1131   fprintf(fp, "      // Build map to register info\n");
1132   pmatch->reset();
1133   for( pmatch->next_instruction( parent, inst_position, inst_name, input ); 
1134        inst_name != NULL;
1135        pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
1136     // If this is not a placeholder
1137     if( ! pmatch->is_placeholder() ) {
1138       // Define temporaries 'inst#', based on self's inst_position
1139       InstructForm *inst = globals[inst_name]->is_instruction();
1140       if( inst != NULL ) {
1141         char inst_prefix[]  = "instXXXX_";
1142         sprintf(inst_prefix, "inst%ld_",   inst_position);
1143         char receiver[]     = "instXXXX->";
1144         sprintf(receiver,    "inst%ld->", inst_position);
1145         inst->index_temps( fp, globals, inst_prefix, receiver );
1146       }
1147     }
1148   }
1149 }
1150 
1151 // Generate tests for the constraints
1152 static void check_peepconstraints(FILE *fp, FormDict &globals, PeepMatch *pmatch, PeepConstraint *pconstraint) {
1153   fprintf(fp, "\n");
1154   fprintf(fp, "      // Check constraints on sub-tree-leaves\n");
1155 
1156   // Build mapping from num_edges to local variables
1157   build_instruction_index_mapping( fp, globals, pmatch );
1158 
1159   // Build constraint tests
1160   if( pconstraint != NULL ) {
1161     fprintf(fp, "      matches = matches &&");
1162     bool   first_constraint = true;
1163     while( pconstraint != NULL ) {
1164       // indentation and connecting '&&'
1165       const char *indentation = "      ";
1166       fprintf(fp, "\n%s%s", indentation, (!first_constraint ? "&& " : "  "));
1167 
1168       // Only have '==' relation implemented
1169       if( strcmp(pconstraint->_relation,"==") != 0 ) {
1170         assert( false, "Unimplemented()" );
1171       }
1172 
1173       // LEFT
1174       intptr_t left_index  = pconstraint->_left_inst;
1175       const char *left_op  = pconstraint->_left_op;
1176       // Access info on the instructions whose operands are compared
1177       InstructForm *inst_left = globals[pmatch->instruction_name(left_index)]->is_instruction();
1178       assert( inst_left, "Parser should guaranty this is an instruction");
1179       int left_op_base  = inst_left->oper_input_base(globals);
1180       // Access info on the operands being compared
1181       int left_op_index  = inst_left->operand_position(left_op, Component::USE);
1182       if( left_op_index == -1 ) {
1183         left_op_index = inst_left->operand_position(left_op, Component::DEF);
1184         if( left_op_index == -1 ) {
1185           left_op_index = inst_left->operand_position(left_op, Component::USE_DEF);
1186         }
1187       }
1188       assert( left_op_index  != NameList::Not_in_list, "Did not find operand in instruction");
1189       ComponentList components_left = inst_left->_components;
1190       const char *left_comp_type = components_left.at(left_op_index)->_type;
1191       OpClassForm *left_opclass = globals[left_comp_type]->is_opclass();
1192       Form::InterfaceType left_interface_type = left_opclass->interface_type(globals);
1193 
1194 
1195       // RIGHT
1196       int right_op_index = -1;
1197       intptr_t right_index = pconstraint->_right_inst;
1198       const char *right_op = pconstraint->_right_op;
1199       if( right_index != -1 ) { // Match operand
1200         // Access info on the instructions whose operands are compared
1201         InstructForm *inst_right = globals[pmatch->instruction_name(right_index)]->is_instruction();
1202         assert( inst_right, "Parser should guaranty this is an instruction");
1203         int right_op_base = inst_right->oper_input_base(globals);
1204         // Access info on the operands being compared
1205         right_op_index = inst_right->operand_position(right_op, Component::USE);
1206         if( right_op_index == -1 ) {
1207           right_op_index = inst_right->operand_position(right_op, Component::DEF);
1208           if( right_op_index == -1 ) {
1209             right_op_index = inst_right->operand_position(right_op, Component::USE_DEF);
1210           }
1211         }
1212         assert( right_op_index != NameList::Not_in_list, "Did not find operand in instruction");
1213         ComponentList components_right = inst_right->_components;
1214         const char *right_comp_type = components_right.at(right_op_index)->_type;
1215         OpClassForm *right_opclass = globals[right_comp_type]->is_opclass();
1216         Form::InterfaceType right_interface_type = right_opclass->interface_type(globals);
1217         assert( right_interface_type == left_interface_type, "Both must be same interface");
1218 
1219       } else {                  // Else match register
1220         // assert( false, "should be a register" );
1221       }
1222 
1223       // 
1224       // Check for equivalence
1225       // 
1226       // fprintf(fp, "phase->eqv( ");
1227       // fprintf(fp, "inst%d->in(%d+%d) /* %s */, inst%d->in(%d+%d) /* %s */",
1228       //         left_index,  left_op_base,  left_op_index,  left_op,
1229       //         right_index, right_op_base, right_op_index, right_op );
1230       // fprintf(fp, ")");
1231       // 
1232       switch( left_interface_type ) {
1233       case Form::register_interface: {
1234         // Check that they are allocated to the same register
1235         // Need parameter for index position if not result operand
1236         char left_reg_index[] = ",instXXXX_idxXXXX";
1237         if( left_op_index != 0 ) {
1238           assert( (left_index <= 9999) && (left_op_index <= 9999), "exceed string size");
1239           // Must have index into operands
1240           sprintf(left_reg_index,",inst%d_idx%d", left_index, left_op_index);
1241         } else {
1242           strcpy(left_reg_index, "");
1243         }
1244         fprintf(fp, "(inst%d->_opnds[%d]->reg(ra_,inst%d%s)  /* %d.%s */",
1245                 left_index,  left_op_index, left_index, left_reg_index, left_index, left_op );
1246         fprintf(fp, " == ");
1247 
1248         if( right_index != -1 ) {
1249           char right_reg_index[18] = ",instXXXX_idxXXXX";
1250           if( right_op_index != 0 ) {
1251             assert( (right_index <= 9999) && (right_op_index <= 9999), "exceed string size");
1252             // Must have index into operands
1253             sprintf(right_reg_index,",inst%d_idx%d", right_index, right_op_index);
1254           } else {
1255             strcpy(right_reg_index, "");
1256           }
1257           fprintf(fp, "/* %d.%s */ inst%d->_opnds[%d]->reg(ra_,inst%d%s)",
1258                   right_index, right_op, right_index, right_op_index, right_index, right_reg_index );
1259         } else {
1260           fprintf(fp, "%s_enc", right_op );
1261         }
1262         fprintf(fp,")");
1263         break;
1264       }
1265       case Form::constant_interface: {
1266         // Compare the '->constant()' values
1267         fprintf(fp, "(inst%d->_opnds[%d]->constant()  /* %d.%s */",
1268                 left_index,  left_op_index,  left_index, left_op );
1269         fprintf(fp, " == ");
1270         fprintf(fp, "/* %d.%s */ inst%d->_opnds[%d]->constant())",
1271                 right_index, right_op, right_index, right_op_index );
1272         break;
1273       }
1274       case Form::memory_interface: {
1275         // Compare 'base', 'index', 'scale', and 'disp'
1276         // base
1277         fprintf(fp, "( \n");
1278         fprintf(fp, "  (inst%d->_opnds[%d]->base(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$base */", 
1279           left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
1280         fprintf(fp, " == ");
1281         fprintf(fp, "/* %d.%s$$base */ inst%d->_opnds[%d]->base(ra_,inst%d,inst%d_idx%d)) &&\n",
1282                 right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
1283         // index
1284         fprintf(fp, "  (inst%d->_opnds[%d]->index(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$index */",
1285                 left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
1286         fprintf(fp, " == ");
1287         fprintf(fp, "/* %d.%s$$index */ inst%d->_opnds[%d]->index(ra_,inst%d,inst%d_idx%d)) &&\n",
1288                 right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
1289         // scale
1290         fprintf(fp, "  (inst%d->_opnds[%d]->scale()  /* %d.%s$$scale */",
1291                 left_index,  left_op_index,  left_index, left_op );
1292         fprintf(fp, " == ");
1293         fprintf(fp, "/* %d.%s$$scale */ inst%d->_opnds[%d]->scale()) &&\n",
1294                 right_index, right_op, right_index, right_op_index );
1295         // disp
1296         fprintf(fp, "  (inst%d->_opnds[%d]->disp(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$disp */",
1297                 left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
1298         fprintf(fp, " == ");
1299         fprintf(fp, "/* %d.%s$$disp */ inst%d->_opnds[%d]->disp(ra_,inst%d,inst%d_idx%d))\n",
1300                 right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
1301         fprintf(fp, ") \n");
1302         break;
1303       }
1304       case Form::conditional_interface: {
1305         // Compare the condition code being tested
1306         assert( false, "Unimplemented()" );
1307         break;
1308       }
1309       default: {
1310         assert( false, "ShouldNotReachHere()" );
1311         break;
1312       }
1313       }
1314  
1315       // Advance to next constraint
1316       pconstraint = pconstraint->next();
1317       first_constraint = false;
1318     }
1319 
1320     fprintf(fp, ";\n");
1321   }
1322 }
1323 
1324 // // EXPERIMENTAL -- TEMPORARY code
1325 // static Form::DataType get_operand_type(FormDict &globals, InstructForm *instr, const char *op_name ) {
1326 //   int op_index = instr->operand_position(op_name, Component::USE);
1327 //   if( op_index == -1 ) {
1328 //     op_index = instr->operand_position(op_name, Component::DEF);
1329 //     if( op_index == -1 ) {
1330 //       op_index = instr->operand_position(op_name, Component::USE_DEF);
1331 //     }
1332 //   }
1333 //   assert( op_index != NameList::Not_in_list, "Did not find operand in instruction");
1334 // 
1335 //   ComponentList components_right = instr->_components;
1336 //   char *right_comp_type = components_right.at(op_index)->_type;
1337 //   OpClassForm *right_opclass = globals[right_comp_type]->is_opclass();
1338 //   Form::InterfaceType  right_interface_type = right_opclass->interface_type(globals);
1339 // 
1340 //   return;
1341 // }
1342 
1343 // Construct the new sub-tree
1344 static void generate_peepreplace( FILE *fp, FormDict &globals, PeepMatch *pmatch, PeepConstraint *pconstraint, PeepReplace *preplace, int max_position ) {
1345   fprintf(fp, "      // IF instructions and constraints matched\n");
1346   fprintf(fp, "      if( matches ) {\n");
1347   fprintf(fp, "        // generate the new sub-tree\n");
1348   fprintf(fp, "        assert( true, \"Debug stopping point\");\n");
1349   if( preplace != NULL ) {
1350     // Get the root of the new sub-tree
1351     const char *root_inst = NULL;
1352     preplace->next_instruction(root_inst);
1353     InstructForm *root_form = globals[root_inst]->is_instruction();
1354     assert( root_form != NULL, "Replacement instruction was not previously defined");
1355     fprintf(fp, "        %sNode *root = new (C) %sNode();\n", root_inst, root_inst);
1356 
1357     intptr_t    inst_num;
1358     const char *op_name;
1359     int         opnds_index = 0;            // define result operand
1360     // Then install the use-operands for the new sub-tree
1361     // preplace->reset();             // reset breaks iteration
1362     for( preplace->next_operand( inst_num, op_name );
1363          op_name != NULL;
1364          preplace->next_operand( inst_num, op_name ) ) {
1365       InstructForm *inst_form;
1366       inst_form  = globals[pmatch->instruction_name(inst_num)]->is_instruction();
1367       assert( inst_form, "Parser should guaranty this is an instruction");
1368       int op_base     = inst_form->oper_input_base(globals);
1369       int inst_op_num = inst_form->operand_position(op_name, Component::USE);
1370       if( inst_op_num == NameList::Not_in_list )
1371         inst_op_num = inst_form->operand_position(op_name, Component::USE_DEF);
1372       assert( inst_op_num != NameList::Not_in_list, "Did not find operand as USE");
1373       // find the name of the OperandForm from the local name
1374       const Form *form   = inst_form->_localNames[op_name];
1375       OperandForm  *op_form = form->is_operand();
1376       if( opnds_index == 0 ) {
1377         // Initial setup of new instruction
1378         fprintf(fp, "        // ----- Initial setup -----\n");
1379         // 
1380         // Add control edge for this node
1381         fprintf(fp, "        root->add_req(_in[0]);                // control edge\n");
1382         // Add unmatched edges from root of match tree
1383         int op_base = root_form->oper_input_base(globals);
1384         for( int unmatched_edge = 1; unmatched_edge < op_base; ++unmatched_edge ) {
1385           fprintf(fp, "        root->add_req(inst%ld->in(%d));        // unmatched ideal edge\n", 
1386                                           inst_num, unmatched_edge);
1387         }
1388         // If new instruction captures bottom type
1389         if( root_form->captures_bottom_type() ) {
1390           // Get bottom type from instruction whose result we are replacing
1391           fprintf(fp, "        root->_bottom_type = inst%ld->bottom_type();\n", inst_num);
1392         }
1393         // Define result register and result operand
1394         fprintf(fp, "        ra_->add_reference(root, inst%ld);\n", inst_num);
1395         fprintf(fp, "        ra_->set_oop (root, ra_->is_oop(inst%ld));\n", inst_num);
1396         fprintf(fp, "        ra_->set_pair(root->_idx, ra_->get_reg_second(inst%ld), ra_->get_reg_first(inst%ld));\n", inst_num, inst_num);
1397         fprintf(fp, "        root->_opnds[0] = inst%ld->_opnds[0]->clone(C); // result\n", inst_num);
1398         fprintf(fp, "        // ----- Done with initial setup -----\n");
1399       } else {
1400         if( (op_form == NULL) || (op_form->is_base_constant(globals) == Form::none) ) {
1401           // Do not have ideal edges for constants after matching
1402           fprintf(fp, "        for( unsigned x%d = inst%ld_idx%d; x%d < inst%ld_idx%d; x%d++ )\n",
1403                   inst_op_num, inst_num, inst_op_num, 
1404                   inst_op_num, inst_num, inst_op_num+1, inst_op_num );
1405           fprintf(fp, "          root->add_req( inst%ld->in(x%d) );\n",
1406                   inst_num, inst_op_num );
1407         } else {
1408           fprintf(fp, "        // no ideal edge for constants after matching\n");
1409         }
1410         fprintf(fp, "        root->_opnds[%d] = inst%ld->_opnds[%d]->clone(C);\n",
1411                 opnds_index, inst_num, inst_op_num );
1412       }
1413       ++opnds_index;
1414     }
1415   }else {
1416     // Replacing subtree with empty-tree
1417     assert( false, "ShouldNotReachHere();");
1418   }
1419   
1420   // Return the new sub-tree
1421   fprintf(fp, "        deleted = %d;\n", max_position+1 /*zero to one based*/);
1422   fprintf(fp, "        return root;  // return new root;\n");
1423   fprintf(fp, "      }\n");
1424 }
1425 
1426 
1427 // Define the Peephole method for an instruction node
1428 void ArchDesc::definePeephole(FILE *fp, InstructForm *node) {
1429   // Generate Peephole function header
1430   fprintf(fp, "MachNode *%sNode::peephole( Block *block, int block_index, PhaseRegAlloc *ra_, int &deleted, Compile* C ) {\n", node->_ident);
1431   fprintf(fp, "  bool  matches = true;\n");
1432 
1433   // Identify the maximum instruction position,
1434   // generate temporaries that hold current instruction
1435   // 
1436   //   MachNode  *inst0 = NULL;
1437   //   ...
1438   //   MachNode  *instMAX = NULL;
1439   // 
1440   int max_position = 0;
1441   Peephole *peep;
1442   for( peep = node->peepholes(); peep != NULL; peep = peep->next() ) {
1443     PeepMatch *pmatch = peep->match();
1444     assert( pmatch != NULL, "fatal(), missing peepmatch rule");
1445     if( max_position < pmatch->max_position() )  max_position = pmatch->max_position();
1446   }
1447   for( int i = 0; i <= max_position; ++i ) {
1448     if( i == 0 ) {
1449       fprintf(fp, "  MachNode *inst0 = this;\n", i);
1450     } else {
1451       fprintf(fp, "  MachNode *inst%d = NULL;\n", i);
1452     }
1453   }
1454 
1455   // For each peephole rule in architecture description
1456   //   Construct a test for the desired instruction sub-tree
1457   //   then check the constraints
1458   //   If these match, Generate the new subtree
1459   for( peep = node->peepholes(); peep != NULL; peep = peep->next() ) {
1460     int         peephole_number = peep->peephole_number();
1461     PeepMatch      *pmatch      = peep->match();
1462     PeepConstraint *pconstraint = peep->constraints();
1463     PeepReplace    *preplace    = peep->replacement();
1464 
1465     // Root of this peephole is the current MachNode
1466     assert( true, // %%name?%% strcmp( node->_ident, pmatch->name(0) ) == 0, 
1467             "root of PeepMatch does not match instruction");
1468 
1469     // Make each peephole rule individually selectable
1470     fprintf(fp, "  if( (OptoPeepholeAt == -1) || (OptoPeepholeAt==%d) ) {\n", peephole_number);
1471     fprintf(fp, "    matches = true;\n");
1472     // Scan the peepmatch and output a test for each instruction
1473     check_peepmatch_instruction_sequence( fp, pmatch, pconstraint );
1474 
1475     // Check constraints and build replacement inside scope
1476     fprintf(fp, "    // If instruction subtree matches\n");
1477     fprintf(fp, "    if( matches ) {\n");
1478 
1479     // Generate tests for the constraints
1480     check_peepconstraints( fp, _globalNames, pmatch, pconstraint );
1481 
1482     // Construct the new sub-tree
1483     generate_peepreplace( fp, _globalNames, pmatch, pconstraint, preplace, max_position );
1484     
1485     // End of scope for this peephole's constraints
1486     fprintf(fp, "    }\n");
1487     // Closing brace '}' to make each peephole rule individually selectable
1488     fprintf(fp, "  } // end of peephole rule #%d\n", peephole_number);
1489     fprintf(fp, "\n");
1490   }
1491 
1492   fprintf(fp, "  return NULL;  // No peephole rules matched\n");
1493   fprintf(fp, "}\n");
1494   fprintf(fp, "\n");
1495 }
1496 
1497 // Define the Expand method for an instruction node
1498 void ArchDesc::defineExpand(FILE *fp, InstructForm *node) {
1499   unsigned      cnt  = 0;          // Count nodes we have expand into
1500   unsigned      i;
1501 
1502   // Generate Expand function header
1503   fprintf(fp,"MachNode *%sNode::Expand(State *state, Node_List &proj_list) {\n", node->_ident);
1504   fprintf(fp,"Compile* C = Compile::current();\n");
1505   // Generate expand code
1506   if( node->expands() ) {
1507     const char   *opid;
1508     int           new_pos, exp_pos;
1509     const char   *new_id   = NULL;
1510     const Form   *frm      = NULL;
1511     InstructForm *new_inst = NULL;
1512     OperandForm  *new_oper = NULL;
1513     unsigned      numo     = node->num_opnds() + 
1514                                 node->_exprule->_newopers.count();
1515 
1516     // If necessary, generate any operands created in expand rule
1517     if (node->_exprule->_newopers.count()) {
1518       for(node->_exprule->_newopers.reset();
1519           (new_id = node->_exprule->_newopers.iter()) != NULL; cnt++) {
1520         frm = node->_localNames[new_id];
1521         assert(frm, "Invalid entry in new operands list of expand rule");
1522         new_oper = frm->is_operand();
1523         char *tmp = (char *)node->_exprule->_newopconst[new_id];
1524         if (tmp == NULL) {
1525           fprintf(fp,"  MachOper *op%d = new (C) %sOper();\n",
1526                   cnt, new_oper->_ident);
1527         }
1528         else {
1529           fprintf(fp,"  MachOper *op%d = new (C) %sOper(%s);\n", 
1530                   cnt, new_oper->_ident, tmp);
1531         }
1532       }
1533     }
1534     cnt = 0;
1535     // Generate the temps to use for DAG building
1536     for(i = 0; i < numo; i++) {
1537       if (i < node->num_opnds()) {
1538         fprintf(fp,"  MachNode *tmp%d = this;\n", i);
1539       }
1540       else {
1541         fprintf(fp,"  MachNode *tmp%d = NULL;\n", i);
1542       }
1543     }
1544     // Build mapping from num_edges to local variables
1545     fprintf(fp,"  unsigned num0 = 0;\n");
1546     for( i = 1; i < node->num_opnds(); i++ ) {
1547       fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();\n",i,i);
1548     }
1549 
1550     // Build a mapping from operand index to input edges
1551     fprintf(fp,"  unsigned idx0 = oper_input_base();\n");
1552 
1553     // The order in which inputs are added to a node is very
1554     // strange.  Store nodes get a memory input before Expand is
1555     // called and all other nodes get it afterwards so
1556     // oper_input_base is wrong during expansion.  This code adjusts
1557     // is so that expansion will work correctly.
1558     bool missing_memory_edge = node->_matrule->needs_ideal_memory_edge(_globalNames) &&
1559                                node->is_ideal_store() == Form::none;
1560     if (missing_memory_edge) {
1561       fprintf(fp,"  idx0--; // Adjust base because memory edge hasn't been inserted yet\n");
1562     }
1563 
1564     for( i = 0; i < node->num_opnds(); i++ ) {
1565       fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
1566               i+1,i,i);
1567     }
1568 
1569     // Declare variable to hold root of expansion
1570     fprintf(fp,"  MachNode *result = NULL;\n");
1571 
1572     // Iterate over the instructions 'node' expands into
1573     ExpandRule  *expand       = node->_exprule;
1574     NameAndList *expand_instr = NULL;
1575     for(expand->reset_instructions();
1576         (expand_instr = expand->iter_instructions()) != NULL; cnt++) {
1577       new_id = expand_instr->name();
1578 
1579       InstructForm* expand_instruction = (InstructForm*)globalAD->globalNames()[new_id];
1580       if (expand_instruction->has_temps()) {
1581         globalAD->syntax_err(node->_linenum, "In %s: expand rules using instructs with TEMPs aren't supported: %s",
1582                              node->_ident, new_id);
1583       }
1584 
1585       // Build the node for the instruction
1586       fprintf(fp,"\n  %sNode *n%d = new (C) %sNode();\n", new_id, cnt, new_id);
1587       // Add control edge for this node
1588       fprintf(fp,"  n%d->add_req(_in[0]);\n", cnt);
1589       // Build the operand for the value this node defines.
1590       Form *form = (Form*)_globalNames[new_id];
1591       assert( form, "'new_id' must be a defined form name");
1592       // Grab the InstructForm for the new instruction
1593       new_inst = form->is_instruction();
1594       assert( new_inst, "'new_id' must be an instruction name");
1595       if( node->is_ideal_if() && new_inst->is_ideal_if() ) {
1596         fprintf(fp, "  ((MachIfNode*)n%d)->_prob = _prob;\n",cnt);
1597         fprintf(fp, "  ((MachIfNode*)n%d)->_fcnt = _fcnt;\n",cnt);
1598       }
1599 
1600       if( node->is_ideal_fastlock() && new_inst->is_ideal_fastlock() ) {
1601         fprintf(fp, "  ((MachFastLockNode*)n%d)->_counters = _counters;\n",cnt);
1602       }
1603 
1604       const char *resultOper = new_inst->reduce_result();
1605       fprintf(fp,"  n%d->set_opnd_array(0, state->MachOperGenerator( %s, C ));\n", 
1606               cnt, machOperEnum(resultOper));
1607 
1608       // get the formal operand NameList
1609       NameList *formal_lst = &new_inst->_parameters;
1610       formal_lst->reset();
1611 
1612       // Handle any memory operand
1613       int memory_operand = new_inst->memory_operand(_globalNames);
1614       if( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
1615         int node_mem_op = node->memory_operand(_globalNames);
1616         assert( node_mem_op != InstructForm::NO_MEMORY_OPERAND, 
1617                 "expand rule member needs memory but top-level inst doesn't have any" );
1618         if (!missing_memory_edge) {
1619           // Copy memory edge
1620           fprintf(fp,"  n%d->add_req(_in[1]);\t// Add memory edge\n", cnt);
1621         }
1622       }
1623 
1624       // Iterate over the new instruction's operands
1625       int prev_pos = -1;
1626       for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
1627         // Use 'parameter' at current position in list of new instruction's formals
1628         // instead of 'opid' when looking up info internal to new_inst
1629         const char *parameter = formal_lst->iter();
1630         // Check for an operand which is created in the expand rule
1631         if ((exp_pos = node->_exprule->_newopers.index(opid)) != -1) {
1632           new_pos = new_inst->operand_position(parameter,Component::USE);
1633           exp_pos += node->num_opnds();
1634           // If there is no use of the created operand, just skip it
1635           if (new_pos != -1) {
1636             //Copy the operand from the original made above
1637             fprintf(fp,"  n%d->set_opnd_array(%d, op%d->clone(C)); // %s\n", 
1638                     cnt, new_pos, exp_pos-node->num_opnds(), opid);
1639             // Check for who defines this operand & add edge if needed
1640             fprintf(fp,"  if(tmp%d != NULL)\n", exp_pos);
1641             fprintf(fp,"    n%d->add_req(tmp%d);\n", cnt, exp_pos);
1642           }
1643         }
1644         else {
1645           // Use operand name to get an index into instruction component list
1646           // ins = (InstructForm *) _globalNames[new_id];
1647           exp_pos = node->operand_position_format(opid);
1648           assert(exp_pos != -1, "Bad expand rule");
1649           if (prev_pos > exp_pos && expand_instruction->_matrule != NULL) {
1650             // For the add_req calls below to work correctly they need
1651             // to added in the same order that a match would add them.
1652             // This means that they would need to be in the order of
1653             // the components list instead of the formal parameters.
1654             // This is a sort of hidden invariant that previously
1655             // wasn't checked and could lead to incorrectly
1656             // constructed nodes.
1657             syntax_err(node->_linenum, "For expand in %s to work, parameter declaration order in %s must follow matchrule\n",
1658                        node->_ident, new_inst->_ident);
1659           }
1660           prev_pos = exp_pos;
1661 
1662           new_pos = new_inst->operand_position(parameter,Component::USE);
1663           if (new_pos != -1) {
1664             // Copy the operand from the ExpandNode to the new node
1665             fprintf(fp,"  n%d->set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n", 
1666                     cnt, new_pos, exp_pos, opid);
1667             // For each operand add appropriate input edges by looking at tmp's
1668             fprintf(fp,"  if(tmp%d == this) {\n", exp_pos);
1669             // Grab corresponding edges from ExpandNode and insert them here
1670             fprintf(fp,"    for(unsigned i = 0; i < num%d; i++) {\n", exp_pos);
1671             fprintf(fp,"      n%d->add_req(_in[i + idx%d]);\n", cnt, exp_pos);
1672             fprintf(fp,"    }\n");
1673             fprintf(fp,"  }\n");
1674             // This value is generated by one of the new instructions
1675             fprintf(fp,"  else n%d->add_req(tmp%d);\n", cnt, exp_pos);
1676           }
1677         }
1678 
1679         // Update the DAG tmp's for values defined by this instruction
1680         int new_def_pos = new_inst->operand_position(parameter,Component::DEF);
1681         Effect *eform = (Effect *)new_inst->_effects[parameter];
1682         // If this operand is a definition in either an effects rule
1683         // or a match rule
1684         if((eform) && (is_def(eform->_use_def))) {
1685           // Update the temp associated with this operand
1686           fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
1687         }
1688         else if( new_def_pos != -1 ) {
1689           // Instruction defines a value but user did not declare it 
1690           // in the 'effect' clause
1691           fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
1692         }
1693       } // done iterating over a new instruction's operands
1694       
1695       // Invoke Expand() for the newly created instruction.
1696       fprintf(fp,"  result = n%d->Expand( state, proj_list );\n", cnt);
1697       assert( !new_inst->expands(), "Do not have complete support for recursive expansion");
1698     } // done iterating over new instructions
1699     fprintf(fp,"\n");
1700   } // done generating expand rule
1701 
1702   else if( node->_matrule != NULL ) {
1703     // Remove duplicated operands and inputs which use the same name.
1704     // Seach through match operands for the same name usage.
1705     uint cur_num_opnds = node->num_opnds();
1706     if( cur_num_opnds > 1 && cur_num_opnds != node->num_unique_opnds() ) {
1707       Component *comp = NULL;
1708       // Build mapping from num_edges to local variables
1709       fprintf(fp,"  unsigned num0 = 0;\n");
1710       for( i = 1; i < cur_num_opnds; i++ ) {
1711         fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();\n",i,i);
1712       }
1713       // Build a mapping from operand index to input edges
1714       fprintf(fp,"  unsigned idx0 = oper_input_base();\n");
1715       for( i = 0; i < cur_num_opnds; i++ ) {
1716         fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
1717                 i+1,i,i);
1718       }
1719 
1720       uint new_num_opnds = 1;
1721       node->_components.reset();
1722       // Skip first unique operands.
1723       for( i = 1; i < cur_num_opnds; i++ ) {
1724         comp = node->_components.iter();
1725         if( (int)i != node->unique_opnds_idx(i) ) {
1726           break;
1727         }
1728         new_num_opnds++;
1729       }
1730       // Replace not unique operands with next unique operands.
1731       for( ; i < cur_num_opnds; i++ ) {
1732         comp = node->_components.iter();
1733         int j = node->unique_opnds_idx(i);
1734         // unique_opnds_idx(i) is unique if unique_opnds_idx(j) is not unique.
1735         if( j != node->unique_opnds_idx(j) ) {
1736           fprintf(fp,"  set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n", 
1737                   new_num_opnds, i, comp->_name);
1738           // delete not unique edges here
1739           fprintf(fp,"  for(unsigned i = 0; i < num%d; i++) {\n", i);
1740           fprintf(fp,"    set_req(i + idx%d, _in[i + idx%d]);\n", new_num_opnds, i);
1741           fprintf(fp,"  }\n");
1742           fprintf(fp,"  num%d = num%d;\n", new_num_opnds, i);
1743           fprintf(fp,"  idx%d = idx%d + num%d;\n", new_num_opnds+1, new_num_opnds, new_num_opnds);
1744           new_num_opnds++;
1745         }
1746       }
1747       // delete the rest of edges
1748       fprintf(fp,"  for(int i = idx%d - 1; i >= (int)idx%d; i--) {\n", cur_num_opnds, new_num_opnds);
1749       fprintf(fp,"    del_req(i);\n", i);
1750       fprintf(fp,"  }\n");
1751       fprintf(fp,"  _num_opnds = %d;\n", new_num_opnds);
1752     }
1753   }
1754 
1755 
1756   // Generate projections for instruction's additional DEFs and KILLs 
1757   if( ! node->expands() && (node->needs_projections() || node->has_temps())) {
1758     // Get string representing the MachNode that projections point at
1759     const char *machNode = "this";
1760     // Generate the projections
1761     fprintf(fp,"  // Add projection edges for additional defs or kills\n");
1762 
1763     // Examine each component to see if it is a DEF or KILL
1764     node->_components.reset();
1765     // Skip the first component, if already handled as (SET dst (...))
1766     Component *comp = NULL;
1767     // For kills, the choice of projection numbers is arbitrary
1768     int proj_no = 1;
1769     bool declared_def  = false;
1770     bool declared_kill = false;
1771 
1772     while( (comp = node->_components.iter()) != NULL ) {
1773       // Lookup register class associated with operand type
1774       Form        *form = (Form*)_globalNames[comp->_type];
1775       assert( form, "component type must be a defined form");
1776       OperandForm *op   = form->is_operand();
1777 
1778       if (comp->is(Component::TEMP)) {
1779         fprintf(fp, "  // TEMP %s\n", comp->_name);
1780         if (!declared_def) {
1781           // Define the variable "def" to hold new MachProjNodes
1782           fprintf(fp, "  MachTempNode *def;\n");
1783           declared_def = true;
1784         }
1785         if (op && op->_interface && op->_interface->is_RegInterface()) {
1786           fprintf(fp,"  def = new (C) MachTempNode(state->MachOperGenerator( %s, C ));\n", 
1787                   machOperEnum(op->_ident));
1788           fprintf(fp,"  add_req(def);\n");
1789           int idx  = node->operand_position_format(comp->_name);
1790           fprintf(fp,"  set_opnd_array(%d, state->MachOperGenerator( %s, C ));\n", 
1791                   idx, machOperEnum(op->_ident));
1792         } else {
1793           assert(false, "can't have temps which aren't registers");
1794         }
1795       } else if (comp->isa(Component::KILL)) {
1796         fprintf(fp, "  // DEF/KILL %s\n", comp->_name);
1797 
1798         if (!declared_kill) {
1799           // Define the variable "kill" to hold new MachProjNodes
1800           fprintf(fp, "  MachProjNode *kill;\n");
1801           declared_kill = true;
1802         }
1803 
1804         assert( op, "Support additional KILLS for base operands");
1805         const char *regmask    = reg_mask(*op);
1806         const char *ideal_type = op->ideal_type(_globalNames, _register);
1807 
1808         if (!op->is_bound_register()) {
1809           syntax_err(node->_linenum, "In %s only bound registers can be killed: %s %s\n",
1810                      node->_ident, comp->_type, comp->_name);
1811         }
1812 
1813         fprintf(fp,"  kill = ");
1814         fprintf(fp,"new (C, 1) MachProjNode( %s, %d, (%s), Op_%s );\n",
1815                 machNode, proj_no++, regmask, ideal_type);
1816         fprintf(fp,"  proj_list.push(kill);\n");
1817       }
1818     }
1819   }
1820 
1821   fprintf(fp,"\n");
1822   if( node->expands() ) {
1823     fprintf(fp,"  return result;\n",cnt-1);
1824   } else {
1825     fprintf(fp,"  return this;\n");
1826   }
1827   fprintf(fp,"}\n");
1828   fprintf(fp,"\n");
1829 }
1830 
1831 
1832 //------------------------------Emit Routines----------------------------------
1833 // Special classes and routines for defining node emit routines which output
1834 // target specific instruction object encodings.
1835 // Define the ___Node::emit() routine
1836 //
1837 // (1) void  ___Node::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
1838 // (2)   // ...  encoding defined by user
1839 // (3)   
1840 // (4) }
1841 // 
1842 
1843 class DefineEmitState {
1844 private:
1845   enum reloc_format { RELOC_NONE        = -1, 
1846                       RELOC_IMMEDIATE   =  0, 
1847                       RELOC_DISP        =  1, 
1848                       RELOC_CALL_DISP   =  2 };
1849   enum literal_status{ LITERAL_NOT_SEEN  = 0,
1850                        LITERAL_SEEN      = 1,
1851                        LITERAL_ACCESSED  = 2,
1852                        LITERAL_OUTPUT    = 3 };
1853   // Temporaries that describe current operand
1854   bool          _cleared;
1855   OpClassForm  *_opclass;
1856   OperandForm  *_operand;
1857   int           _operand_idx;
1858   const char   *_local_name;
1859   const char   *_operand_name;
1860   bool          _doing_disp;
1861   bool          _doing_constant;
1862   Form::DataType _constant_type;
1863   DefineEmitState::literal_status _constant_status;
1864   DefineEmitState::literal_status _reg_status;
1865   bool          _doing_emit8;
1866   bool          _doing_emit_d32;
1867   bool          _doing_emit_d16;
1868   bool          _doing_emit_hi;
1869   bool          _doing_emit_lo;
1870   bool          _may_reloc;
1871   bool          _must_reloc;
1872   reloc_format  _reloc_form;
1873   const char *  _reloc_type;                              
1874   bool          _processing_noninput;
1875                
1876   NameList      _strings_to_emit;
1877 
1878   // Stable state, set by constructor
1879   ArchDesc     &_AD;
1880   FILE         *_fp;
1881   EncClass     &_encoding;
1882   InsEncode    &_ins_encode;
1883   InstructForm &_inst;
1884   
1885 public:
1886   DefineEmitState(FILE *fp, ArchDesc &AD, EncClass &encoding, 
1887                   InsEncode &ins_encode, InstructForm &inst) 
1888     : _AD(AD), _fp(fp), _encoding(encoding), _ins_encode(ins_encode), _inst(inst) {
1889       clear();
1890   }
1891 
1892   void clear() {
1893     _cleared       = true;
1894     _opclass       = NULL;
1895     _operand       = NULL;
1896     _operand_idx   = 0;
1897     _local_name    = "";
1898     _operand_name  = "";
1899     _doing_disp    = false;
1900     _doing_constant= false;
1901     _constant_type = Form::none;
1902     _constant_status = LITERAL_NOT_SEEN;
1903     _reg_status      = LITERAL_NOT_SEEN;
1904     _doing_emit8   = false;
1905     _doing_emit_d32= false;
1906     _doing_emit_d16= false;
1907     _doing_emit_hi = false;
1908     _doing_emit_lo = false;
1909     _may_reloc     = false;
1910     _must_reloc    = false;
1911     _reloc_form    = RELOC_NONE;
1912     _reloc_type    = AdlcVMDeps::none_reloc_type();
1913     _strings_to_emit.clear();
1914   }
1915 
1916   // Track necessary state when identifying a replacement variable
1917   void update_state(const char *rep_var) {
1918     // A replacement variable or one of its subfields
1919     // Obtain replacement variable from list
1920     if ( (*rep_var) != '$' ) {
1921       // A replacement variable, '$' prefix
1922       // check_rep_var( rep_var );
1923       if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
1924         // No state needed.
1925         assert( _opclass == NULL, 
1926                 "'primary', 'secondary' and 'tertiary' don't follow operand.");
1927       } else {
1928         // Lookup its position in parameter list
1929         int   param_no  = _encoding.rep_var_index(rep_var);
1930         if ( param_no == -1 ) {
1931           _AD.syntax_err( _encoding._linenum,
1932                           "Replacement variable %s not found in enc_class %s.\n",
1933                           rep_var, _encoding._name);
1934         }
1935 
1936         // Lookup the corresponding ins_encode parameter
1937         const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
1938         if (inst_rep_var == NULL) {
1939           _AD.syntax_err( _ins_encode._linenum,
1940                           "Parameter %s not passed to enc_class %s from instruct %s.\n",
1941                           rep_var, _encoding._name, _inst._ident);
1942         }
1943 
1944         // Check if instruction's actual parameter is a local name in the instruction
1945         const Form  *local     = _inst._localNames[inst_rep_var];
1946         OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
1947         // Note: assert removed to allow constant and symbolic parameters
1948         // assert( opc, "replacement variable was not found in local names");
1949         // Lookup the index position iff the replacement variable is a localName
1950         int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
1951 
1952         if ( idx != -1 ) {
1953           // This is a local in the instruction
1954           // Update local state info.
1955           _opclass        = opc;
1956           _operand_idx    = idx;
1957           _local_name     = rep_var;
1958           _operand_name   = inst_rep_var;
1959 
1960           // !!!!!
1961           // Do not support consecutive operands.
1962           assert( _operand == NULL, "Unimplemented()");
1963           _operand = opc->is_operand();
1964         }
1965         else if( ADLParser::is_literal_constant(inst_rep_var) ) {
1966           // Instruction provided a constant expression
1967           // Check later that encoding specifies $$$constant to resolve as constant
1968           _constant_status   = LITERAL_SEEN;
1969         }
1970         else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
1971           // Instruction provided an opcode: "primary", "secondary", "tertiary"
1972           // Check later that encoding specifies $$$constant to resolve as constant
1973           _constant_status   = LITERAL_SEEN;
1974         }
1975         else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
1976           // Instruction provided a literal register name for this parameter
1977           // Check that encoding specifies $$$reg to resolve.as register.
1978           _reg_status        = LITERAL_SEEN;
1979         }
1980         else {
1981           // Check for unimplemented functionality before hard failure
1982           assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
1983           assert( false, "ShouldNotReachHere()");
1984         }
1985       } // done checking which operand this is.
1986     } else {
1987       // 
1988       // A subfield variable, '$$' prefix
1989       // Check for fields that may require relocation information.
1990       // Then check that literal register parameters are accessed with 'reg' or 'constant'
1991       // 
1992       if ( strcmp(rep_var,"$disp") == 0 ) {
1993         _doing_disp = true;
1994         assert( _opclass, "Must use operand or operand class before '$disp'");
1995         if( _operand == NULL ) {
1996           // Only have an operand class, generate run-time check for relocation
1997           _may_reloc    = true;
1998           _reloc_form   = RELOC_DISP;
1999           _reloc_type   = AdlcVMDeps::oop_reloc_type();
2000         } else {
2001           // Do precise check on operand: is it a ConP or not
2002           // 
2003           // Check interface for value of displacement
2004           assert( ( _operand->_interface != NULL ),
2005                   "$disp can only follow memory interface operand");
2006           MemInterface *mem_interface= _operand->_interface->is_MemInterface();
2007           assert( mem_interface != NULL,
2008                   "$disp can only follow memory interface operand");
2009           const char *disp = mem_interface->_disp;
2010 
2011           if( disp != NULL && (*disp == '$') ) {
2012             // MemInterface::disp contains a replacement variable,
2013             // Check if this matches a ConP
2014             // 
2015             // Lookup replacement variable, in operand's component list
2016             const char *rep_var_name = disp + 1; // Skip '$'
2017             const Component *comp = _operand->_components.search(rep_var_name);
2018             assert( comp != NULL,"Replacement variable not found in components");
2019             const char      *type = comp->_type;
2020             // Lookup operand form for replacement variable's type
2021             const Form *form = _AD.globalNames()[type];
2022             assert( form != NULL, "Replacement variable's type not found");
2023             OperandForm *op = form->is_operand();
2024             assert( op, "Attempting to emit a non-register or non-constant");
2025             // Check if this is a constant
2026             if (op->_matrule && op->_matrule->is_base_constant(_AD.globalNames())) {
2027               // Check which constant this name maps to: _c0, _c1, ..., _cn
2028               // const int idx = _operand.constant_position(_AD.globalNames(), comp);
2029               // assert( idx != -1, "Constant component not found in operand");
2030               Form::DataType dtype = op->is_base_constant(_AD.globalNames());
2031               if ( dtype == Form::idealP ) {
2032                 _may_reloc    = true;
2033                 // No longer true that idealP is always an oop
2034                 _reloc_form   = RELOC_DISP;
2035                 _reloc_type   = AdlcVMDeps::oop_reloc_type();
2036               }
2037             } 
2038 
2039             else if( _operand->is_user_name_for_sReg() != Form::none ) {
2040               // The only non-constant allowed access to disp is an operand sRegX in a stackSlotX
2041               assert( op->ideal_to_sReg_type(type) != Form::none, "StackSlots access displacements using 'sRegs'");
2042               _may_reloc   = false;
2043             } else {
2044               assert( false, "fatal(); Only stackSlots can access a non-constant using 'disp'");
2045             }
2046           }
2047         } // finished with precise check of operand for relocation.
2048       } // finished with subfield variable
2049       else if ( strcmp(rep_var,"$constant") == 0 ) {
2050         _doing_constant = true;
2051         if ( _constant_status == LITERAL_NOT_SEEN ) {
2052           // Check operand for type of constant
2053           assert( _operand, "Must use operand before '$$constant'");
2054           Form::DataType dtype = _operand->is_base_constant(_AD.globalNames());
2055           _constant_type = dtype;
2056           if ( dtype == Form::idealP ) {
2057             _may_reloc    = true;
2058             // No longer true that idealP is always an oop
2059             // // _must_reloc   = true;
2060             _reloc_form   = RELOC_IMMEDIATE;
2061             _reloc_type   = AdlcVMDeps::oop_reloc_type();
2062           } else {
2063             // No relocation information needed
2064           }
2065         } else {
2066           // User-provided literals may not require relocation information !!!!!
2067           assert( _constant_status == LITERAL_SEEN, "Must know we are processing a user-provided literal");
2068         }
2069       }
2070       else if ( strcmp(rep_var,"$label") == 0 ) {
2071         // Calls containing labels require relocation
2072         if ( _inst.is_ideal_call() )  {
2073           _may_reloc    = true;
2074           // !!!!! !!!!!
2075           _reloc_type   = AdlcVMDeps::none_reloc_type();
2076         }
2077       }
2078 
2079       // literal register parameter must be accessed as a 'reg' field.
2080       if ( _reg_status != LITERAL_NOT_SEEN ) {
2081         assert( _reg_status == LITERAL_SEEN, "Must have seen register literal before now");
2082         if (strcmp(rep_var,"$reg") == 0 || reg_conversion(rep_var) != NULL) {
2083           _reg_status  = LITERAL_ACCESSED;
2084         } else {
2085           assert( false, "invalid access to literal register parameter");
2086         }
2087       }
2088       // literal constant parameters must be accessed as a 'constant' field
2089       if ( _constant_status != LITERAL_NOT_SEEN ) {
2090         assert( _constant_status == LITERAL_SEEN, "Must have seen constant literal before now");
2091         if( strcmp(rep_var,"$constant") == 0 ) {
2092           _constant_status  = LITERAL_ACCESSED;
2093         } else {
2094           assert( false, "invalid access to literal constant parameter");
2095         }
2096       }
2097     } // end replacement and/or subfield
2098 
2099   }
2100 
2101   void add_rep_var(const char *rep_var) {
2102     // Handle subfield and replacement variables.
2103     if ( ( *rep_var == '$' ) && ( *(rep_var+1) == '$' ) ) {
2104       // Check for emit prefix, '$$emit32'
2105       assert( _cleared, "Can not nest $$$emit32");
2106       if ( strcmp(rep_var,"$$emit32") == 0 ) {
2107         _doing_emit_d32 = true;
2108       }
2109       else if ( strcmp(rep_var,"$$emit16") == 0 ) {
2110         _doing_emit_d16 = true;
2111       }
2112       else if ( strcmp(rep_var,"$$emit_hi") == 0 ) {
2113         _doing_emit_hi  = true;
2114       }
2115       else if ( strcmp(rep_var,"$$emit_lo") == 0 ) {
2116         _doing_emit_lo  = true;
2117       }
2118       else if ( strcmp(rep_var,"$$emit8") == 0 ) {
2119         _doing_emit8    = true;
2120       }
2121       else {
2122         _AD.syntax_err(_encoding._linenum, "Unsupported $$operation '%s'\n",rep_var);
2123         assert( false, "fatal();");
2124       }
2125     }
2126     else {
2127       // Update state for replacement variables
2128       update_state( rep_var );
2129       _strings_to_emit.addName(rep_var);
2130     }
2131     _cleared  = false;
2132   }
2133 
2134   void emit_replacement() {
2135     // A replacement variable or one of its subfields
2136     // Obtain replacement variable from list
2137     // const char *ec_rep_var = encoding->_rep_vars.iter();
2138     const char *rep_var;
2139     _strings_to_emit.reset();
2140     while ( (rep_var = _strings_to_emit.iter()) != NULL ) {
2141       
2142       if ( (*rep_var) == '$' ) {
2143         // A subfield variable, '$$' prefix
2144         emit_field( rep_var );
2145       } else {
2146         // A replacement variable, '$' prefix
2147         emit_rep_var( rep_var );
2148       } // end replacement and/or subfield
2149     }
2150   }
2151 
2152   void emit_reloc_type(const char* type) {
2153     fprintf(_fp, "%s", type)
2154       ;
2155   }
2156 
2157 
2158   void gen_emit_x_reloc(const char *d32_lo_hi ) {
2159     fprintf(_fp,"emit_%s_reloc(cbuf, ", d32_lo_hi );
2160     emit_replacement();             fprintf(_fp,", ");
2161     emit_reloc_type( _reloc_type ); fprintf(_fp,", ");    
2162     fprintf(_fp, "%d", _reloc_form);fprintf(_fp, ");");
2163   }
2164     
2165   
2166   void emit() {
2167     // 
2168     //   "emit_d32_reloc(" or "emit_hi_reloc" or "emit_lo_reloc"
2169     // 
2170     // Emit the function name when generating an emit function
2171     if ( _doing_emit_d32 || _doing_emit_hi || _doing_emit_lo ) {
2172       const char *d32_hi_lo = _doing_emit_d32 ? "d32" : (_doing_emit_hi ? "hi" : "lo");
2173       // In general, relocatable isn't known at compiler compile time.
2174       // Check results of prior scan
2175       if ( ! _may_reloc ) {
2176         // Definitely don't need relocation information
2177         fprintf( _fp, "emit_%s(cbuf, ", d32_hi_lo );
2178         emit_replacement(); fprintf(_fp, ")"); 
2179       } 
2180       else if ( _must_reloc ) {
2181         // Must emit relocation information
2182         gen_emit_x_reloc( d32_hi_lo );
2183       }
2184       else {
2185         // Emit RUNTIME CHECK to see if value needs relocation info
2186         // If emitting a relocatable address, use 'emit_d32_reloc'
2187         const char *disp_constant = _doing_disp ? "disp" : _doing_constant ? "constant" : "INVALID";
2188         assert( (_doing_disp || _doing_constant)
2189                 && !(_doing_disp && _doing_constant),
2190                 "Must be emitting either a displacement or a constant");
2191         fprintf(_fp,"\n");
2192         fprintf(_fp,"if ( opnd_array(%d)->%s_is_oop() ) {\n", 
2193                 _operand_idx, disp_constant);
2194         fprintf(_fp,"  ");  
2195         gen_emit_x_reloc( d32_hi_lo ); fprintf(_fp,"\n");
2196         fprintf(_fp,"} else {\n");
2197         fprintf(_fp,"  emit_%s(cbuf, ", d32_hi_lo);
2198         emit_replacement(); fprintf(_fp, ");\n"); fprintf(_fp,"}");
2199       }
2200     }
2201     else if ( _doing_emit_d16 ) {
2202       // Relocation of 16-bit values is not supported
2203       fprintf(_fp,"emit_d16(cbuf, "); 
2204       emit_replacement(); fprintf(_fp, ")");
2205       // No relocation done for 16-bit values
2206     }
2207     else if ( _doing_emit8 ) {
2208       // Relocation of 8-bit values is not supported
2209       fprintf(_fp,"emit_d8(cbuf, "); 
2210       emit_replacement(); fprintf(_fp, ")");
2211       // No relocation done for 8-bit values
2212     }
2213     else {
2214       // Not an emit# command, just output the replacement string.
2215       emit_replacement();
2216     }
2217 
2218     // Get ready for next state collection.
2219     clear();
2220   }
2221 
2222 private:
2223 
2224   // recognizes names which represent MacroAssembler register types
2225   // and return the conversion function to build them from OptoReg
2226   const char* reg_conversion(const char* rep_var) {
2227     if (strcmp(rep_var,"$Register") == 0)      return "as_Register";
2228     if (strcmp(rep_var,"$FloatRegister") == 0) return "as_FloatRegister";
2229 #if defined(IA32) || defined(AMD64)
2230     if (strcmp(rep_var,"$XMMRegister") == 0)   return "as_XMMRegister";
2231 #endif
2232     return NULL;
2233   }
2234   
2235   void emit_field(const char *rep_var) {
2236     const char* reg_convert = reg_conversion(rep_var);
2237 
2238     // A subfield variable, '$$subfield'
2239     if ( strcmp(rep_var, "$reg") == 0 || reg_convert != NULL) {
2240       // $reg form or the $Register MacroAssembler type conversions
2241       assert( _operand_idx != -1, 
2242               "Must use this subfield after operand");
2243       if( _reg_status == LITERAL_NOT_SEEN ) {
2244         if (_processing_noninput) {
2245           const Form  *local     = _inst._localNames[_operand_name];
2246           OperandForm *oper      = local->is_operand();
2247           const RegDef* first = oper->get_RegClass()->find_first_elem();
2248           if (reg_convert != NULL) {
2249             fprintf(_fp, "%s(%s_enc)", reg_convert, first->_regname);
2250           } else {
2251             fprintf(_fp, "%s_enc", first->_regname);
2252           }
2253         } else {
2254           fprintf(_fp,"->%s(ra_,this", reg_convert != NULL ? reg_convert : "reg");
2255           // Add parameter for index position, if not result operand
2256           if( _operand_idx != 0 ) fprintf(_fp,",idx%d", _operand_idx);
2257           fprintf(_fp,")");
2258         }
2259       } else {
2260         assert( _reg_status == LITERAL_OUTPUT, "should have output register literal in emit_rep_var");
2261         // Register literal has already been sent to output file, nothing more needed
2262       }
2263     }
2264     else if ( strcmp(rep_var,"$base") == 0 ) {
2265       assert( _operand_idx != -1, 
2266               "Must use this subfield after operand");
2267       assert( ! _may_reloc, "UnImplemented()");
2268       fprintf(_fp,"->base(ra_,this,idx%d)", _operand_idx);
2269     }
2270     else if ( strcmp(rep_var,"$index") == 0 ) {
2271       assert( _operand_idx != -1, 
2272               "Must use this subfield after operand");
2273       assert( ! _may_reloc, "UnImplemented()");
2274       fprintf(_fp,"->index(ra_,this,idx%d)", _operand_idx);
2275     }
2276     else if ( strcmp(rep_var,"$scale") == 0 ) {
2277       assert( ! _may_reloc, "UnImplemented()");
2278       fprintf(_fp,"->scale()");
2279     }
2280     else if ( strcmp(rep_var,"$cmpcode") == 0 ) {
2281       assert( ! _may_reloc, "UnImplemented()");
2282       fprintf(_fp,"->ccode()");
2283     }
2284     else if ( strcmp(rep_var,"$constant") == 0 ) {
2285       if( _constant_status == LITERAL_NOT_SEEN ) {
2286         if ( _constant_type == Form::idealD ) {
2287           fprintf(_fp,"->constantD()");
2288         } else if ( _constant_type == Form::idealF ) {
2289           fprintf(_fp,"->constantF()");
2290         } else if ( _constant_type == Form::idealL ) {
2291           fprintf(_fp,"->constantL()");
2292         } else {
2293           fprintf(_fp,"->constant()");
2294         }
2295       } else {
2296         assert( _constant_status == LITERAL_OUTPUT, "should have output constant literal in emit_rep_var");
2297         // Cosntant literal has already been sent to output file, nothing more needed
2298       }
2299     }
2300     else if ( strcmp(rep_var,"$disp") == 0 ) {
2301       Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
2302       if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
2303         fprintf(_fp,"->disp(ra_,this,0)");
2304       } else {
2305         fprintf(_fp,"->disp(ra_,this,idx%d)", _operand_idx);
2306       }
2307     }
2308     else if ( strcmp(rep_var,"$label") == 0 ) {
2309       fprintf(_fp,"->label()");
2310     }
2311     else if ( strcmp(rep_var,"$method") == 0 ) {
2312       fprintf(_fp,"->method()");
2313     }
2314     else {
2315       printf("emit_field: %s\n",rep_var);
2316       assert( false, "UnImplemented()");
2317     }
2318   }
2319 
2320 
2321   void emit_rep_var(const char *rep_var) {
2322     _processing_noninput = false;
2323     // A replacement variable, originally '$'
2324     if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
2325       if (!_inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(rep_var) )) {
2326         // Missing opcode
2327         _AD.syntax_err( _inst._linenum,
2328                         "Missing $%s opcode definition in %s, used by encoding %s\n",
2329                         rep_var, _inst._ident, _encoding._name);
2330       }
2331     }
2332     else {
2333       // Lookup its position in parameter list
2334       int   param_no  = _encoding.rep_var_index(rep_var);
2335       if ( param_no == -1 ) {
2336         _AD.syntax_err( _encoding._linenum,
2337                         "Replacement variable %s not found in enc_class %s.\n",
2338                         rep_var, _encoding._name);
2339       }
2340       // Lookup the corresponding ins_encode parameter
2341       const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
2342 
2343       // Check if instruction's actual parameter is a local name in the instruction
2344       const Form  *local     = _inst._localNames[inst_rep_var];
2345       OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
2346       // Note: assert removed to allow constant and symbolic parameters
2347       // assert( opc, "replacement variable was not found in local names");
2348       // Lookup the index position iff the replacement variable is a localName
2349       int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
2350       if( idx != -1 ) {
2351         if (_inst.is_noninput_operand(idx)) {
2352           // This operand isn't a normal input so printing it is done
2353           // specially.
2354           _processing_noninput = true;
2355         } else {
2356           // Output the emit code for this operand
2357           fprintf(_fp,"opnd_array(%d)",idx);
2358         }
2359         assert( _operand == opc->is_operand(),
2360                 "Previous emit $operand does not match current");
2361       }
2362       else if( ADLParser::is_literal_constant(inst_rep_var) ) {
2363         // else check if it is a constant expression
2364         // Removed following assert to allow primitive C types as arguments to encodings
2365         // assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
2366         fprintf(_fp,"(%s)", inst_rep_var);
2367         _constant_status = LITERAL_OUTPUT;
2368       }
2369       else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
2370         // else check if "primary", "secondary", "tertiary"
2371         assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
2372         if (!_inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(inst_rep_var) )) {
2373           // Missing opcode
2374           _AD.syntax_err( _inst._linenum,
2375                           "Missing $%s opcode definition in %s\n",
2376                           rep_var, _inst._ident);
2377 
2378         }
2379         _constant_status = LITERAL_OUTPUT;
2380       }
2381       else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
2382         // Instruction provided a literal register name for this parameter
2383         // Check that encoding specifies $$$reg to resolve.as register.
2384         assert( _reg_status == LITERAL_ACCESSED, "Must be processing a literal register parameter");
2385         fprintf(_fp,"(%s_enc)", inst_rep_var);
2386         _reg_status = LITERAL_OUTPUT;
2387       }
2388       else {
2389         // Check for unimplemented functionality before hard failure
2390         assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
2391         assert( false, "ShouldNotReachHere()");
2392       }
2393       // all done
2394     }
2395   }
2396 
2397 };  // end class DefineEmitState
2398 
2399 
2400 void ArchDesc::defineSize(FILE *fp, InstructForm &inst) {
2401   
2402   //(1)
2403   // Output instruction's emit prototype
2404   fprintf(fp,"uint  %sNode::size(PhaseRegAlloc *ra_) const {\n",
2405           inst._ident);
2406 
2407   fprintf(fp, " assert(VerifyOops || MachNode::size(ra_) <= %s, \"bad fixed size\");\n", inst._size);
2408 
2409   //(2)
2410   // Print the size
2411   fprintf(fp, " return (VerifyOops ? MachNode::size(ra_) : %s);\n", inst._size);
2412 
2413   // (3) and (4)
2414   fprintf(fp,"}\n");
2415 }
2416 
2417 void ArchDesc::defineEmit(FILE *fp, InstructForm &inst) {
2418   InsEncode *ins_encode = inst._insencode;
2419 
2420   // (1)
2421   // Output instruction's emit prototype
2422   fprintf(fp,"void  %sNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {\n",
2423           inst._ident);
2424 
2425   // If user did not define an encode section, 
2426   // provide stub that does not generate any machine code.
2427   if( (_encode == NULL) || (ins_encode == NULL) ) {
2428     fprintf(fp, "  // User did not define an encode section.\n");
2429     fprintf(fp,"}\n");
2430     return;
2431   }
2432 
2433   // Save current instruction's starting address (helps with relocation).
2434   fprintf( fp, "    cbuf.set_inst_mark();\n");
2435 
2436   // // // idx0 is only needed for syntactic purposes and only by "storeSSI"
2437   // fprintf( fp, "    unsigned idx0  = 0;\n");
2438 
2439   // Output each operand's offset into the array of registers.
2440   inst.index_temps( fp, _globalNames );
2441   
2442   // Output this instruction's encodings
2443   const char *ec_name;
2444   bool        user_defined = false;
2445   ins_encode->reset();
2446   while ( (ec_name = ins_encode->encode_class_iter()) != NULL ) {
2447     fprintf(fp, "  {");
2448     // Output user-defined encoding
2449     user_defined           = true;
2450 
2451     const char *ec_code    = NULL;
2452     const char *ec_rep_var = NULL;
2453     EncClass   *encoding   = _encode->encClass(ec_name);
2454     if (encoding == NULL) {
2455       fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
2456       abort();
2457     }
2458 
2459     if (ins_encode->current_encoding_num_args() != encoding->num_args()) {
2460       globalAD->syntax_err(ins_encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
2461                            inst._ident, ins_encode->current_encoding_num_args(),
2462                            ec_name, encoding->num_args());
2463     }
2464 
2465     DefineEmitState  pending(fp, *this, *encoding, *ins_encode, inst );
2466     encoding->_code.reset();
2467     encoding->_rep_vars.reset();
2468     // Process list of user-defined strings, 
2469     // and occurrences of replacement variables.
2470     // Replacement Vars are pushed into a list and then output
2471     while ( (ec_code = encoding->_code.iter()) != NULL ) {
2472       if ( ! encoding->_code.is_signal( ec_code ) ) {
2473         // Emit pending code
2474         pending.emit();
2475         pending.clear();
2476         // Emit this code section
2477         fprintf(fp,"%s", ec_code);
2478       } else {
2479         // A replacement variable or one of its subfields
2480         // Obtain replacement variable from list
2481         ec_rep_var  = encoding->_rep_vars.iter();
2482         pending.add_rep_var(ec_rep_var);
2483       }
2484     }
2485     // Emit pending code
2486     pending.emit();
2487     pending.clear();
2488     fprintf(fp, "}\n");
2489   } // end while instruction's encodings
2490 
2491   // Check if user stated which encoding to user
2492   if ( user_defined == false ) {
2493     fprintf(fp, "  // User did not define which encode class to use.\n");
2494   }
2495   
2496   // (3) and (4)
2497   fprintf(fp,"}\n");
2498 }
2499 
2500 // ---------------------------------------------------------------------------
2501 //--------Utilities to build MachOper and MachNode derived Classes------------
2502 // ---------------------------------------------------------------------------
2503 
2504 //------------------------------Utilities to build Operand Classes------------
2505 static void defineIn_RegMask(FILE *fp, FormDict &globals, OperandForm &oper) {
2506   uint num_edges = oper.num_edges(globals);
2507   if( num_edges != 0 ) {
2508     // Method header
2509     fprintf(fp, "const RegMask *%sOper::in_RegMask(int index) const {\n", 
2510             oper._ident);
2511 
2512     // Assert that the index is in range.
2513     fprintf(fp, "  assert(0 <= index && index < %d, \"index out of range\");\n",
2514             num_edges);
2515 
2516     // Figure out if all RegMasks are the same.
2517     const char* first_reg_class = oper.in_reg_class(0, globals);
2518     bool all_same = true;
2519     assert(first_reg_class != NULL, "did not find register mask");
2520 
2521     for (uint index = 1; all_same && index < num_edges; index++) {
2522       const char* some_reg_class = oper.in_reg_class(index, globals);
2523       assert(some_reg_class != NULL, "did not find register mask");
2524       if (strcmp(first_reg_class, some_reg_class) != 0) {
2525         all_same = false;
2526       }
2527     }
2528 
2529     if (all_same) {
2530       // Return the sole RegMask.
2531       if (strcmp(first_reg_class, "stack_slots") == 0) {
2532         fprintf(fp,"  return &(Compile::current()->FIRST_STACK_mask());\n");
2533       } else {
2534         fprintf(fp,"  return &%s_mask;\n", toUpper(first_reg_class));
2535       }
2536     } else {
2537       // Build a switch statement to return the desired mask.
2538       fprintf(fp,"  switch (index) {\n");
2539 
2540       for (uint index = 0; index < num_edges; index++) {
2541         const char *reg_class = oper.in_reg_class(index, globals);
2542         assert(reg_class != NULL, "did not find register mask");
2543         if( !strcmp(reg_class, "stack_slots") ) {
2544           fprintf(fp, "  case %d: return &(Compile::current()->FIRST_STACK_mask());\n", index);
2545         } else {
2546           fprintf(fp, "  case %d: return &%s_mask;\n", index, toUpper(reg_class));
2547         }
2548       }
2549       fprintf(fp,"  }\n");
2550       fprintf(fp,"  ShouldNotReachHere();\n");
2551       fprintf(fp,"  return NULL;\n");
2552     }
2553 
2554     // Method close
2555     fprintf(fp, "}\n\n");
2556   }
2557 }
2558 
2559 // generate code to create a clone for a class derived from MachOper
2560 // 
2561 // (0)  MachOper  *MachOperXOper::clone(Compile* C) const {
2562 // (1)    return new (C) MachXOper( _ccode, _c0, _c1, ..., _cn);
2563 // (2)  }
2564 // 
2565 static void defineClone(FILE *fp, FormDict &globalNames, OperandForm &oper) {
2566   fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper._ident);
2567   // Check for constants that need to be copied over
2568   const int  num_consts    = oper.num_consts(globalNames);
2569   const bool is_ideal_bool = oper.is_ideal_bool();
2570   if( (num_consts > 0) ) {
2571     fprintf(fp,"  return  new (C) %sOper(", oper._ident);
2572     // generate parameters for constants
2573     int i = 0;
2574     fprintf(fp,"_c%d", i);
2575     for( i = 1; i < num_consts; ++i) {
2576       fprintf(fp,", _c%d", i);
2577     }
2578     // finish line (1)
2579     fprintf(fp,");\n");
2580   }
2581   else {
2582     assert( num_consts == 0, "Currently support zero or one constant per operand clone function");
2583     fprintf(fp,"  return  new (C) %sOper();\n", oper._ident);
2584   }
2585   // finish method
2586   fprintf(fp,"}\n");
2587 }
2588 
2589 static void define_hash(FILE *fp, char *operand) {
2590   fprintf(fp,"uint %sOper::hash() const { return 5; }\n", operand);
2591 }
2592 
2593 static void define_cmp(FILE *fp, char *operand) {
2594   fprintf(fp,"uint %sOper::cmp( const MachOper &oper ) const { return opcode() == oper.opcode(); }\n", operand);
2595 }
2596 
2597 
2598 // Helper functions for bug 4796752, abstracted with minimal modification 
2599 // from define_oper_interface()
2600 OperandForm *rep_var_to_operand(const char *encoding, OperandForm &oper, FormDict &globals) {
2601   OperandForm *op = NULL;
2602   // Check for replacement variable
2603   if( *encoding == '$' ) {
2604     // Replacement variable
2605     const char *rep_var = encoding + 1;
2606     // Lookup replacement variable, rep_var, in operand's component list
2607     const Component *comp = oper._components.search(rep_var);
2608     assert( comp != NULL, "Replacement variable not found in components");
2609     // Lookup operand form for replacement variable's type
2610     const char      *type = comp->_type;
2611     Form            *form = (Form*)globals[type];
2612     assert( form != NULL, "Replacement variable's type not found");
2613     op = form->is_operand();
2614     assert( op, "Attempting to emit a non-register or non-constant");
2615   }
2616 
2617   return op;
2618 }
2619 
2620 int rep_var_to_constant_index(const char *encoding, OperandForm &oper, FormDict &globals) {
2621   int idx = -1;
2622   // Check for replacement variable
2623   if( *encoding == '$' ) {
2624     // Replacement variable
2625     const char *rep_var = encoding + 1;
2626     // Lookup replacement variable, rep_var, in operand's component list
2627     const Component *comp = oper._components.search(rep_var);
2628     assert( comp != NULL, "Replacement variable not found in components");
2629     // Lookup operand form for replacement variable's type
2630     const char      *type = comp->_type;
2631     Form            *form = (Form*)globals[type];
2632     assert( form != NULL, "Replacement variable's type not found");
2633     OperandForm *op = form->is_operand();
2634     assert( op, "Attempting to emit a non-register or non-constant");
2635     // Check that this is a constant and find constant's index:
2636     if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2637       idx  = oper.constant_position(globals, comp);
2638     }
2639   }
2640 
2641   return idx;
2642 }
2643 
2644 bool is_regI(const char *encoding, OperandForm &oper, FormDict &globals ) {
2645   bool is_regI = false;
2646 
2647   OperandForm *op = rep_var_to_operand(encoding, oper, globals);
2648   if( op != NULL ) {
2649     // Check that this is a register 
2650     if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
2651       // Register
2652       const char* ideal  = op->ideal_type(globals);
2653       is_regI = (ideal && (op->ideal_to_Reg_type(ideal) == Form::idealI));
2654     }
2655   }
2656 
2657   return is_regI;
2658 }
2659 
2660 bool is_conP(const char *encoding, OperandForm &oper, FormDict &globals ) {
2661   bool is_conP = false;
2662 
2663   OperandForm *op = rep_var_to_operand(encoding, oper, globals);
2664   if( op != NULL ) {
2665     // Check that this is a constant pointer
2666     if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2667       // Constant
2668       Form::DataType dtype = op->is_base_constant(globals);
2669       is_conP = (dtype == Form::idealP);
2670     }
2671   }
2672 
2673   return is_conP;
2674 }
2675 
2676 
2677 // Define a MachOper interface methods
2678 void ArchDesc::define_oper_interface(FILE *fp, OperandForm &oper, FormDict &globals,
2679                                      const char *name, const char *encoding) {
2680   bool emit_position = false;
2681   int position = -1;
2682 
2683   fprintf(fp,"  virtual int            %s", name);
2684   // Generate access method for base, index, scale, disp, ...
2685   if( (strcmp(name,"base") == 0) || (strcmp(name,"index") == 0) ) {
2686     fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
2687     emit_position = true;
2688   } else if ( (strcmp(name,"disp") == 0) ) {
2689     fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
2690   } else {
2691     fprintf(fp,"() const { ");
2692   }
2693 
2694   // Check for hexadecimal value OR replacement variable
2695   if( *encoding == '$' ) {
2696     // Replacement variable
2697     const char *rep_var = encoding + 1;
2698     fprintf(fp,"// Replacement variable: %s\n", encoding+1);
2699     // Lookup replacement variable, rep_var, in operand's component list
2700     const Component *comp = oper._components.search(rep_var);
2701     assert( comp != NULL, "Replacement variable not found in components");
2702     // Lookup operand form for replacement variable's type
2703     const char      *type = comp->_type;
2704     Form            *form = (Form*)globals[type];
2705     assert( form != NULL, "Replacement variable's type not found");
2706     OperandForm *op = form->is_operand();
2707     assert( op, "Attempting to emit a non-register or non-constant");
2708     // Check that this is a register or a constant and generate code:
2709     if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
2710       // Register
2711       int idx_offset = oper.register_position( globals, rep_var);
2712       position = idx_offset;
2713       fprintf(fp,"    return (int)ra_->get_encode(node->in(idx");
2714       if ( idx_offset > 0 ) fprintf(fp,                      "+%d",idx_offset);
2715       fprintf(fp,"));\n");
2716     } else if ( op->ideal_to_sReg_type(op->_ident) != Form::none ) {
2717       // StackSlot for an sReg comes either from input node or from self, when idx==0
2718       fprintf(fp,"    if( idx != 0 ) {\n");
2719       fprintf(fp,"      // Access register number for input operand\n");
2720       fprintf(fp,"      return ra_->reg2offset(ra_->get_reg_first(node->in(idx)));/* sReg */\n");
2721       fprintf(fp,"    }\n");
2722       fprintf(fp,"    // Access register number from myself\n");
2723       fprintf(fp,"    return ra_->reg2offset(ra_->get_reg_first(node));/* sReg */\n");
2724     } else if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2725       // Constant
2726       // Check which constant this name maps to: _c0, _c1, ..., _cn
2727       const int idx = oper.constant_position(globals, comp);
2728       assert( idx != -1, "Constant component not found in operand");
2729       // Output code for this constant, type dependent.
2730       fprintf(fp,"    return (int)" );
2731       oper.access_constant(fp, globals, (uint)idx /* , const_type */);
2732       fprintf(fp,";\n");
2733     } else {
2734       assert( false, "Attempting to emit a non-register or non-constant");
2735     }
2736   } 
2737   else if( *encoding == '0' && *(encoding+1) == 'x' ) {
2738     // Hex value
2739     fprintf(fp,"return %s;", encoding);
2740   } else {
2741     assert( false, "Do not support octal or decimal encode constants");
2742   }
2743   fprintf(fp,"  }\n");
2744 
2745   if( emit_position && (position != -1) && (oper.num_edges(globals) > 0) ) {
2746     fprintf(fp,"  virtual int            %s_position() const { return %d; }\n", name, position);
2747     MemInterface *mem_interface = oper._interface->is_MemInterface();
2748     const char *base = mem_interface->_base;
2749     const char *disp = mem_interface->_disp;
2750     if( emit_position && (strcmp(name,"base") == 0) 
2751         && base != NULL && is_regI(base, oper, globals) 
2752         && disp != NULL && is_conP(disp, oper, globals) ) {
2753       // Found a memory access using a constant pointer for a displacement 
2754       // and a base register containing an integer offset.
2755       // In this case the base and disp are reversed with respect to what 
2756       // is expected by MachNode::get_base_and_disp() and MachNode::adr_type().
2757       // Provide a non-NULL return for disp_as_type() that will allow adr_type()
2758       // to correctly compute the access type for alias analysis.
2759       // 
2760       // See BugId 4796752, operand indOffset32X in i486.ad
2761       int idx = rep_var_to_constant_index(disp, oper, globals);
2762       fprintf(fp,"  virtual const TypePtr *disp_as_type() const { return _c%d; }\n", idx);
2763     }
2764   }
2765 }
2766 
2767 //
2768 // Construct the method to copy _idx, inputs and operands to new node.
2769 static void define_fill_new_machnode(bool used, FILE *fp_cpp) {
2770   fprintf(fp_cpp, "\n");
2771   fprintf(fp_cpp, "// Copy _idx, inputs and operands to new node\n");
2772   fprintf(fp_cpp, "void MachNode::fill_new_machnode( MachNode* node, Compile* C) const {\n");
2773   if( !used ) {
2774     fprintf(fp_cpp, "  // This architecture does not have cisc or short branch instructions\n");
2775     fprintf(fp_cpp, "  ShouldNotCallThis();\n");
2776     fprintf(fp_cpp, "}\n");
2777   } else {
2778     // New node must use same node index for access through allocator's tables
2779     fprintf(fp_cpp, "  // New node must use same node index\n");
2780     fprintf(fp_cpp, "  node->set_idx( _idx );\n");
2781     // Copy machine-independent inputs
2782     fprintf(fp_cpp, "  // Copy machine-independent inputs\n");
2783     fprintf(fp_cpp, "  for( uint j = 0; j < req(); j++ ) {\n");
2784     fprintf(fp_cpp, "    node->add_req(in(j));\n");
2785     fprintf(fp_cpp, "  }\n");
2786     // Copy machine operands to new MachNode
2787     fprintf(fp_cpp, "  // Copy my operands, except for cisc position\n");
2788     fprintf(fp_cpp, "  int nopnds = num_opnds();\n");
2789     fprintf(fp_cpp, "  assert( node->num_opnds() == (uint)nopnds, \"Must have same number of operands\");\n");
2790     fprintf(fp_cpp, "  MachOper **to = node->_opnds;\n");
2791     fprintf(fp_cpp, "  for( int i = 0; i < nopnds; i++ ) {\n");
2792     fprintf(fp_cpp, "    if( i != cisc_operand() ) \n");
2793     fprintf(fp_cpp, "      to[i] = _opnds[i]->clone(C);\n");
2794     fprintf(fp_cpp, "  }\n");
2795     fprintf(fp_cpp, "}\n");
2796   }
2797   fprintf(fp_cpp, "\n");
2798 }
2799 
2800 //------------------------------defineClasses----------------------------------
2801 // Define members of MachNode and MachOper classes based on 
2802 // operand and instruction lists
2803 void ArchDesc::defineClasses(FILE *fp) {
2804 
2805   // Define the contents of an array containing the machine register names
2806   defineRegNames(fp, _register);
2807   // Define an array containing the machine register encoding values
2808   defineRegEncodes(fp, _register);
2809   // Generate an enumeration of user-defined register classes
2810   // and a list of register masks, one for each class.
2811   // Only define the RegMask value objects in the expand file.
2812   // Declare each as an extern const RegMask ...; in ad_<arch>.hpp
2813   declare_register_masks(_HPP_file._fp);
2814   // build_register_masks(fp);
2815   build_register_masks(_CPP_EXPAND_file._fp);
2816   // Define the pipe_classes
2817   build_pipe_classes(_CPP_PIPELINE_file._fp);
2818 
2819   // Generate Machine Classes for each operand defined in AD file
2820   fprintf(fp,"\n");
2821   fprintf(fp,"\n");
2822   fprintf(fp,"//------------------Define classes derived from MachOper---------------------\n");
2823   // Iterate through all operands
2824   _operands.reset(); 
2825   OperandForm *oper;
2826   for( ; (oper = (OperandForm*)_operands.iter()) != NULL; ) {
2827     // Ensure this is a machine-world instruction
2828     if ( oper->ideal_only() ) continue;
2829     // !!!!!
2830     // The declaration of labelOper is in machine-independent file: machnode
2831     if ( strcmp(oper->_ident,"label") == 0 ) {
2832       defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);
2833 
2834       fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
2835       fprintf(fp,"  return  new (C) %sOper(_label, _block_num);\n", oper->_ident);
2836       fprintf(fp,"}\n");
2837 
2838       fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
2839               oper->_ident, machOperEnum(oper->_ident));
2840       // // Currently all XXXOper::Hash() methods are identical (990820)
2841       // define_hash(fp, oper->_ident);
2842       // // Currently all XXXOper::Cmp() methods are identical (990820)
2843       // define_cmp(fp, oper->_ident);
2844       fprintf(fp,"\n");
2845 
2846       continue;
2847     }
2848 
2849     // The declaration of methodOper is in machine-independent file: machnode
2850     if ( strcmp(oper->_ident,"method") == 0 ) {
2851       defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);
2852 
2853       fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
2854       fprintf(fp,"  return  new (C) %sOper(_method);\n", oper->_ident);
2855       fprintf(fp,"}\n");
2856 
2857       fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
2858               oper->_ident, machOperEnum(oper->_ident));
2859       // // Currently all XXXOper::Hash() methods are identical (990820)
2860       // define_hash(fp, oper->_ident);
2861       // // Currently all XXXOper::Cmp() methods are identical (990820)
2862       // define_cmp(fp, oper->_ident);
2863       fprintf(fp,"\n");
2864 
2865       continue;
2866     }
2867 
2868     defineIn_RegMask(fp, _globalNames, *oper);
2869     defineClone(_CPP_CLONE_file._fp, _globalNames, *oper);
2870     // // Currently all XXXOper::Hash() methods are identical (990820)
2871     // define_hash(fp, oper->_ident);
2872     // // Currently all XXXOper::Cmp() methods are identical (990820)
2873     // define_cmp(fp, oper->_ident);
2874 
2875     // side-call to generate output that used to be in the header file:
2876     extern void gen_oper_format(FILE *fp, FormDict &globals, OperandForm &oper, bool for_c_file);
2877     gen_oper_format(_CPP_FORMAT_file._fp, _globalNames, *oper, true);
2878 
2879   }
2880 
2881 
2882   // Generate Machine Classes for each instruction defined in AD file
2883   fprintf(fp,"//------------------Define members for classes derived from MachNode----------\n");
2884   // Output the definitions for out_RegMask() // & kill_RegMask()
2885   _instructions.reset();
2886   InstructForm *instr;
2887   MachNodeForm *machnode;
2888   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2889     // Ensure this is a machine-world instruction
2890     if ( instr->ideal_only() ) continue;
2891 
2892     defineOut_RegMask(_CPP_MISC_file._fp, instr->_ident, reg_mask(*instr));
2893   }
2894 
2895   bool used = false;
2896   // Output the definitions for expand rules & peephole rules
2897   _instructions.reset(); 
2898   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2899     // Ensure this is a machine-world instruction
2900     if ( instr->ideal_only() ) continue;
2901     // If there are multiple defs/kills, or an explicit expand rule, build rule
2902     if( instr->expands() || instr->needs_projections() ||
2903         instr->has_temps() ||
2904         instr->_matrule != NULL && 
2905         instr->num_opnds() != instr->num_unique_opnds() ) 
2906       defineExpand(_CPP_EXPAND_file._fp, instr);
2907     // If there is an explicit peephole rule, build it
2908     if ( instr->peepholes() )
2909       definePeephole(_CPP_PEEPHOLE_file._fp, instr);
2910 
2911     // Output code to convert to the cisc version, if applicable
2912     used |= instr->define_cisc_version(*this, fp);
2913 
2914     // Output code to convert to the short branch version, if applicable
2915     used |= instr->define_short_branch_methods(fp);
2916   }
2917 
2918   // Construct the method called by cisc_version() to copy inputs and operands.
2919   define_fill_new_machnode(used, fp);
2920 
2921   // Output the definitions for labels
2922   _instructions.reset(); 
2923   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
2924     // Ensure this is a machine-world instruction
2925     if ( instr->ideal_only() ) continue;
2926 
2927     // Access the fields for operand Label
2928     int label_position = instr->label_position();
2929     if( label_position != -1 ) {
2930       // Set the label
2931       fprintf(fp,"void %sNode::label_set( Label& label, uint block_num ) {\n", instr->_ident);
2932       fprintf(fp,"  labelOper* oper  = (labelOper*)(opnd_array(%d));\n",
2933               label_position );
2934       fprintf(fp,"  oper->_label     = &label;\n");
2935       fprintf(fp,"  oper->_block_num = block_num;\n");
2936       fprintf(fp,"}\n");
2937     }
2938   }
2939 
2940   // Output the definitions for methods
2941   _instructions.reset(); 
2942   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
2943     // Ensure this is a machine-world instruction
2944     if ( instr->ideal_only() ) continue;
2945 
2946     // Access the fields for operand Label
2947     int method_position = instr->method_position();
2948     if( method_position != -1 ) {
2949       // Access the method's address
2950       fprintf(fp,"void %sNode::method_set( intptr_t method ) {\n", instr->_ident);
2951       fprintf(fp,"  ((methodOper*)opnd_array(%d))->_method = method;\n",
2952               method_position );
2953       fprintf(fp,"}\n");
2954       fprintf(fp,"\n");
2955     }
2956   }
2957 
2958   // Define this instruction's number of relocation entries, base is '0'
2959   _instructions.reset(); 
2960   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
2961     // Output the definition for number of relocation entries
2962     uint reloc_size = instr->reloc(_globalNames);
2963     if ( reloc_size != 0 ) {
2964       fprintf(fp,"int  %sNode::reloc()   const {\n", instr->_ident);
2965       fprintf(fp,  "  return  %d;\n", reloc_size );
2966       fprintf(fp,"}\n");
2967       fprintf(fp,"\n");
2968     }
2969   }
2970   fprintf(fp,"\n");
2971 
2972   // Output the definitions for code generation
2973   // 
2974   // address  ___Node::emit(address ptr, PhaseRegAlloc *ra_) const {
2975   //   // ...  encoding defined by user
2976   //   return ptr;
2977   // }
2978   //
2979   _instructions.reset(); 
2980   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2981     // Ensure this is a machine-world instruction
2982     if ( instr->ideal_only() ) continue;
2983 
2984     if (instr->_insencode) defineEmit(fp, *instr);
2985     if (instr->_size)      defineSize(fp, *instr);
2986 
2987     // side-call to generate output that used to be in the header file:
2988     extern void gen_inst_format(FILE *fp, FormDict &globals, InstructForm &oper, bool for_c_file);
2989     gen_inst_format(_CPP_FORMAT_file._fp, _globalNames, *instr, true);
2990   }
2991 
2992   // Output the definitions for alias analysis
2993   _instructions.reset(); 
2994   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2995     // Ensure this is a machine-world instruction
2996     if ( instr->ideal_only() ) continue;
2997 
2998     // Analyze machine instructions that either USE or DEF memory.
2999     int memory_operand = instr->memory_operand(_globalNames);
3000     // Some guys kill all of memory
3001     if ( instr->is_wide_memory_kill(_globalNames) ) {
3002       memory_operand = InstructForm::MANY_MEMORY_OPERANDS;
3003     }
3004 
3005     if ( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
3006       if( memory_operand == InstructForm::MANY_MEMORY_OPERANDS ) {
3007         fprintf(fp,"const TypePtr *%sNode::adr_type() const { return TypePtr::BOTTOM; }\n", instr->_ident);
3008         fprintf(fp,"const MachOper* %sNode::memory_operand() const { return (MachOper*)-1; }\n", instr->_ident);
3009       } else {
3010         fprintf(fp,"const MachOper* %sNode::memory_operand() const { return _opnds[%d]; }\n", instr->_ident, memory_operand);
3011   }
3012     }
3013   }
3014 
3015   // Get the length of the longest identifier
3016   int max_ident_len = 0;
3017   _instructions.reset();
3018 
3019   for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3020     if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
3021       int ident_len = (int)strlen(instr->_ident);
3022       if( max_ident_len < ident_len )
3023         max_ident_len = ident_len;
3024     }
3025   }
3026 
3027   // Emit specifically for Node(s)
3028   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
3029     max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
3030   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return %s; }\n",
3031     max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
3032   fprintf(_CPP_PIPELINE_file._fp, "\n");
3033 
3034   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
3035     max_ident_len, "MachNode", _pipeline ? "(&pipeline_class_Unknown_Instructions)" : "NULL");
3036   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return pipeline_class(); }\n",
3037     max_ident_len, "MachNode");
3038   fprintf(_CPP_PIPELINE_file._fp, "\n");
3039 
3040   // Output the definitions for machine node specific pipeline data
3041   _machnodes.reset();
3042 
3043   for ( ; (machnode = (MachNodeForm*)_machnodes.iter()) != NULL; ) {
3044     fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
3045       machnode->_ident, ((class PipeClassForm *)_pipeline->_classdict[machnode->_machnode_pipe])->_num);
3046   }
3047 
3048   fprintf(_CPP_PIPELINE_file._fp, "\n");
3049 
3050   // Output the definitions for instruction pipeline static data references
3051   _instructions.reset();
3052 
3053   for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3054     if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
3055       fprintf(_CPP_PIPELINE_file._fp, "\n");
3056       fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline_class() { return (&pipeline_class_%03d); }\n",
3057         max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
3058       fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
3059         max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
3060     }
3061   }
3062 }
3063 
3064 
3065 // -------------------------------- maps ------------------------------------
3066 
3067 // Information needed to generate the ReduceOp mapping for the DFA
3068 class OutputReduceOp : public OutputMap {
3069 public:
3070   OutputReduceOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3071     : OutputMap(hpp, cpp, globals, AD) {};
3072 
3073   void declaration() { fprintf(_hpp, "extern const int   reduceOp[];\n"); }
3074   void definition()  { fprintf(_cpp, "const        int   reduceOp[] = {\n"); }
3075   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3076                        OutputMap::closing();
3077   }
3078   void map(OpClassForm &opc)  { 
3079     const char *reduce = opc._ident;
3080     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3081     else          fprintf(_cpp, "  0");
3082   }
3083   void map(OperandForm &oper) {
3084     // Most operands without match rules, e.g.  eFlagsReg, do not have a result operand
3085     const char *reduce = (oper._matrule ? oper.reduce_result() : NULL);
3086     // operand stackSlot does not have a match rule, but produces a stackSlot
3087     if( oper.is_user_name_for_sReg() != Form::none ) reduce = oper.reduce_result();
3088     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3089     else          fprintf(_cpp, "  0");
3090   }
3091   void map(InstructForm &inst) {
3092     const char *reduce = (inst._matrule ? inst.reduce_result() : NULL);
3093     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3094     else          fprintf(_cpp, "  0");
3095   }
3096   void map(char         *reduce) { 
3097     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3098     else          fprintf(_cpp, "  0");
3099   }
3100 };
3101 
3102 // Information needed to generate the LeftOp mapping for the DFA
3103 class OutputLeftOp : public OutputMap {
3104 public:
3105   OutputLeftOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3106     : OutputMap(hpp, cpp, globals, AD) {};
3107 
3108   void declaration() { fprintf(_hpp, "extern const int   leftOp[];\n"); }
3109   void definition()  { fprintf(_cpp, "const        int   leftOp[] = {\n"); }
3110   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3111                        OutputMap::closing();
3112   }
3113   void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
3114   void map(OperandForm &oper) {
3115     const char *reduce = oper.reduce_left(_globals);
3116     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3117     else          fprintf(_cpp, "  0");
3118   }
3119   void map(char        *name) {
3120     const char *reduce = _AD.reduceLeft(name);
3121     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3122     else          fprintf(_cpp, "  0");
3123   }
3124   void map(InstructForm &inst) {
3125     const char *reduce = inst.reduce_left(_globals);
3126     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3127     else          fprintf(_cpp, "  0");
3128   }
3129 };
3130 
3131 
3132 // Information needed to generate the RightOp mapping for the DFA
3133 class OutputRightOp : public OutputMap {
3134 public:
3135   OutputRightOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3136     : OutputMap(hpp, cpp, globals, AD) {};
3137 
3138   void declaration() { fprintf(_hpp, "extern const int   rightOp[];\n"); }
3139   void definition()  { fprintf(_cpp, "const        int   rightOp[] = {\n"); }
3140   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3141                        OutputMap::closing();
3142   }
3143   void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
3144   void map(OperandForm &oper) {
3145     const char *reduce = oper.reduce_right(_globals);
3146     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3147     else          fprintf(_cpp, "  0");
3148   }
3149   void map(char        *name) {
3150     const char *reduce = _AD.reduceRight(name);
3151     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3152     else          fprintf(_cpp, "  0");
3153   }
3154   void map(InstructForm &inst) {
3155     const char *reduce = inst.reduce_right(_globals);
3156     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3157     else          fprintf(_cpp, "  0");
3158   }
3159 };
3160 
3161 
3162 // Information needed to generate the Rule names for the DFA
3163 class OutputRuleName : public OutputMap {
3164 public:
3165   OutputRuleName(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3166     : OutputMap(hpp, cpp, globals, AD) {};
3167 
3168   void declaration() { fprintf(_hpp, "extern const char *ruleName[];\n"); }
3169   void definition()  { fprintf(_cpp, "const char        *ruleName[] = {\n"); }
3170   void closing()     { fprintf(_cpp, "  \"no trailing comma\"\n");
3171                        OutputMap::closing();
3172   }
3173   void map(OpClassForm &opc)  { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(opc._ident) ); }
3174   void map(OperandForm &oper) { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(oper._ident) ); }
3175   void map(char        *name) { fprintf(_cpp, "  \"%s\"", name ? name : "0"); }
3176   void map(InstructForm &inst){ fprintf(_cpp, "  \"%s\"", inst._ident ? inst._ident : "0"); }
3177 };
3178 
3179 
3180 // Information needed to generate the swallowed mapping for the DFA
3181 class OutputSwallowed : public OutputMap {
3182 public:
3183   OutputSwallowed(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3184     : OutputMap(hpp, cpp, globals, AD) {};
3185 
3186   void declaration() { fprintf(_hpp, "extern const bool  swallowed[];\n"); }
3187   void definition()  { fprintf(_cpp, "const        bool  swallowed[] = {\n"); }
3188   void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
3189                        OutputMap::closing();
3190   }
3191   void map(OperandForm &oper) { // Generate the entry for this opcode
3192     const char *swallowed = oper.swallowed(_globals) ? "true" : "false";
3193     fprintf(_cpp, "  %s", swallowed);
3194   }
3195   void map(OpClassForm &opc)  { fprintf(_cpp, "  false"); }
3196   void map(char        *name) { fprintf(_cpp, "  false"); }
3197   void map(InstructForm &inst){ fprintf(_cpp, "  false"); }
3198 };
3199 
3200 
3201 // Information needed to generate the decision array for instruction chain rule
3202 class OutputInstChainRule : public OutputMap {
3203 public:
3204   OutputInstChainRule(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3205     : OutputMap(hpp, cpp, globals, AD) {};
3206 
3207   void declaration() { fprintf(_hpp, "extern const bool  instruction_chain_rule[];\n"); }
3208   void definition()  { fprintf(_cpp, "const        bool  instruction_chain_rule[] = {\n"); }
3209   void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
3210                        OutputMap::closing();
3211   }
3212   void map(OpClassForm &opc)   { fprintf(_cpp, "  false"); }
3213   void map(OperandForm &oper)  { fprintf(_cpp, "  false"); }
3214   void map(char        *name)  { fprintf(_cpp, "  false"); }
3215   void map(InstructForm &inst) { // Check for simple chain rule
3216     const char *chain = inst.is_simple_chain_rule(_globals) ? "true" : "false";
3217     fprintf(_cpp, "  %s", chain);
3218   }
3219 };
3220 
3221 
3222 //---------------------------build_map------------------------------------
3223 // Build  mapping from enumeration for densely packed operands
3224 // TO result and child types.
3225 void ArchDesc::build_map(OutputMap &map) {
3226   FILE         *fp_hpp = map.decl_file();
3227   FILE         *fp_cpp = map.def_file();
3228   int           idx    = 0;
3229   OperandForm  *op;
3230   OpClassForm  *opc;
3231   InstructForm *inst;
3232 
3233   // Construct this mapping
3234   map.declaration();
3235   fprintf(fp_cpp,"\n");
3236   map.definition();
3237   
3238   // Output the mapping for operands
3239   map.record_position(OutputMap::BEGIN_OPERANDS, idx );
3240   _operands.reset(); 
3241   for(; (op = (OperandForm*)_operands.iter()) != NULL; ) {
3242     // Ensure this is a machine-world instruction
3243     if ( op->ideal_only() )  continue;
3244 
3245     // Generate the entry for this opcode
3246     map.map(*op);    fprintf(fp_cpp, ", // %d\n", idx);
3247     ++idx;
3248   };
3249   fprintf(fp_cpp, "  // last operand\n");
3250 
3251   // Place all user-defined operand classes into the mapping
3252   map.record_position(OutputMap::BEGIN_OPCLASSES, idx );
3253   _opclass.reset(); 
3254   for(; (opc = (OpClassForm*)_opclass.iter()) != NULL; ) {
3255     map.map(*opc);    fprintf(fp_cpp, ", // %d\n", idx);
3256     ++idx;
3257   };
3258   fprintf(fp_cpp, "  // last operand class\n");
3259 
3260   // Place all internally defined operands into the mapping
3261   map.record_position(OutputMap::BEGIN_INTERNALS, idx );
3262   _internalOpNames.reset(); 
3263   char *name = NULL;
3264   for(; (name = (char *)_internalOpNames.iter()) != NULL; ) {
3265     map.map(name);    fprintf(fp_cpp, ", // %d\n", idx);
3266     ++idx;
3267   };
3268   fprintf(fp_cpp, "  // last internally defined operand\n");
3269 
3270   // Place all user-defined instructions into the mapping
3271   if( map.do_instructions() ) {
3272     map.record_position(OutputMap::BEGIN_INSTRUCTIONS, idx );
3273     // Output all simple instruction chain rules first
3274     map.record_position(OutputMap::BEGIN_INST_CHAIN_RULES, idx );
3275     {
3276       _instructions.reset(); 
3277       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3278         // Ensure this is a machine-world instruction
3279         if ( inst->ideal_only() )  continue;
3280         if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
3281         if ( inst->rematerialize(_globalNames, get_registers()) ) continue;
3282         
3283         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3284         ++idx;
3285       };
3286       map.record_position(OutputMap::BEGIN_REMATERIALIZE, idx );
3287       _instructions.reset(); 
3288       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3289         // Ensure this is a machine-world instruction
3290         if ( inst->ideal_only() )  continue;
3291         if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
3292         if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;
3293         
3294         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3295         ++idx;
3296       };
3297       map.record_position(OutputMap::END_INST_CHAIN_RULES, idx );
3298     }
3299     // Output all instructions that are NOT simple chain rules
3300     {
3301       _instructions.reset(); 
3302       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3303         // Ensure this is a machine-world instruction
3304         if ( inst->ideal_only() )  continue;
3305         if ( inst->is_simple_chain_rule(_globalNames) ) continue;
3306         if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;
3307         
3308         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3309         ++idx;
3310       };
3311       map.record_position(OutputMap::END_REMATERIALIZE, idx );
3312       _instructions.reset(); 
3313       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3314         // Ensure this is a machine-world instruction
3315         if ( inst->ideal_only() )  continue;
3316         if ( inst->is_simple_chain_rule(_globalNames) ) continue;
3317         if ( inst->rematerialize(_globalNames, get_registers()) ) continue;
3318         
3319         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3320         ++idx;
3321       };
3322     }
3323     fprintf(fp_cpp, "  // last instruction\n");
3324     map.record_position(OutputMap::END_INSTRUCTIONS, idx );
3325   }
3326   // Finish defining table
3327   map.closing();
3328 };
3329 
3330 
3331 // Helper function for buildReduceMaps
3332 char reg_save_policy(const char *calling_convention) {
3333   char callconv;
3334 
3335   if      (!strcmp(calling_convention, "NS"))  callconv = 'N';
3336   else if (!strcmp(calling_convention, "SOE")) callconv = 'E';
3337   else if (!strcmp(calling_convention, "SOC")) callconv = 'C';
3338   else if (!strcmp(calling_convention, "AS"))  callconv = 'A';
3339   else                                         callconv = 'Z';
3340 
3341   return callconv;
3342 }
3343 
3344 //---------------------------generate_assertion_checks-------------------
3345 void ArchDesc::generate_adlc_verification(FILE *fp_cpp) {
3346   fprintf(fp_cpp, "\n");
3347 
3348   fprintf(fp_cpp, "#ifndef PRODUCT\n");
3349   fprintf(fp_cpp, "void Compile::adlc_verification() {\n");
3350   globalDefs().print_asserts(fp_cpp);
3351   fprintf(fp_cpp, "}\n");
3352   fprintf(fp_cpp, "#endif\n");
3353   fprintf(fp_cpp, "\n");
3354 }
3355 
3356 //---------------------------addSourceBlocks-----------------------------
3357 void ArchDesc::addSourceBlocks(FILE *fp_cpp) {
3358   if (_source.count() > 0)
3359     _source.output(fp_cpp);
3360 
3361   generate_adlc_verification(fp_cpp);
3362 }
3363 //---------------------------addHeaderBlocks-----------------------------
3364 void ArchDesc::addHeaderBlocks(FILE *fp_hpp) {
3365   if (_header.count() > 0)
3366     _header.output(fp_hpp); 
3367 }
3368 //-------------------------addPreHeaderBlocks----------------------------
3369 void ArchDesc::addPreHeaderBlocks(FILE *fp_hpp) {
3370   // Output #defines from definition block
3371   globalDefs().print_defines(fp_hpp);
3372 
3373   if (_pre_header.count() > 0)
3374     _pre_header.output(fp_hpp); 
3375 }
3376 
3377 //---------------------------buildReduceMaps-----------------------------
3378 // Build  mapping from enumeration for densely packed operands
3379 // TO result and child types.
3380 void ArchDesc::buildReduceMaps(FILE *fp_hpp, FILE *fp_cpp) {
3381   RegDef       *rdef;
3382   RegDef       *next;
3383 
3384   // The emit bodies currently require functions defined in the source block.
3385 
3386   // Build external declarations for mappings
3387   fprintf(fp_hpp, "\n");
3388   fprintf(fp_hpp, "extern const char  register_save_policy[];\n");
3389   fprintf(fp_hpp, "extern const char  c_reg_save_policy[];\n");
3390   fprintf(fp_hpp, "extern const int   register_save_type[];\n");
3391   fprintf(fp_hpp, "\n");
3392 
3393   // Construct Save-Policy array
3394   fprintf(fp_cpp, "// Map from machine-independent register number to register_save_policy\n");
3395   fprintf(fp_cpp, "const        char register_save_policy[] = {\n");
3396   _register->reset_RegDefs();
3397   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3398     next              = _register->iter_RegDefs();
3399     char policy       = reg_save_policy(rdef->_callconv);
3400     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3401     fprintf(fp_cpp, "  '%c'%s\n", policy, comma);
3402   }
3403   fprintf(fp_cpp, "};\n\n");
3404 
3405   // Construct Native Save-Policy array
3406   fprintf(fp_cpp, "// Map from machine-independent register number to c_reg_save_policy\n");
3407   fprintf(fp_cpp, "const        char c_reg_save_policy[] = {\n");
3408   _register->reset_RegDefs();
3409   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3410     next        = _register->iter_RegDefs();
3411     char policy = reg_save_policy(rdef->_c_conv);
3412     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3413     fprintf(fp_cpp, "  '%c'%s\n", policy, comma);
3414   }
3415   fprintf(fp_cpp, "};\n\n");
3416 
3417   // Construct Register Save Type array
3418   fprintf(fp_cpp, "// Map from machine-independent register number to register_save_type\n");
3419   fprintf(fp_cpp, "const        int register_save_type[] = {\n");
3420   _register->reset_RegDefs();
3421   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3422     next = _register->iter_RegDefs();
3423     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3424     fprintf(fp_cpp, "  %s%s\n", rdef->_idealtype, comma);
3425   }
3426   fprintf(fp_cpp, "};\n\n");
3427 
3428   // Construct the table for reduceOp
3429   OutputReduceOp output_reduce_op(fp_hpp, fp_cpp, _globalNames, *this);
3430   build_map(output_reduce_op);
3431   // Construct the table for leftOp
3432   OutputLeftOp output_left_op(fp_hpp, fp_cpp, _globalNames, *this);
3433   build_map(output_left_op);
3434   // Construct the table for rightOp
3435   OutputRightOp output_right_op(fp_hpp, fp_cpp, _globalNames, *this);
3436   build_map(output_right_op);
3437   // Construct the table of rule names
3438   OutputRuleName output_rule_name(fp_hpp, fp_cpp, _globalNames, *this);
3439   build_map(output_rule_name);
3440   // Construct the boolean table for subsumed operands
3441   OutputSwallowed output_swallowed(fp_hpp, fp_cpp, _globalNames, *this);
3442   build_map(output_swallowed);
3443   // // // Preserve in case we decide to use this table instead of another
3444   //// Construct the boolean table for instruction chain rules
3445   //OutputInstChainRule output_inst_chain(fp_hpp, fp_cpp, _globalNames, *this);
3446   //build_map(output_inst_chain);
3447 
3448 }
3449 
3450 
3451 //---------------------------buildMachOperGenerator---------------------------
3452 
3453 // Recurse through match tree, building path through corresponding state tree,
3454 // Until we reach the constant we are looking for.
3455 static void path_to_constant(FILE *fp, FormDict &globals,
3456                              MatchNode *mnode, uint idx) {
3457   if ( ! mnode) return;
3458   
3459   unsigned    position = 0;
3460   const char *result   = NULL;
3461   const char *name     = NULL;
3462   const char *optype   = NULL;
3463 
3464   // Base Case: access constant in ideal node linked to current state node
3465   // Each type of constant has its own access function
3466   if ( (mnode->_lChild == NULL) && (mnode->_rChild == NULL)
3467        && mnode->base_operand(position, globals, result, name, optype) ) {
3468     if (         strcmp(optype,"ConI") == 0 ) {
3469       fprintf(fp, "_leaf->get_int()");
3470     } else if ( (strcmp(optype,"ConP") == 0) ) {
3471       fprintf(fp, "_leaf->bottom_type()->is_ptr()");
3472     } else if ( (strcmp(optype,"ConN") == 0) ) {
3473       fprintf(fp, "_leaf->bottom_type()->is_narrowoop()");
3474     } else if ( (strcmp(optype,"ConF") == 0) ) {
3475       fprintf(fp, "_leaf->getf()");
3476     } else if ( (strcmp(optype,"ConD") == 0) ) {
3477       fprintf(fp, "_leaf->getd()");
3478     } else if ( (strcmp(optype,"ConL") == 0) ) {
3479       fprintf(fp, "_leaf->get_long()");
3480     } else if ( (strcmp(optype,"Con")==0) ) {
3481       // !!!!! - Update if adding a machine-independent constant type
3482       fprintf(fp, "_leaf->get_int()");
3483       assert( false, "Unsupported constant type, pointer or indefinite");
3484     } else if ( (strcmp(optype,"Bool") == 0) ) {
3485       fprintf(fp, "_leaf->as_Bool()->_test._test");
3486     } else {
3487       assert( false, "Unsupported constant type");
3488     }
3489     return;
3490   }
3491 
3492   // If constant is in left child, build path and recurse 
3493   uint lConsts = (mnode->_lChild) ? (mnode->_lChild->num_consts(globals) ) : 0;
3494   uint rConsts = (mnode->_rChild) ? (mnode->_rChild->num_consts(globals) ) : 0;
3495   if ( (mnode->_lChild) && (lConsts > idx) ) {
3496     fprintf(fp, "_kids[0]->");
3497     path_to_constant(fp, globals, mnode->_lChild, idx);
3498     return;
3499   } 
3500   // If constant is in right child, build path and recurse
3501   if ( (mnode->_rChild) && (rConsts > (idx - lConsts) ) ) {
3502     idx = idx - lConsts;
3503     fprintf(fp, "_kids[1]->");
3504     path_to_constant(fp, globals, mnode->_rChild, idx);
3505     return;
3506   }
3507   assert( false, "ShouldNotReachHere()");
3508 }
3509 
3510 // Generate code that is executed when generating a specific Machine Operand
3511 static void genMachOperCase(FILE *fp, FormDict &globalNames, ArchDesc &AD, 
3512                             OperandForm &op) {
3513   const char *opName         = op._ident;
3514   const char *opEnumName     = AD.machOperEnum(opName);
3515   uint        num_consts     = op.num_consts(globalNames);
3516 
3517   // Generate the case statement for this opcode
3518   fprintf(fp, "  case %s:", opEnumName);
3519   fprintf(fp, "\n    return new (C) %sOper(", opName);
3520   // Access parameters for constructor from the stat object
3521   // 
3522   // Build access to condition code value
3523   if ( (num_consts > 0) ) {
3524     uint i = 0;
3525     path_to_constant(fp, globalNames, op._matrule, i);
3526     for ( i = 1; i < num_consts; ++i ) {
3527       fprintf(fp, ", ");
3528       path_to_constant(fp, globalNames, op._matrule, i);
3529     }
3530   }
3531   fprintf(fp, " );\n");
3532 }
3533 
3534 
3535 // Build switch to invoke "new" MachNode or MachOper
3536 void ArchDesc::buildMachOperGenerator(FILE *fp_cpp) {
3537   int idx = 0;
3538 
3539   // Build switch to invoke 'new' for a specific MachOper
3540   fprintf(fp_cpp, "\n");
3541   fprintf(fp_cpp, "\n");
3542   fprintf(fp_cpp, 
3543           "//------------------------- MachOper Generator ---------------\n");
3544   fprintf(fp_cpp, 
3545           "// A switch statement on the dense-packed user-defined type system\n"
3546           "// that invokes 'new' on the corresponding class constructor.\n");
3547   fprintf(fp_cpp, "\n");
3548   fprintf(fp_cpp, "MachOper *State::MachOperGenerator");
3549   fprintf(fp_cpp, "(int opcode, Compile* C)");
3550   fprintf(fp_cpp, "{\n");
3551   fprintf(fp_cpp, "\n");
3552   fprintf(fp_cpp, "  switch(opcode) {\n");
3553 
3554   // Place all user-defined operands into the mapping
3555   _operands.reset();
3556   int  opIndex = 0;
3557   OperandForm *op;
3558   for( ; (op =  (OperandForm*)_operands.iter()) != NULL; ) {
3559     // Ensure this is a machine-world instruction
3560     if ( op->ideal_only() )  continue;
3561     
3562     genMachOperCase(fp_cpp, _globalNames, *this, *op);
3563   };
3564 
3565   // Do not iterate over operand classes for the  operand generator!!!
3566 
3567   // Place all internal operands into the mapping
3568   _internalOpNames.reset();
3569   const char *iopn;
3570   for( ; (iopn =  _internalOpNames.iter()) != NULL; ) {
3571     const char *opEnumName = machOperEnum(iopn);
3572     // Generate the case statement for this opcode
3573     fprintf(fp_cpp, "  case %s:", opEnumName);
3574     fprintf(fp_cpp, "    return NULL;\n");
3575   };
3576 
3577   // Generate the default case for switch(opcode)
3578   fprintf(fp_cpp, "  \n");
3579   fprintf(fp_cpp, "  default:\n");
3580   fprintf(fp_cpp, "    fprintf(stderr, \"Default MachOper Generator invoked for: \\n\");\n");
3581   fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
3582   fprintf(fp_cpp, "    break;\n");
3583   fprintf(fp_cpp, "  }\n");
3584 
3585   // Generate the closing for method Matcher::MachOperGenerator
3586   fprintf(fp_cpp, "  return NULL;\n");
3587   fprintf(fp_cpp, "};\n");
3588 }
3589 
3590 
3591 //---------------------------buildMachNode-------------------------------------
3592 // Build a new MachNode, for MachNodeGenerator or cisc-spilling
3593 void ArchDesc::buildMachNode(FILE *fp_cpp, InstructForm *inst, const char *indent) {
3594   const char *opType  = NULL;
3595   const char *opClass = inst->_ident; 
3596 
3597   // Create the MachNode object
3598   fprintf(fp_cpp, "%s %sNode *node = new (C) %sNode();\n",indent, opClass,opClass);
3599 
3600   if ( (inst->num_post_match_opnds() != 0) ) {
3601     // Instruction that contains operands which are not in match rule.
3602     // 
3603     // Check if the first post-match component may be an interesting def
3604     bool           dont_care = false;
3605     ComponentList &comp_list = inst->_components;
3606     Component     *comp      = NULL;
3607     comp_list.reset();
3608     if ( comp_list.match_iter() != NULL )    dont_care = true;
3609     
3610     // Insert operands that are not in match-rule.
3611     // Only insert a DEF if the do_care flag is set
3612     comp_list.reset();
3613     while ( comp = comp_list.post_match_iter() ) {
3614       // Check if we don't care about DEFs or KILLs that are not USEs
3615       if ( dont_care && (! comp->isa(Component::USE)) ) {
3616         continue;
3617       } 
3618       dont_care = true;
3619       // For each operand not in the match rule, call MachOperGenerator 
3620       // with the enum for the opcode that needs to be built
3621       // and the node just built, the parent of the operand.
3622       ComponentList clist = inst->_components;
3623       int         index  = clist.operand_position(comp->_name, comp->_usedef);
3624       const char *opcode = machOperEnum(comp->_type);
3625       const char *parent = "node";
3626       fprintf(fp_cpp, "%s node->set_opnd_array(%d, ", indent, index);
3627       fprintf(fp_cpp, "MachOperGenerator(%s, C));\n", opcode);
3628       }
3629   } 
3630   else if ( inst->is_chain_of_constant(_globalNames, opType) ) {
3631     // An instruction that chains from a constant!
3632     // In this case, we need to subsume the constant into the node
3633     // at operand position, oper_input_base().
3634     // 
3635     // Fill in the constant
3636     fprintf(fp_cpp, "%s node->_opnd_array[%d] = ", indent, 
3637             inst->oper_input_base(_globalNames));
3638     // #####
3639     // Check for multiple constants and then fill them in.
3640     // Just like MachOperGenerator
3641     const char *opName = inst->_matrule->_rChild->_opType;
3642     fprintf(fp_cpp, "new (C) %sOper(", opName);
3643     // Grab operand form
3644     OperandForm *op = (_globalNames[opName])->is_operand();
3645     // Look up the number of constants
3646     uint num_consts = op->num_consts(_globalNames);
3647     if ( (num_consts > 0) ) {
3648       uint i = 0;
3649       path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
3650       for ( i = 1; i < num_consts; ++i ) {
3651         fprintf(fp_cpp, ", ");
3652         path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
3653       }
3654     }
3655     fprintf(fp_cpp, " );\n");
3656     // #####
3657   }
3658   
3659   // Fill in the bottom_type where requested
3660   if ( inst->captures_bottom_type() ) {
3661     fprintf(fp_cpp, "%s node->_bottom_type = _leaf->bottom_type();\n", indent);
3662   }
3663   if( inst->is_ideal_if() ) {
3664     fprintf(fp_cpp, "%s node->_prob = _leaf->as_If()->_prob;\n", indent);
3665     fprintf(fp_cpp, "%s node->_fcnt = _leaf->as_If()->_fcnt;\n", indent);
3666   }
3667   if( inst->is_ideal_fastlock() ) {
3668     fprintf(fp_cpp, "%s node->_counters = _leaf->as_FastLock()->counters();\n", indent);
3669   }
3670   
3671 }
3672 
3673 //---------------------------declare_cisc_version------------------------------
3674 // Build CISC version of this instruction
3675 void InstructForm::declare_cisc_version(ArchDesc &AD, FILE *fp_hpp) {
3676   if( AD.can_cisc_spill() ) {
3677     InstructForm *inst_cisc = cisc_spill_alternate();
3678     if (inst_cisc != NULL) {
3679       fprintf(fp_hpp, "  virtual int            cisc_operand() const { return %d; }\n", cisc_spill_operand());
3680       fprintf(fp_hpp, "  virtual MachNode      *cisc_version(int offset, Compile* C);\n");
3681       fprintf(fp_hpp, "  virtual void           use_cisc_RegMask();\n");
3682       fprintf(fp_hpp, "  virtual const RegMask *cisc_RegMask() const { return _cisc_RegMask; }\n");
3683     }
3684   }
3685 }
3686 
3687 //---------------------------define_cisc_version-------------------------------
3688 // Build CISC version of this instruction
3689 bool InstructForm::define_cisc_version(ArchDesc &AD, FILE *fp_cpp) {
3690   InstructForm *inst_cisc = this->cisc_spill_alternate();
3691   if( AD.can_cisc_spill() && (inst_cisc != NULL) ) {
3692     const char   *name      = inst_cisc->_ident;
3693     assert( inst_cisc->num_opnds() == this->num_opnds(), "Must have same number of operands");
3694     OperandForm *cisc_oper = AD.cisc_spill_operand();
3695     assert( cisc_oper != NULL, "insanity check");
3696     const char *cisc_oper_name  = cisc_oper->_ident;
3697     assert( cisc_oper_name != NULL, "insanity check");
3698     //
3699     // Set the correct reg_mask_or_stack for the cisc operand
3700     fprintf(fp_cpp, "\n");
3701     fprintf(fp_cpp, "void %sNode::use_cisc_RegMask() {\n", this->_ident);
3702     // Lookup the correct reg_mask_or_stack
3703     const char *reg_mask_name = cisc_reg_mask_name();
3704     fprintf(fp_cpp, "  _cisc_RegMask = &STACK_OR_%s;\n", reg_mask_name);
3705     fprintf(fp_cpp, "}\n");
3706     //
3707     // Construct CISC version of this instruction
3708     fprintf(fp_cpp, "\n");
3709     fprintf(fp_cpp, "// Build CISC version of this instruction\n");
3710     fprintf(fp_cpp, "MachNode *%sNode::cisc_version( int offset, Compile* C ) {\n", this->_ident);
3711     // Create the MachNode object
3712     fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
3713     // Fill in the bottom_type where requested
3714     if ( this->captures_bottom_type() ) {
3715       fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
3716     }
3717     fprintf(fp_cpp, "\n");
3718     fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
3719     fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
3720     // Construct operand to access [stack_pointer + offset]
3721     fprintf(fp_cpp, "  // Construct operand to access [stack_pointer + offset]\n");
3722     fprintf(fp_cpp, "  node->set_opnd_array(cisc_operand(), new (C) %sOper(offset));\n", cisc_oper_name);
3723     fprintf(fp_cpp, "\n");
3724 
3725     // Return result and exit scope
3726     fprintf(fp_cpp, "  return node;\n");
3727     fprintf(fp_cpp, "}\n");
3728     fprintf(fp_cpp, "\n");
3729     return true;
3730   }
3731   return false;
3732 }
3733 
3734 //---------------------------declare_short_branch_methods----------------------
3735 // Build prototypes for short branch methods
3736 void InstructForm::declare_short_branch_methods(FILE *fp_hpp) {
3737   if (has_short_branch_form()) {
3738     fprintf(fp_hpp, "  virtual MachNode      *short_branch_version(Compile* C);\n");
3739   }
3740 }
3741 
3742 //---------------------------define_short_branch_methods-----------------------
3743 // Build definitions for short branch methods
3744 bool InstructForm::define_short_branch_methods(FILE *fp_cpp) {
3745   if (has_short_branch_form()) {
3746     InstructForm *short_branch = short_branch_form();
3747     const char   *name         = short_branch->_ident;
3748 
3749     // Construct short_branch_version() method.
3750     fprintf(fp_cpp, "// Build short branch version of this instruction\n");
3751     fprintf(fp_cpp, "MachNode *%sNode::short_branch_version(Compile* C) {\n", this->_ident);
3752     // Create the MachNode object
3753     fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
3754     if( is_ideal_if() ) {
3755       fprintf(fp_cpp, "  node->_prob = _prob;\n");
3756       fprintf(fp_cpp, "  node->_fcnt = _fcnt;\n");
3757     }
3758     // Fill in the bottom_type where requested
3759     if ( this->captures_bottom_type() ) {
3760       fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
3761     }
3762 
3763     fprintf(fp_cpp, "\n");
3764     // Short branch version must use same node index for access
3765     // through allocator's tables
3766     fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
3767     fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
3768 
3769     // Return result and exit scope
3770     fprintf(fp_cpp, "  return node;\n");
3771     fprintf(fp_cpp, "}\n");
3772     fprintf(fp_cpp,"\n");
3773     return true;
3774   }
3775   return false;
3776 }
3777 
3778 
3779 //---------------------------buildMachNodeGenerator----------------------------
3780 // Build switch to invoke appropriate "new" MachNode for an opcode
3781 void ArchDesc::buildMachNodeGenerator(FILE *fp_cpp) {
3782 
3783   // Build switch to invoke 'new' for a specific MachNode
3784   fprintf(fp_cpp, "\n");
3785   fprintf(fp_cpp, "\n");
3786   fprintf(fp_cpp, 
3787           "//------------------------- MachNode Generator ---------------\n");
3788   fprintf(fp_cpp, 
3789           "// A switch statement on the dense-packed user-defined type system\n"
3790           "// that invokes 'new' on the corresponding class constructor.\n");
3791   fprintf(fp_cpp, "\n");
3792   fprintf(fp_cpp, "MachNode *State::MachNodeGenerator");
3793   fprintf(fp_cpp, "(int opcode, Compile* C)");
3794   fprintf(fp_cpp, "{\n");
3795   fprintf(fp_cpp, "  switch(opcode) {\n");
3796  
3797   // Provide constructor for all user-defined instructions
3798   _instructions.reset(); 
3799   int  opIndex = operandFormCount();
3800   InstructForm *inst;
3801   for( ; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3802     // Ensure that matrule is defined.
3803     if ( inst->_matrule == NULL ) continue;
3804 
3805     int         opcode  = opIndex++;
3806     const char *opClass = inst->_ident; 
3807     char       *opType  = NULL;
3808 
3809     // Generate the case statement for this instruction
3810     fprintf(fp_cpp, "  case %s_rule:", opClass);
3811 
3812     // Start local scope 
3813     fprintf(fp_cpp, "  {\n");
3814     // Generate code to construct the new MachNode
3815     buildMachNode(fp_cpp, inst, "     ");
3816     // Return result and exit scope
3817     fprintf(fp_cpp, "      return node;\n");
3818     fprintf(fp_cpp, "    }\n");
3819   }
3820 
3821   // Generate the default case for switch(opcode)
3822   fprintf(fp_cpp, "  \n");
3823   fprintf(fp_cpp, "  default:\n");
3824   fprintf(fp_cpp, "    fprintf(stderr, \"Default MachNode Generator invoked for: \\n\");\n");
3825   fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
3826   fprintf(fp_cpp, "    break;\n");
3827   fprintf(fp_cpp, "  };\n");
3828 
3829   // Generate the closing for method Matcher::MachNodeGenerator
3830   fprintf(fp_cpp, "  return NULL;\n");
3831   fprintf(fp_cpp, "}\n");
3832 }
3833 
3834 
3835 //---------------------------buildInstructMatchCheck--------------------------
3836 // Output the method to Matcher which checks whether or not a specific
3837 // instruction has a matching rule for the host architecture.
3838 void ArchDesc::buildInstructMatchCheck(FILE *fp_cpp) const {
3839   fprintf(fp_cpp, "\n\n");
3840   fprintf(fp_cpp, "const bool Matcher::has_match_rule(int opcode) {\n");
3841   fprintf(fp_cpp, "  assert(_last_machine_leaf < opcode && opcode < _last_opcode, \"opcode in range\");\n");
3842   fprintf(fp_cpp, "  return _hasMatchRule[opcode];\n");
3843   fprintf(fp_cpp, "}\n\n");
3844 
3845   fprintf(fp_cpp, "const bool Matcher::_hasMatchRule[_last_opcode] = {\n");
3846   int i;
3847   for (i = 0; i < _last_opcode - 1; i++) {
3848     fprintf(fp_cpp, "    %-5s,  // %s\n",
3849             _has_match_rule[i] ? "true" : "false",
3850             NodeClassNames[i]);
3851   }
3852   fprintf(fp_cpp, "    %-5s   // %s\n",
3853           _has_match_rule[i] ? "true" : "false",
3854           NodeClassNames[i]);
3855   fprintf(fp_cpp, "};\n");
3856 }
3857 
3858 //---------------------------buildFrameMethods---------------------------------
3859 // Output the methods to Matcher which specify frame behavior
3860 void ArchDesc::buildFrameMethods(FILE *fp_cpp) {
3861   fprintf(fp_cpp,"\n\n");
3862   // Stack Direction
3863   fprintf(fp_cpp,"bool Matcher::stack_direction() const { return %s; }\n\n",
3864           _frame->_direction ? "true" : "false");
3865   // Sync Stack Slots
3866   fprintf(fp_cpp,"int Compile::sync_stack_slots() const { return %s; }\n\n",
3867           _frame->_sync_stack_slots);
3868   // Java Stack Alignment
3869   fprintf(fp_cpp,"uint Matcher::stack_alignment_in_bytes() { return %s; }\n\n",
3870           _frame->_alignment);
3871   // Java Return Address Location
3872   fprintf(fp_cpp,"OptoReg::Name Matcher::return_addr() const {");
3873   if (_frame->_return_addr_loc) {
3874     fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3875             _frame->_return_addr);
3876   }
3877   else {
3878     fprintf(fp_cpp," return OptoReg::stack2reg(%s); }\n\n",
3879             _frame->_return_addr);
3880   }
3881   // Java Stack Slot Preservation
3882   fprintf(fp_cpp,"uint Compile::in_preserve_stack_slots() ");
3883   fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_in_preserve_slots);
3884   // Top Of Stack Slot Preservation, for both Java and C
3885   fprintf(fp_cpp,"uint Compile::out_preserve_stack_slots() ");
3886   fprintf(fp_cpp,"{ return SharedRuntime::out_preserve_stack_slots(); }\n\n");
3887   // varargs C out slots killed
3888   fprintf(fp_cpp,"uint Compile::varargs_C_out_slots_killed() const ");
3889   fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_varargs_C_out_slots_killed);
3890   // Java Argument Position
3891   fprintf(fp_cpp,"void Matcher::calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length, bool is_outgoing) {\n");
3892   fprintf(fp_cpp,"%s\n", _frame->_calling_convention);
3893   fprintf(fp_cpp,"}\n\n");
3894   // Native Argument Position
3895   fprintf(fp_cpp,"void Matcher::c_calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length) {\n");
3896   fprintf(fp_cpp,"%s\n", _frame->_c_calling_convention);
3897   fprintf(fp_cpp,"}\n\n");
3898   // Java Return Value Location
3899   fprintf(fp_cpp,"OptoRegPair Matcher::return_value(int ideal_reg, bool is_outgoing) {\n");
3900   fprintf(fp_cpp,"%s\n", _frame->_return_value);
3901   fprintf(fp_cpp,"}\n\n");
3902   // Native Return Value Location
3903   fprintf(fp_cpp,"OptoRegPair Matcher::c_return_value(int ideal_reg, bool is_outgoing) {\n");
3904   fprintf(fp_cpp,"%s\n", _frame->_c_return_value);
3905   fprintf(fp_cpp,"}\n\n");
3906 
3907   // Inline Cache Register, mask definition, and encoding
3908   fprintf(fp_cpp,"OptoReg::Name Matcher::inline_cache_reg() {");
3909   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3910           _frame->_inline_cache_reg);
3911   fprintf(fp_cpp,"const RegMask &Matcher::inline_cache_reg_mask() {");
3912   fprintf(fp_cpp," return INLINE_CACHE_REG_mask; }\n\n");
3913   fprintf(fp_cpp,"int Matcher::inline_cache_reg_encode() {");
3914   fprintf(fp_cpp," return _regEncode[inline_cache_reg()]; }\n\n");
3915 
3916   // Interpreter's Method Oop Register, mask definition, and encoding
3917   fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_method_oop_reg() {");
3918   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3919           _frame->_interpreter_method_oop_reg);
3920   fprintf(fp_cpp,"const RegMask &Matcher::interpreter_method_oop_reg_mask() {");
3921   fprintf(fp_cpp," return INTERPRETER_METHOD_OOP_REG_mask; }\n\n");
3922   fprintf(fp_cpp,"int Matcher::interpreter_method_oop_reg_encode() {");
3923   fprintf(fp_cpp," return _regEncode[interpreter_method_oop_reg()]; }\n\n");
3924 
3925   // Interpreter's Frame Pointer Register, mask definition, and encoding
3926   fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_frame_pointer_reg() {");
3927   if (_frame->_interpreter_frame_pointer_reg == NULL)
3928     fprintf(fp_cpp," return OptoReg::Bad; }\n\n");
3929   else
3930     fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3931             _frame->_interpreter_frame_pointer_reg);
3932   fprintf(fp_cpp,"const RegMask &Matcher::interpreter_frame_pointer_reg_mask() {");
3933   if (_frame->_interpreter_frame_pointer_reg == NULL)
3934     fprintf(fp_cpp," static RegMask dummy; return dummy; }\n\n");
3935   else
3936     fprintf(fp_cpp," return INTERPRETER_FRAME_POINTER_REG_mask; }\n\n");
3937 
3938   // Frame Pointer definition
3939   /* CNC - I can not contemplate having a different frame pointer between
3940      Java and native code; makes my head hurt to think about it.
3941   fprintf(fp_cpp,"OptoReg::Name Matcher::frame_pointer() const {");
3942   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3943           _frame->_frame_pointer);
3944   */
3945   // (Native) Frame Pointer definition
3946   fprintf(fp_cpp,"OptoReg::Name Matcher::c_frame_pointer() const {");
3947   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3948           _frame->_frame_pointer);
3949 
3950   // Number of callee-save + always-save registers for calling convention
3951   fprintf(fp_cpp, "// Number of callee-save + always-save registers\n");
3952   fprintf(fp_cpp, "int  Matcher::number_of_saved_registers() {\n");
3953   RegDef *rdef;
3954   int nof_saved_registers = 0;
3955   _register->reset_RegDefs();
3956   while( (rdef = _register->iter_RegDefs()) != NULL ) {
3957     if( !strcmp(rdef->_callconv, "SOE") ||  !strcmp(rdef->_callconv, "AS") )
3958       ++nof_saved_registers;
3959   }
3960   fprintf(fp_cpp, "  return %d;\n", nof_saved_registers);
3961   fprintf(fp_cpp, "};\n\n");
3962 }
3963 
3964 
3965 
3966 
3967 static int PrintAdlcCisc = 0;
3968 //---------------------------identify_cisc_spilling----------------------------
3969 // Get info for the CISC_oracle and MachNode::cisc_version()
3970 void ArchDesc::identify_cisc_spill_instructions() {
3971 
3972   // Find the user-defined operand for cisc-spilling
3973   if( _frame->_cisc_spilling_operand_name != NULL ) {
3974     const Form *form = _globalNames[_frame->_cisc_spilling_operand_name];
3975     OperandForm *oper = form ? form->is_operand() : NULL;
3976     // Verify the user's suggestion 
3977     if( oper != NULL ) {
3978       // Ensure that match field is defined.
3979       if ( oper->_matrule != NULL )  {
3980         MatchRule &mrule = *oper->_matrule;
3981         if( strcmp(mrule._opType,"AddP") == 0 ) {
3982           MatchNode *left = mrule._lChild;
3983           MatchNode *right= mrule._rChild;
3984           if( left != NULL && right != NULL ) {
3985             const Form *left_op  = _globalNames[left->_opType]->is_operand();
3986             const Form *right_op = _globalNames[right->_opType]->is_operand();
3987             if(  (left_op != NULL && right_op != NULL)
3988               && (left_op->interface_type(_globalNames) == Form::register_interface)
3989               && (right_op->interface_type(_globalNames) == Form::constant_interface) ) {
3990               // Successfully verified operand
3991               set_cisc_spill_operand( oper );
3992               if( _cisc_spill_debug ) {
3993                 fprintf(stderr, "\n\nVerified CISC-spill operand %s\n\n", oper->_ident);
3994              }
3995             }
3996           }
3997         }
3998       }
3999     }
4000   }
4001 
4002   if( cisc_spill_operand() != NULL ) {
4003     // N^2 comparison of instructions looking for a cisc-spilling version
4004     _instructions.reset(); 
4005     InstructForm *instr;
4006     for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
4007       // Ensure that match field is defined.
4008       if ( instr->_matrule == NULL )  continue;
4009 
4010       MatchRule &mrule = *instr->_matrule;
4011       Predicate *pred  =  instr->build_predicate();
4012 
4013       // Grab the machine type of the operand
4014       const char *rootOp = instr->_ident;
4015       mrule._machType    = rootOp;
4016 
4017       // Find result type for match
4018       const char *result = instr->reduce_result();
4019 
4020       if( PrintAdlcCisc ) fprintf(stderr, "  new instruction %s \n", instr->_ident ? instr->_ident : " ");
4021       bool  found_cisc_alternate = false;
4022       _instructions.reset2();
4023       InstructForm *instr2;
4024       for( ; !found_cisc_alternate && (instr2 = (InstructForm*)_instructions.iter2()) != NULL; ) {
4025         // Ensure that match field is defined.
4026         if( PrintAdlcCisc ) fprintf(stderr, "  instr2 == %s \n", instr2->_ident ? instr2->_ident : " ");
4027         if ( instr2->_matrule != NULL
4028             && (instr != instr2 )                // Skip self
4029             && (instr2->reduce_result() != NULL) // want same result
4030             && (strcmp(result, instr2->reduce_result()) == 0)) {
4031           MatchRule &mrule2 = *instr2->_matrule;
4032           Predicate *pred2  =  instr2->build_predicate();
4033           found_cisc_alternate = instr->cisc_spills_to(*this, instr2);
4034         }
4035       }
4036     }
4037   }
4038 }
4039 
4040 //---------------------------build_cisc_spilling-------------------------------
4041 // Get info for the CISC_oracle and MachNode::cisc_version()
4042 void ArchDesc::build_cisc_spill_instructions(FILE *fp_hpp, FILE *fp_cpp) {
4043   // Output the table for cisc spilling
4044   fprintf(fp_cpp, "//  The following instructions can cisc-spill\n");
4045   _instructions.reset(); 
4046   InstructForm *inst = NULL;
4047   for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
4048     // Ensure this is a machine-world instruction
4049     if ( inst->ideal_only() )  continue;
4050     const char *inst_name = inst->_ident;
4051     int   operand   = inst->cisc_spill_operand();
4052     if( operand != AdlcVMDeps::Not_cisc_spillable ) {
4053       InstructForm *inst2 = inst->cisc_spill_alternate();
4054       fprintf(fp_cpp, "//  %s can cisc-spill operand %d to %s\n", inst->_ident, operand, inst2->_ident);
4055     }
4056   }
4057   fprintf(fp_cpp, "\n\n");
4058 }
4059 
4060 //---------------------------identify_short_branches----------------------------
4061 // Get info for our short branch replacement oracle.
4062 void ArchDesc::identify_short_branches() {
4063   // Walk over all instructions, checking to see if they match a short
4064   // branching alternate.
4065   _instructions.reset(); 
4066   InstructForm *instr;
4067   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
4068     // The instruction must have a match rule.
4069     if (instr->_matrule != NULL &&
4070         instr->is_short_branch()) {
4071 
4072       _instructions.reset2();
4073       InstructForm *instr2;
4074       while( (instr2 = (InstructForm*)_instructions.iter2()) != NULL ) {
4075         instr2->check_branch_variant(*this, instr);
4076       }
4077     }
4078   }
4079 }
4080 
4081 
4082 //---------------------------identify_unique_operands---------------------------
4083 // Identify unique operands.
4084 void ArchDesc::identify_unique_operands() {
4085   // Walk over all instructions.
4086   _instructions.reset(); 
4087   InstructForm *instr;
4088   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
4089     // Ensure this is a machine-world instruction
4090     if (!instr->ideal_only()) {
4091       instr->set_unique_opnds();
4092     }
4093   }
4094 }