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-2007 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     for( i = 0; i < node->num_opnds(); i++ ) {
1553       fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
1554               i+1,i,i);
1555     }
1556 
1557     // Declare variable to hold root of expansion
1558     fprintf(fp,"  MachNode *result = NULL;\n");
1559 
1560     // Iterate over the instructions 'node' expands into
1561     ExpandRule  *expand       = node->_exprule;
1562     NameAndList *expand_instr = NULL;
1563     for(expand->reset_instructions();
1564         (expand_instr = expand->iter_instructions()) != NULL; cnt++) {
1565       new_id = expand_instr->name();
1566 
1567       InstructForm* expand_instruction = (InstructForm*)globalAD->globalNames()[new_id];
1568       if (expand_instruction->has_temps()) {
1569         globalAD->syntax_err(node->_linenum, "In %s: expand rules using instructs with TEMPs aren't supported: %s",
1570                              node->_ident, new_id);
1571       }
1572 
1573       // Build the node for the instruction
1574       fprintf(fp,"\n  %sNode *n%d = new (C) %sNode();\n", new_id, cnt, new_id);
1575       // Add control edge for this node
1576       fprintf(fp,"  n%d->add_req(_in[0]);\n", cnt);
1577       // Build the operand for the value this node defines.
1578       Form *form = (Form*)_globalNames[new_id];
1579       assert( form, "'new_id' must be a defined form name");
1580       // Grab the InstructForm for the new instruction
1581       new_inst = form->is_instruction();
1582       assert( new_inst, "'new_id' must be an instruction name");
1583       if( node->is_ideal_if() && new_inst->is_ideal_if() ) {
1584         fprintf(fp, "  ((MachIfNode*)n%d)->_prob = _prob;\n",cnt);
1585         fprintf(fp, "  ((MachIfNode*)n%d)->_fcnt = _fcnt;\n",cnt);
1586       }
1587 
1588       if( node->is_ideal_fastlock() && new_inst->is_ideal_fastlock() ) {
1589         fprintf(fp, "  ((MachFastLockNode*)n%d)->_counters = _counters;\n",cnt);
1590       }
1591 
1592       const char *resultOper = new_inst->reduce_result();
1593       fprintf(fp,"  n%d->set_opnd_array(0, state->MachOperGenerator( %s, C ));\n", 
1594               cnt, machOperEnum(resultOper));
1595 
1596       // get the formal operand NameList
1597       NameList *formal_lst = &new_inst->_parameters;
1598       formal_lst->reset();
1599 
1600       // Handle any memory operand
1601       int memory_operand = new_inst->memory_operand(_globalNames);
1602       if( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
1603         int node_mem_op = node->memory_operand(_globalNames);
1604         assert( node_mem_op != InstructForm::NO_MEMORY_OPERAND, 
1605                 "expand rule member needs memory but top-level inst doesn't have any" );
1606         // Copy memory edge
1607         fprintf(fp,"  n%d->add_req(_in[1]);\t// Add memory edge\n", cnt);
1608       }
1609 
1610       // Iterate over the new instruction's operands
1611       for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
1612         // Use 'parameter' at current position in list of new instruction's formals
1613         // instead of 'opid' when looking up info internal to new_inst
1614         const char *parameter = formal_lst->iter();
1615         // Check for an operand which is created in the expand rule
1616         if ((exp_pos = node->_exprule->_newopers.index(opid)) != -1) {
1617           new_pos = new_inst->operand_position(parameter,Component::USE);
1618           exp_pos += node->num_opnds();
1619           // If there is no use of the created operand, just skip it
1620           if (new_pos != -1) {
1621             //Copy the operand from the original made above
1622             fprintf(fp,"  n%d->set_opnd_array(%d, op%d->clone(C)); // %s\n", 
1623                     cnt, new_pos, exp_pos-node->num_opnds(), opid);
1624             // Check for who defines this operand & add edge if needed
1625             fprintf(fp,"  if(tmp%d != NULL)\n", exp_pos);
1626             fprintf(fp,"    n%d->add_req(tmp%d);\n", cnt, exp_pos);
1627           }
1628         }
1629         else {
1630           // Use operand name to get an index into instruction component list
1631           // ins = (InstructForm *) _globalNames[new_id];
1632           exp_pos = node->operand_position_format(opid);
1633           assert(exp_pos != -1, "Bad expand rule");
1634           
1635           new_pos = new_inst->operand_position(parameter,Component::USE);
1636           if (new_pos != -1) {
1637             // Copy the operand from the ExpandNode to the new node
1638             fprintf(fp,"  n%d->set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n", 
1639                     cnt, new_pos, exp_pos, opid);
1640             // For each operand add appropriate input edges by looking at tmp's
1641             fprintf(fp,"  if(tmp%d == this) {\n", exp_pos);
1642             // Grab corresponding edges from ExpandNode and insert them here
1643             fprintf(fp,"    for(unsigned i = 0; i < num%d; i++) {\n", exp_pos);
1644             fprintf(fp,"      n%d->add_req(_in[i + idx%d]);\n", cnt, exp_pos);
1645             fprintf(fp,"    }\n");
1646             fprintf(fp,"  }\n");
1647             // This value is generated by one of the new instructions
1648             fprintf(fp,"  else n%d->add_req(tmp%d);\n", cnt, exp_pos);
1649           }
1650         }
1651 
1652         // Update the DAG tmp's for values defined by this instruction
1653         int new_def_pos = new_inst->operand_position(parameter,Component::DEF);
1654         Effect *eform = (Effect *)new_inst->_effects[parameter];
1655         // If this operand is a definition in either an effects rule
1656         // or a match rule
1657         if((eform) && (is_def(eform->_use_def))) {
1658           // Update the temp associated with this operand
1659           fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
1660         }
1661         else if( new_def_pos != -1 ) {
1662           // Instruction defines a value but user did not declare it 
1663           // in the 'effect' clause
1664           fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
1665         }
1666       } // done iterating over a new instruction's operands
1667       
1668       // Invoke Expand() for the newly created instruction.
1669       fprintf(fp,"  result = n%d->Expand( state, proj_list );\n", cnt);
1670       assert( !new_inst->expands(), "Do not have complete support for recursive expansion");
1671     } // done iterating over new instructions
1672     fprintf(fp,"\n");
1673   } // done generating expand rule
1674 
1675   else if( node->_matrule != NULL ) {
1676     // Remove duplicated operands and inputs which use the same name.
1677     // Seach through match operands for the same name usage.
1678     uint cur_num_opnds = node->num_opnds();
1679     if( cur_num_opnds > 1 && cur_num_opnds != node->num_unique_opnds() ) {
1680       Component *comp = NULL;
1681       // Build mapping from num_edges to local variables
1682       fprintf(fp,"  unsigned num0 = 0;\n");
1683       for( i = 1; i < cur_num_opnds; i++ ) {
1684         fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();\n",i,i);
1685       }
1686       // Build a mapping from operand index to input edges
1687       fprintf(fp,"  unsigned idx0 = oper_input_base();\n");
1688       for( i = 0; i < cur_num_opnds; i++ ) {
1689         fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
1690                 i+1,i,i);
1691       }
1692 
1693       uint new_num_opnds = 1;
1694       node->_components.reset();
1695       // Skip first unique operands.
1696       for( i = 1; i < cur_num_opnds; i++ ) {
1697         comp = node->_components.iter();
1698         if( (int)i != node->unique_opnds_idx(i) ) {
1699           break;
1700         }
1701         new_num_opnds++;
1702       }
1703       // Replace not unique operands with next unique operands.
1704       for( ; i < cur_num_opnds; i++ ) {
1705         comp = node->_components.iter();
1706         int j = node->unique_opnds_idx(i);
1707         // unique_opnds_idx(i) is unique if unique_opnds_idx(j) is not unique.
1708         if( j != node->unique_opnds_idx(j) ) {
1709           fprintf(fp,"  set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n", 
1710                   new_num_opnds, i, comp->_name);
1711           // delete not unique edges here
1712           fprintf(fp,"  for(unsigned i = 0; i < num%d; i++) {\n", i);
1713           fprintf(fp,"    set_req(i + idx%d, _in[i + idx%d]);\n", new_num_opnds, i);
1714           fprintf(fp,"  }\n");
1715           fprintf(fp,"  num%d = num%d;\n", new_num_opnds, i);
1716           fprintf(fp,"  idx%d = idx%d + num%d;\n", new_num_opnds+1, new_num_opnds, new_num_opnds);
1717           new_num_opnds++;
1718         }
1719       }
1720       // delete the rest of edges
1721       fprintf(fp,"  for(int i = idx%d - 1; i >= (int)idx%d; i--) {\n", cur_num_opnds, new_num_opnds);
1722       fprintf(fp,"    del_req(i);\n", i);
1723       fprintf(fp,"  }\n");
1724       fprintf(fp,"  _num_opnds = %d;\n", new_num_opnds);
1725     }
1726   }
1727 
1728 
1729   // Generate projections for instruction's additional DEFs and KILLs 
1730   if( ! node->expands() && (node->needs_projections() || node->has_temps())) {
1731     // Get string representing the MachNode that projections point at
1732     const char *machNode = "this";
1733     // Generate the projections
1734     fprintf(fp,"  // Add projection edges for additional defs or kills\n");
1735 
1736     // Examine each component to see if it is a DEF or KILL
1737     node->_components.reset();
1738     // Skip the first component, if already handled as (SET dst (...))
1739     Component *comp = NULL;
1740     // For kills, the choice of projection numbers is arbitrary
1741     int proj_no = 1;
1742     bool declared_def  = false;
1743     bool declared_kill = false;
1744 
1745     while( (comp = node->_components.iter()) != NULL ) {
1746       // Lookup register class associated with operand type
1747       Form        *form = (Form*)_globalNames[comp->_type];
1748       assert( form, "component type must be a defined form");
1749       OperandForm *op   = form->is_operand();
1750 
1751       if (comp->is(Component::TEMP)) {
1752         fprintf(fp, "  // TEMP %s\n", comp->_name);
1753         if (!declared_def) {
1754           // Define the variable "def" to hold new MachProjNodes
1755           fprintf(fp, "  MachTempNode *def;\n");
1756           declared_def = true;
1757         }
1758         if (op && op->_interface && op->_interface->is_RegInterface()) {
1759           fprintf(fp,"  def = new (C) MachTempNode(state->MachOperGenerator( %s, C ));\n", 
1760                   machOperEnum(op->_ident));
1761           fprintf(fp,"  add_req(def);\n");
1762           int idx  = node->operand_position_format(comp->_name);
1763           fprintf(fp,"  set_opnd_array(%d, state->MachOperGenerator( %s, C ));\n", 
1764                   idx, machOperEnum(op->_ident));
1765         } else {
1766           assert(false, "can't have temps which aren't registers");
1767         }
1768       } else if (comp->isa(Component::KILL)) {
1769         fprintf(fp, "  // DEF/KILL %s\n", comp->_name);
1770 
1771         if (!declared_kill) {
1772           // Define the variable "kill" to hold new MachProjNodes
1773           fprintf(fp, "  MachProjNode *kill;\n");
1774           declared_kill = true;
1775         }
1776 
1777         assert( op, "Support additional KILLS for base operands");
1778         const char *regmask    = reg_mask(*op);
1779         const char *ideal_type = op->ideal_type(_globalNames, _register);
1780 
1781         if (!op->is_bound_register()) {
1782           syntax_err(node->_linenum, "In %s only bound registers can be killed: %s %s\n",
1783                      node->_ident, comp->_type, comp->_name);
1784         }
1785 
1786         fprintf(fp,"  kill = ");
1787         fprintf(fp,"new (C, 1) MachProjNode( %s, %d, (%s), Op_%s );\n",
1788                 machNode, proj_no++, regmask, ideal_type);
1789         fprintf(fp,"  proj_list.push(kill);\n");
1790       }
1791     }
1792   }
1793 
1794   fprintf(fp,"\n");
1795   if( node->expands() ) {
1796     fprintf(fp,"  return result;\n",cnt-1);
1797   } else {
1798     fprintf(fp,"  return this;\n");
1799   }
1800   fprintf(fp,"}\n");
1801   fprintf(fp,"\n");
1802 }
1803 
1804 
1805 //------------------------------Emit Routines----------------------------------
1806 // Special classes and routines for defining node emit routines which output
1807 // target specific instruction object encodings.
1808 // Define the ___Node::emit() routine
1809 //
1810 // (1) void  ___Node::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
1811 // (2)   // ...  encoding defined by user
1812 // (3)   
1813 // (4) }
1814 // 
1815 
1816 class DefineEmitState {
1817 private:
1818   enum reloc_format { RELOC_NONE        = -1, 
1819                       RELOC_IMMEDIATE   =  0, 
1820                       RELOC_DISP        =  1, 
1821                       RELOC_CALL_DISP   =  2 };
1822   enum literal_status{ LITERAL_NOT_SEEN  = 0,
1823                        LITERAL_SEEN      = 1,
1824                        LITERAL_ACCESSED  = 2,
1825                        LITERAL_OUTPUT    = 3 };
1826   // Temporaries that describe current operand
1827   bool          _cleared;
1828   OpClassForm  *_opclass;
1829   OperandForm  *_operand;
1830   int           _operand_idx;
1831   const char   *_local_name;
1832   const char   *_operand_name;
1833   bool          _doing_disp;
1834   bool          _doing_constant;
1835   Form::DataType _constant_type;
1836   DefineEmitState::literal_status _constant_status;
1837   DefineEmitState::literal_status _reg_status;
1838   bool          _doing_emit8;
1839   bool          _doing_emit_d32;
1840   bool          _doing_emit_d16;
1841   bool          _doing_emit_hi;
1842   bool          _doing_emit_lo;
1843   bool          _may_reloc;
1844   bool          _must_reloc;
1845   reloc_format  _reloc_form;
1846   const char *  _reloc_type;                              
1847   bool          _processing_noninput;
1848                
1849   NameList      _strings_to_emit;
1850 
1851   // Stable state, set by constructor
1852   ArchDesc     &_AD;
1853   FILE         *_fp;
1854   EncClass     &_encoding;
1855   InsEncode    &_ins_encode;
1856   InstructForm &_inst;
1857   
1858 public:
1859   DefineEmitState(FILE *fp, ArchDesc &AD, EncClass &encoding, 
1860                   InsEncode &ins_encode, InstructForm &inst) 
1861     : _AD(AD), _fp(fp), _encoding(encoding), _ins_encode(ins_encode), _inst(inst) {
1862       clear();
1863   }
1864 
1865   void clear() {
1866     _cleared       = true;
1867     _opclass       = NULL;
1868     _operand       = NULL;
1869     _operand_idx   = 0;
1870     _local_name    = "";
1871     _operand_name  = "";
1872     _doing_disp    = false;
1873     _doing_constant= false;
1874     _constant_type = Form::none;
1875     _constant_status = LITERAL_NOT_SEEN;
1876     _reg_status      = LITERAL_NOT_SEEN;
1877     _doing_emit8   = false;
1878     _doing_emit_d32= false;
1879     _doing_emit_d16= false;
1880     _doing_emit_hi = false;
1881     _doing_emit_lo = false;
1882     _may_reloc     = false;
1883     _must_reloc    = false;
1884     _reloc_form    = RELOC_NONE;
1885     _reloc_type    = AdlcVMDeps::none_reloc_type();
1886     _strings_to_emit.clear();
1887   }
1888 
1889   // Track necessary state when identifying a replacement variable
1890   void update_state(const char *rep_var) {
1891     // A replacement variable or one of its subfields
1892     // Obtain replacement variable from list
1893     if ( (*rep_var) != '$' ) {
1894       // A replacement variable, '$' prefix
1895       // check_rep_var( rep_var );
1896       if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
1897         // No state needed.
1898         assert( _opclass == NULL, 
1899                 "'primary', 'secondary' and 'tertiary' don't follow operand.");
1900       } else {
1901         // Lookup its position in parameter list
1902         int   param_no  = _encoding.rep_var_index(rep_var);
1903         if ( param_no == -1 ) {
1904           _AD.syntax_err( _encoding._linenum,
1905                           "Replacement variable %s not found in enc_class %s.\n",
1906                           rep_var, _encoding._name);
1907         }
1908 
1909         // Lookup the corresponding ins_encode parameter
1910         const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
1911         if (inst_rep_var == NULL) {
1912           _AD.syntax_err( _ins_encode._linenum,
1913                           "Parameter %s not passed to enc_class %s from instruct %s.\n",
1914                           rep_var, _encoding._name, _inst._ident);
1915         }
1916 
1917         // Check if instruction's actual parameter is a local name in the instruction
1918         const Form  *local     = _inst._localNames[inst_rep_var];
1919         OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
1920         // Note: assert removed to allow constant and symbolic parameters
1921         // assert( opc, "replacement variable was not found in local names");
1922         // Lookup the index position iff the replacement variable is a localName
1923         int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
1924 
1925         if ( idx != -1 ) {
1926           // This is a local in the instruction
1927           // Update local state info.
1928           _opclass        = opc;
1929           _operand_idx    = idx;
1930           _local_name     = rep_var;
1931           _operand_name   = inst_rep_var;
1932 
1933           // !!!!!
1934           // Do not support consecutive operands.
1935           assert( _operand == NULL, "Unimplemented()");
1936           _operand = opc->is_operand();
1937         }
1938         else if( ADLParser::is_literal_constant(inst_rep_var) ) {
1939           // Instruction provided a constant expression
1940           // Check later that encoding specifies $$$constant to resolve as constant
1941           _constant_status   = LITERAL_SEEN;
1942         }
1943         else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
1944           // Instruction provided an opcode: "primary", "secondary", "tertiary"
1945           // Check later that encoding specifies $$$constant to resolve as constant
1946           _constant_status   = LITERAL_SEEN;
1947         }
1948         else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
1949           // Instruction provided a literal register name for this parameter
1950           // Check that encoding specifies $$$reg to resolve.as register.
1951           _reg_status        = LITERAL_SEEN;
1952         }
1953         else {
1954           // Check for unimplemented functionality before hard failure
1955           assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
1956           assert( false, "ShouldNotReachHere()");
1957         }
1958       } // done checking which operand this is.
1959     } else {
1960       // 
1961       // A subfield variable, '$$' prefix
1962       // Check for fields that may require relocation information.
1963       // Then check that literal register parameters are accessed with 'reg' or 'constant'
1964       // 
1965       if ( strcmp(rep_var,"$disp") == 0 ) {
1966         _doing_disp = true;
1967         assert( _opclass, "Must use operand or operand class before '$disp'");
1968         if( _operand == NULL ) {
1969           // Only have an operand class, generate run-time check for relocation
1970           _may_reloc    = true;
1971           _reloc_form   = RELOC_DISP;
1972           _reloc_type   = AdlcVMDeps::oop_reloc_type();
1973         } else {
1974           // Do precise check on operand: is it a ConP or not
1975           // 
1976           // Check interface for value of displacement
1977           assert( ( _operand->_interface != NULL ),
1978                   "$disp can only follow memory interface operand");
1979           MemInterface *mem_interface= _operand->_interface->is_MemInterface();
1980           assert( mem_interface != NULL,
1981                   "$disp can only follow memory interface operand");
1982           const char *disp = mem_interface->_disp;
1983 
1984           if( disp != NULL && (*disp == '$') ) {
1985             // MemInterface::disp contains a replacement variable,
1986             // Check if this matches a ConP
1987             // 
1988             // Lookup replacement variable, in operand's component list
1989             const char *rep_var_name = disp + 1; // Skip '$'
1990             const Component *comp = _operand->_components.search(rep_var_name);
1991             assert( comp != NULL,"Replacement variable not found in components");
1992             const char      *type = comp->_type;
1993             // Lookup operand form for replacement variable's type
1994             const Form *form = _AD.globalNames()[type];
1995             assert( form != NULL, "Replacement variable's type not found");
1996             OperandForm *op = form->is_operand();
1997             assert( op, "Attempting to emit a non-register or non-constant");
1998             // Check if this is a constant
1999             if (op->_matrule && op->_matrule->is_base_constant(_AD.globalNames())) {
2000               // Check which constant this name maps to: _c0, _c1, ..., _cn
2001               // const int idx = _operand.constant_position(_AD.globalNames(), comp);
2002               // assert( idx != -1, "Constant component not found in operand");
2003               Form::DataType dtype = op->is_base_constant(_AD.globalNames());
2004               if ( dtype == Form::idealP ) {
2005                 _may_reloc    = true;
2006                 // No longer true that idealP is always an oop
2007                 _reloc_form   = RELOC_DISP;
2008                 _reloc_type   = AdlcVMDeps::oop_reloc_type();
2009               }
2010             } 
2011 
2012             else if( _operand->is_user_name_for_sReg() != Form::none ) {
2013               // The only non-constant allowed access to disp is an operand sRegX in a stackSlotX
2014               assert( op->ideal_to_sReg_type(type) != Form::none, "StackSlots access displacements using 'sRegs'");
2015               _may_reloc   = false;
2016             } else {
2017               assert( false, "fatal(); Only stackSlots can access a non-constant using 'disp'");
2018             }
2019           }
2020         } // finished with precise check of operand for relocation.
2021       } // finished with subfield variable
2022       else if ( strcmp(rep_var,"$constant") == 0 ) {
2023         _doing_constant = true;
2024         if ( _constant_status == LITERAL_NOT_SEEN ) {
2025           // Check operand for type of constant
2026           assert( _operand, "Must use operand before '$$constant'");
2027           Form::DataType dtype = _operand->is_base_constant(_AD.globalNames());
2028           _constant_type = dtype;
2029           if ( dtype == Form::idealP ) {
2030             _may_reloc    = true;
2031             // No longer true that idealP is always an oop
2032             // // _must_reloc   = true;
2033             _reloc_form   = RELOC_IMMEDIATE;
2034             _reloc_type   = AdlcVMDeps::oop_reloc_type();
2035           } else {
2036             // No relocation information needed
2037           }
2038         } else {
2039           // User-provided literals may not require relocation information !!!!!
2040           assert( _constant_status == LITERAL_SEEN, "Must know we are processing a user-provided literal");
2041         }
2042       }
2043       else if ( strcmp(rep_var,"$label") == 0 ) {
2044         // Calls containing labels require relocation
2045         if ( _inst.is_ideal_call() )  {
2046           _may_reloc    = true;
2047           // !!!!! !!!!!
2048           _reloc_type   = AdlcVMDeps::none_reloc_type();
2049         }
2050       }
2051 
2052       // literal register parameter must be accessed as a 'reg' field.
2053       if ( _reg_status != LITERAL_NOT_SEEN ) {
2054         assert( _reg_status == LITERAL_SEEN, "Must have seen register literal before now");
2055         if (strcmp(rep_var,"$reg") == 0 || reg_conversion(rep_var) != NULL) {
2056           _reg_status  = LITERAL_ACCESSED;
2057         } else {
2058           assert( false, "invalid access to literal register parameter");
2059         }
2060       }
2061       // literal constant parameters must be accessed as a 'constant' field
2062       if ( _constant_status != LITERAL_NOT_SEEN ) {
2063         assert( _constant_status == LITERAL_SEEN, "Must have seen constant literal before now");
2064         if( strcmp(rep_var,"$constant") == 0 ) {
2065           _constant_status  = LITERAL_ACCESSED;
2066         } else {
2067           assert( false, "invalid access to literal constant parameter");
2068         }
2069       }
2070     } // end replacement and/or subfield
2071 
2072   }
2073 
2074   void add_rep_var(const char *rep_var) {
2075     // Handle subfield and replacement variables.
2076     if ( ( *rep_var == '$' ) && ( *(rep_var+1) == '$' ) ) {
2077       // Check for emit prefix, '$$emit32'
2078       assert( _cleared, "Can not nest $$$emit32");
2079       if ( strcmp(rep_var,"$$emit32") == 0 ) {
2080         _doing_emit_d32 = true;
2081       }
2082       else if ( strcmp(rep_var,"$$emit16") == 0 ) {
2083         _doing_emit_d16 = true;
2084       }
2085       else if ( strcmp(rep_var,"$$emit_hi") == 0 ) {
2086         _doing_emit_hi  = true;
2087       }
2088       else if ( strcmp(rep_var,"$$emit_lo") == 0 ) {
2089         _doing_emit_lo  = true;
2090       }
2091       else if ( strcmp(rep_var,"$$emit8") == 0 ) {
2092         _doing_emit8    = true;
2093       }
2094       else {
2095         _AD.syntax_err(_encoding._linenum, "Unsupported $$operation '%s'\n",rep_var);
2096         assert( false, "fatal();");
2097       }
2098     }
2099     else {
2100       // Update state for replacement variables
2101       update_state( rep_var );
2102       _strings_to_emit.addName(rep_var);
2103     }
2104     _cleared  = false;
2105   }
2106 
2107   void emit_replacement() {
2108     // A replacement variable or one of its subfields
2109     // Obtain replacement variable from list
2110     // const char *ec_rep_var = encoding->_rep_vars.iter();
2111     const char *rep_var;
2112     _strings_to_emit.reset();
2113     while ( (rep_var = _strings_to_emit.iter()) != NULL ) {
2114       
2115       if ( (*rep_var) == '$' ) {
2116         // A subfield variable, '$$' prefix
2117         emit_field( rep_var );
2118       } else {
2119         // A replacement variable, '$' prefix
2120         emit_rep_var( rep_var );
2121       } // end replacement and/or subfield
2122     }
2123   }
2124 
2125   void emit_reloc_type(const char* type) {
2126     fprintf(_fp, "%s", type)
2127       ;
2128   }
2129 
2130 
2131   void gen_emit_x_reloc(const char *d32_lo_hi ) {
2132     fprintf(_fp,"emit_%s_reloc(cbuf, ", d32_lo_hi );
2133     emit_replacement();             fprintf(_fp,", ");
2134     emit_reloc_type( _reloc_type ); fprintf(_fp,", ");    
2135     fprintf(_fp, "%d", _reloc_form);fprintf(_fp, ");");
2136   }
2137     
2138   
2139   void emit() {
2140     // 
2141     //   "emit_d32_reloc(" or "emit_hi_reloc" or "emit_lo_reloc"
2142     // 
2143     // Emit the function name when generating an emit function
2144     if ( _doing_emit_d32 || _doing_emit_hi || _doing_emit_lo ) {
2145       const char *d32_hi_lo = _doing_emit_d32 ? "d32" : (_doing_emit_hi ? "hi" : "lo");
2146       // In general, relocatable isn't known at compiler compile time.
2147       // Check results of prior scan
2148       if ( ! _may_reloc ) {
2149         // Definitely don't need relocation information
2150         fprintf( _fp, "emit_%s(cbuf, ", d32_hi_lo );
2151         emit_replacement(); fprintf(_fp, ")"); 
2152       } 
2153       else if ( _must_reloc ) {
2154         // Must emit relocation information
2155         gen_emit_x_reloc( d32_hi_lo );
2156       }
2157       else {
2158         // Emit RUNTIME CHECK to see if value needs relocation info
2159         // If emitting a relocatable address, use 'emit_d32_reloc'
2160         const char *disp_constant = _doing_disp ? "disp" : _doing_constant ? "constant" : "INVALID";
2161         assert( (_doing_disp || _doing_constant)
2162                 && !(_doing_disp && _doing_constant),
2163                 "Must be emitting either a displacement or a constant");
2164         fprintf(_fp,"\n");
2165         fprintf(_fp,"if ( opnd_array(%d)->%s_is_oop() ) {\n", 
2166                 _operand_idx, disp_constant);
2167         fprintf(_fp,"  ");  
2168         gen_emit_x_reloc( d32_hi_lo ); fprintf(_fp,"\n");
2169         fprintf(_fp,"} else {\n");
2170         fprintf(_fp,"  emit_%s(cbuf, ", d32_hi_lo);
2171         emit_replacement(); fprintf(_fp, ");\n"); fprintf(_fp,"}");
2172       }
2173     }
2174     else if ( _doing_emit_d16 ) {
2175       // Relocation of 16-bit values is not supported
2176       fprintf(_fp,"emit_d16(cbuf, "); 
2177       emit_replacement(); fprintf(_fp, ")");
2178       // No relocation done for 16-bit values
2179     }
2180     else if ( _doing_emit8 ) {
2181       // Relocation of 8-bit values is not supported
2182       fprintf(_fp,"emit_d8(cbuf, "); 
2183       emit_replacement(); fprintf(_fp, ")");
2184       // No relocation done for 8-bit values
2185     }
2186     else {
2187       // Not an emit# command, just output the replacement string.
2188       emit_replacement();
2189     }
2190 
2191     // Get ready for next state collection.
2192     clear();
2193   }
2194 
2195 private:
2196 
2197   // recognizes names which represent MacroAssembler register types
2198   // and return the conversion function to build them from OptoReg
2199   const char* reg_conversion(const char* rep_var) {
2200     if (strcmp(rep_var,"$Register") == 0)      return "as_Register";
2201     if (strcmp(rep_var,"$FloatRegister") == 0) return "as_FloatRegister";
2202 #if defined(IA32) || defined(AMD64)
2203     if (strcmp(rep_var,"$XMMRegister") == 0)   return "as_XMMRegister";
2204 #endif
2205     return NULL;
2206   }
2207   
2208   void emit_field(const char *rep_var) {
2209     const char* reg_convert = reg_conversion(rep_var);
2210 
2211     // A subfield variable, '$$subfield'
2212     if ( strcmp(rep_var, "$reg") == 0 || reg_convert != NULL) {
2213       // $reg form or the $Register MacroAssembler type conversions
2214       assert( _operand_idx != -1, 
2215               "Must use this subfield after operand");
2216       if( _reg_status == LITERAL_NOT_SEEN ) {
2217         if (_processing_noninput) {
2218           const Form  *local     = _inst._localNames[_operand_name];
2219           OperandForm *oper      = local->is_operand();
2220           const RegDef* first = oper->get_RegClass()->find_first_elem();
2221           if (reg_convert != NULL) {
2222             fprintf(_fp, "%s(%s_enc)", reg_convert, first->_regname);
2223           } else {
2224             fprintf(_fp, "%s_enc", first->_regname);
2225           }
2226         } else {
2227           fprintf(_fp,"->%s(ra_,this", reg_convert != NULL ? reg_convert : "reg");
2228           // Add parameter for index position, if not result operand
2229           if( _operand_idx != 0 ) fprintf(_fp,",idx%d", _operand_idx);
2230           fprintf(_fp,")");
2231         }
2232       } else {
2233         assert( _reg_status == LITERAL_OUTPUT, "should have output register literal in emit_rep_var");
2234         // Register literal has already been sent to output file, nothing more needed
2235       }
2236     }
2237     else if ( strcmp(rep_var,"$base") == 0 ) {
2238       assert( _operand_idx != -1, 
2239               "Must use this subfield after operand");
2240       assert( ! _may_reloc, "UnImplemented()");
2241       fprintf(_fp,"->base(ra_,this,idx%d)", _operand_idx);
2242     }
2243     else if ( strcmp(rep_var,"$index") == 0 ) {
2244       assert( _operand_idx != -1, 
2245               "Must use this subfield after operand");
2246       assert( ! _may_reloc, "UnImplemented()");
2247       fprintf(_fp,"->index(ra_,this,idx%d)", _operand_idx);
2248     }
2249     else if ( strcmp(rep_var,"$scale") == 0 ) {
2250       assert( ! _may_reloc, "UnImplemented()");
2251       fprintf(_fp,"->scale()");
2252     }
2253     else if ( strcmp(rep_var,"$cmpcode") == 0 ) {
2254       assert( ! _may_reloc, "UnImplemented()");
2255       fprintf(_fp,"->ccode()");
2256     }
2257     else if ( strcmp(rep_var,"$constant") == 0 ) {
2258       if( _constant_status == LITERAL_NOT_SEEN ) {
2259         if ( _constant_type == Form::idealD ) {
2260           fprintf(_fp,"->constantD()");
2261         } else if ( _constant_type == Form::idealF ) {
2262           fprintf(_fp,"->constantF()");
2263         } else if ( _constant_type == Form::idealL ) {
2264           fprintf(_fp,"->constantL()");
2265         } else {
2266           fprintf(_fp,"->constant()");
2267         }
2268       } else {
2269         assert( _constant_status == LITERAL_OUTPUT, "should have output constant literal in emit_rep_var");
2270         // Cosntant literal has already been sent to output file, nothing more needed
2271       }
2272     }
2273     else if ( strcmp(rep_var,"$disp") == 0 ) {
2274       Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
2275       if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
2276         fprintf(_fp,"->disp(ra_,this,0)");
2277       } else {
2278         fprintf(_fp,"->disp(ra_,this,idx%d)", _operand_idx);
2279       }
2280     }
2281     else if ( strcmp(rep_var,"$label") == 0 ) {
2282       fprintf(_fp,"->label()");
2283     }
2284     else if ( strcmp(rep_var,"$method") == 0 ) {
2285       fprintf(_fp,"->method()");
2286     }
2287     else {
2288       printf("emit_field: %s\n",rep_var);
2289       assert( false, "UnImplemented()");
2290     }
2291   }
2292 
2293 
2294   void emit_rep_var(const char *rep_var) {
2295     _processing_noninput = false;
2296     // A replacement variable, originally '$'
2297     if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
2298       _inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(rep_var) );
2299     }
2300     else {
2301       // Lookup its position in parameter list
2302       int   param_no  = _encoding.rep_var_index(rep_var);
2303       if ( param_no == -1 ) {
2304         _AD.syntax_err( _encoding._linenum,
2305                         "Replacement variable %s not found in enc_class %s.\n",
2306                         rep_var, _encoding._name);
2307       }
2308       // Lookup the corresponding ins_encode parameter
2309       const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
2310 
2311       // Check if instruction's actual parameter is a local name in the instruction
2312       const Form  *local     = _inst._localNames[inst_rep_var];
2313       OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
2314       // Note: assert removed to allow constant and symbolic parameters
2315       // assert( opc, "replacement variable was not found in local names");
2316       // Lookup the index position iff the replacement variable is a localName
2317       int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
2318       if( idx != -1 ) {
2319         if (_inst.is_noninput_operand(idx)) {
2320           // This operand isn't a normal input so printing it is done
2321           // specially.
2322           _processing_noninput = true;
2323         } else {
2324           // Output the emit code for this operand
2325           fprintf(_fp,"opnd_array(%d)",idx);
2326         }
2327         assert( _operand == opc->is_operand(),
2328                 "Previous emit $operand does not match current");
2329       }
2330       else if( ADLParser::is_literal_constant(inst_rep_var) ) {
2331         // else check if it is a constant expression
2332         // Removed following assert to allow primitive C types as arguments to encodings
2333         // assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
2334         fprintf(_fp,"(%s)", inst_rep_var);
2335         _constant_status = LITERAL_OUTPUT;
2336       }
2337       else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
2338         // else check if "primary", "secondary", "tertiary"
2339         assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
2340         _inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(inst_rep_var) );
2341         _constant_status = LITERAL_OUTPUT;
2342       }
2343       else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
2344         // Instruction provided a literal register name for this parameter
2345         // Check that encoding specifies $$$reg to resolve.as register.
2346         assert( _reg_status == LITERAL_ACCESSED, "Must be processing a literal register parameter");
2347         fprintf(_fp,"(%s_enc)", inst_rep_var);
2348         _reg_status = LITERAL_OUTPUT;
2349       }
2350       else {
2351         // Check for unimplemented functionality before hard failure
2352         assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
2353         assert( false, "ShouldNotReachHere()");
2354       }
2355       // all done
2356     }
2357   }
2358 
2359 };  // end class DefineEmitState
2360 
2361 
2362 void ArchDesc::defineSize(FILE *fp, InstructForm &inst) {
2363   
2364   //(1)
2365   // Output instruction's emit prototype
2366   fprintf(fp,"uint  %sNode::size(PhaseRegAlloc *ra_) const {\n",
2367           inst._ident);
2368 
2369   //(2)
2370   // Print the size
2371   fprintf(fp, " return (VerifyOops ? MachNode::size(ra_) : %s);\n", inst._size);
2372 
2373   // (3) and (4)
2374   fprintf(fp,"}\n");
2375 }
2376 
2377 void ArchDesc::defineEmit(FILE *fp, InstructForm &inst) {
2378   InsEncode *ins_encode = inst._insencode;
2379 
2380   // (1)
2381   // Output instruction's emit prototype
2382   fprintf(fp,"void  %sNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {\n",
2383           inst._ident);
2384 
2385   // If user did not define an encode section, 
2386   // provide stub that does not generate any machine code.
2387   if( (_encode == NULL) || (ins_encode == NULL) ) {
2388     fprintf(fp, "  // User did not define an encode section.\n");
2389     fprintf(fp,"}\n");
2390     return;
2391   }
2392 
2393   // Save current instruction's starting address (helps with relocation).
2394   fprintf( fp, "    cbuf.set_inst_mark();\n");
2395 
2396   // // // idx0 is only needed for syntactic purposes and only by "storeSSI"
2397   // fprintf( fp, "    unsigned idx0  = 0;\n");
2398 
2399   // Output each operand's offset into the array of registers.
2400   inst.index_temps( fp, _globalNames );
2401   
2402   // Output this instruction's encodings
2403   const char *ec_name;
2404   bool        user_defined = false;
2405   ins_encode->reset();
2406   while ( (ec_name = ins_encode->encode_class_iter()) != NULL ) {
2407     fprintf(fp, "  {");
2408     // Output user-defined encoding
2409     user_defined           = true;
2410 
2411     const char *ec_code    = NULL;
2412     const char *ec_rep_var = NULL;
2413     EncClass   *encoding   = _encode->encClass(ec_name);
2414     if (encoding == NULL) {
2415       fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
2416       abort();
2417     }
2418 
2419     if (ins_encode->current_encoding_num_args() != encoding->num_args()) {
2420       globalAD->syntax_err(ins_encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
2421                            inst._ident, ins_encode->current_encoding_num_args(),
2422                            ec_name, encoding->num_args());
2423     }
2424 
2425     DefineEmitState  pending(fp, *this, *encoding, *ins_encode, inst );
2426     encoding->_code.reset();
2427     encoding->_rep_vars.reset();
2428     // Process list of user-defined strings, 
2429     // and occurrences of replacement variables.
2430     // Replacement Vars are pushed into a list and then output
2431     while ( (ec_code = encoding->_code.iter()) != NULL ) {
2432       if ( ! encoding->_code.is_signal( ec_code ) ) {
2433         // Emit pending code
2434         pending.emit();
2435         pending.clear();
2436         // Emit this code section
2437         fprintf(fp,"%s", ec_code);
2438       } else {
2439         // A replacement variable or one of its subfields
2440         // Obtain replacement variable from list
2441         ec_rep_var  = encoding->_rep_vars.iter();
2442         pending.add_rep_var(ec_rep_var);
2443       }
2444     }
2445     // Emit pending code
2446     pending.emit();
2447     pending.clear();
2448     fprintf(fp, "}\n");
2449   } // end while instruction's encodings
2450 
2451   // Check if user stated which encoding to user
2452   if ( user_defined == false ) {
2453     fprintf(fp, "  // User did not define which encode class to use.\n");
2454   }
2455   
2456   // (3) and (4)
2457   fprintf(fp,"}\n");
2458 }
2459 
2460 // ---------------------------------------------------------------------------
2461 //--------Utilities to build MachOper and MachNode derived Classes------------
2462 // ---------------------------------------------------------------------------
2463 
2464 //------------------------------Utilities to build Operand Classes------------
2465 static void defineIn_RegMask(FILE *fp, FormDict &globals, OperandForm &oper) {
2466   uint num_edges = oper.num_edges(globals);
2467   if( num_edges != 0 ) {
2468     // Method header
2469     fprintf(fp, "const RegMask *%sOper::in_RegMask(int index) const {\n", 
2470             oper._ident);
2471 
2472     // Assert that the index is in range.
2473     fprintf(fp, "  assert(0 <= index && index < %d, \"index out of range\");\n",
2474             num_edges);
2475 
2476     // Figure out if all RegMasks are the same.
2477     const char* first_reg_class = oper.in_reg_class(0, globals);
2478     bool all_same = true;
2479     assert(first_reg_class != NULL, "did not find register mask");
2480 
2481     for (uint index = 1; all_same && index < num_edges; index++) {
2482       const char* some_reg_class = oper.in_reg_class(index, globals);
2483       assert(some_reg_class != NULL, "did not find register mask");
2484       if (strcmp(first_reg_class, some_reg_class) != 0) {
2485         all_same = false;
2486       }
2487     }
2488 
2489     if (all_same) {
2490       // Return the sole RegMask.
2491       if (strcmp(first_reg_class, "stack_slots") == 0) {
2492         fprintf(fp,"  return &(Compile::current()->FIRST_STACK_mask());\n");
2493       } else {
2494         fprintf(fp,"  return &%s_mask;\n", toUpper(first_reg_class));
2495       }
2496     } else {
2497       // Build a switch statement to return the desired mask.
2498       fprintf(fp,"  switch (index) {\n");
2499 
2500       for (uint index = 0; index < num_edges; index++) {
2501         const char *reg_class = oper.in_reg_class(index, globals);
2502         assert(reg_class != NULL, "did not find register mask");
2503         if( !strcmp(reg_class, "stack_slots") ) {
2504           fprintf(fp, "  case %d: return &(Compile::current()->FIRST_STACK_mask());\n", index);
2505         } else {
2506           fprintf(fp, "  case %d: return &%s_mask;\n", index, toUpper(reg_class));
2507         }
2508       }
2509       fprintf(fp,"  }\n");
2510       fprintf(fp,"  ShouldNotReachHere();\n");
2511       fprintf(fp,"  return NULL;\n");
2512     }
2513 
2514     // Method close
2515     fprintf(fp, "}\n\n");
2516   }
2517 }
2518 
2519 // generate code to create a clone for a class derived from MachOper
2520 // 
2521 // (0)  MachOper  *MachOperXOper::clone(Compile* C) const {
2522 // (1)    return new (C) MachXOper( _ccode, _c0, _c1, ..., _cn);
2523 // (2)  }
2524 // 
2525 static void defineClone(FILE *fp, FormDict &globalNames, OperandForm &oper) {
2526   fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper._ident);
2527   // Check for constants that need to be copied over
2528   const int  num_consts    = oper.num_consts(globalNames);
2529   const bool is_ideal_bool = oper.is_ideal_bool();
2530   if( (num_consts > 0) ) {
2531     fprintf(fp,"  return  new (C) %sOper(", oper._ident);
2532     // generate parameters for constants
2533     int i = 0;
2534     fprintf(fp,"_c%d", i);
2535     for( i = 1; i < num_consts; ++i) {
2536       fprintf(fp,", _c%d", i);
2537     }
2538     // finish line (1)
2539     fprintf(fp,");\n");
2540   }
2541   else {
2542     assert( num_consts == 0, "Currently support zero or one constant per operand clone function");
2543     fprintf(fp,"  return  new (C) %sOper();\n", oper._ident);
2544   }
2545   // finish method
2546   fprintf(fp,"}\n");
2547 }
2548 
2549 static void define_hash(FILE *fp, char *operand) {
2550   fprintf(fp,"uint %sOper::hash() const { return 5; }\n", operand);
2551 }
2552 
2553 static void define_cmp(FILE *fp, char *operand) {
2554   fprintf(fp,"uint %sOper::cmp( const MachOper &oper ) const { return opcode() == oper.opcode(); }\n", operand);
2555 }
2556 
2557 
2558 // Helper functions for bug 4796752, abstracted with minimal modification 
2559 // from define_oper_interface()
2560 OperandForm *rep_var_to_operand(const char *encoding, OperandForm &oper, FormDict &globals) {
2561   OperandForm *op = NULL;
2562   // Check for replacement variable
2563   if( *encoding == '$' ) {
2564     // Replacement variable
2565     const char *rep_var = encoding + 1;
2566     // Lookup replacement variable, rep_var, in operand's component list
2567     const Component *comp = oper._components.search(rep_var);
2568     assert( comp != NULL, "Replacement variable not found in components");
2569     // Lookup operand form for replacement variable's type
2570     const char      *type = comp->_type;
2571     Form            *form = (Form*)globals[type];
2572     assert( form != NULL, "Replacement variable's type not found");
2573     op = form->is_operand();
2574     assert( op, "Attempting to emit a non-register or non-constant");
2575   }
2576 
2577   return op;
2578 }
2579 
2580 int rep_var_to_constant_index(const char *encoding, OperandForm &oper, FormDict &globals) {
2581   int idx = -1;
2582   // Check for replacement variable
2583   if( *encoding == '$' ) {
2584     // Replacement variable
2585     const char *rep_var = encoding + 1;
2586     // Lookup replacement variable, rep_var, in operand's component list
2587     const Component *comp = oper._components.search(rep_var);
2588     assert( comp != NULL, "Replacement variable not found in components");
2589     // Lookup operand form for replacement variable's type
2590     const char      *type = comp->_type;
2591     Form            *form = (Form*)globals[type];
2592     assert( form != NULL, "Replacement variable's type not found");
2593     OperandForm *op = form->is_operand();
2594     assert( op, "Attempting to emit a non-register or non-constant");
2595     // Check that this is a constant and find constant's index:
2596     if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2597       idx  = oper.constant_position(globals, comp);
2598     }
2599   }
2600 
2601   return idx;
2602 }
2603 
2604 bool is_regI(const char *encoding, OperandForm &oper, FormDict &globals ) {
2605   bool is_regI = false;
2606 
2607   OperandForm *op = rep_var_to_operand(encoding, oper, globals);
2608   if( op != NULL ) {
2609     // Check that this is a register 
2610     if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
2611       // Register
2612       const char* ideal  = op->ideal_type(globals);
2613       is_regI = (ideal && (op->ideal_to_Reg_type(ideal) == Form::idealI));
2614     }
2615   }
2616 
2617   return is_regI;
2618 }
2619 
2620 bool is_conP(const char *encoding, OperandForm &oper, FormDict &globals ) {
2621   bool is_conP = false;
2622 
2623   OperandForm *op = rep_var_to_operand(encoding, oper, globals);
2624   if( op != NULL ) {
2625     // Check that this is a constant pointer
2626     if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2627       // Constant
2628       Form::DataType dtype = op->is_base_constant(globals);
2629       is_conP = (dtype == Form::idealP);
2630     }
2631   }
2632 
2633   return is_conP;
2634 }
2635 
2636 
2637 // Define a MachOper interface methods
2638 void ArchDesc::define_oper_interface(FILE *fp, OperandForm &oper, FormDict &globals,
2639                                      const char *name, const char *encoding) {
2640   bool emit_position = false;
2641   int position = -1;
2642 
2643   fprintf(fp,"  virtual int            %s", name);
2644   // Generate access method for base, index, scale, disp, ...
2645   if( (strcmp(name,"base") == 0) || (strcmp(name,"index") == 0) ) {
2646     fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
2647     emit_position = true;
2648   } else if ( (strcmp(name,"disp") == 0) ) {
2649     fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
2650   } else {
2651     fprintf(fp,"() const { ");
2652   }
2653 
2654   // Check for hexadecimal value OR replacement variable
2655   if( *encoding == '$' ) {
2656     // Replacement variable
2657     const char *rep_var = encoding + 1;
2658     fprintf(fp,"// Replacement variable: %s\n", encoding+1);
2659     // Lookup replacement variable, rep_var, in operand's component list
2660     const Component *comp = oper._components.search(rep_var);
2661     assert( comp != NULL, "Replacement variable not found in components");
2662     // Lookup operand form for replacement variable's type
2663     const char      *type = comp->_type;
2664     Form            *form = (Form*)globals[type];
2665     assert( form != NULL, "Replacement variable's type not found");
2666     OperandForm *op = form->is_operand();
2667     assert( op, "Attempting to emit a non-register or non-constant");
2668     // Check that this is a register or a constant and generate code:
2669     if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
2670       // Register
2671       int idx_offset = oper.register_position( globals, rep_var);
2672       position = idx_offset;
2673       fprintf(fp,"    return (int)ra_->get_encode(node->in(idx");
2674       if ( idx_offset > 0 ) fprintf(fp,                      "+%d",idx_offset);
2675       fprintf(fp,"));\n");
2676     } else if ( op->ideal_to_sReg_type(op->_ident) != Form::none ) {
2677       // StackSlot for an sReg comes either from input node or from self, when idx==0
2678       fprintf(fp,"    if( idx != 0 ) {\n");
2679       fprintf(fp,"      // Access register number for input operand\n");
2680       fprintf(fp,"      return ra_->reg2offset(ra_->get_reg_first(node->in(idx)));/* sReg */\n");
2681       fprintf(fp,"    }\n");
2682       fprintf(fp,"    // Access register number from myself\n");
2683       fprintf(fp,"    return ra_->reg2offset(ra_->get_reg_first(node));/* sReg */\n");
2684     } else if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2685       // Constant
2686       // Check which constant this name maps to: _c0, _c1, ..., _cn
2687       const int idx = oper.constant_position(globals, comp);
2688       assert( idx != -1, "Constant component not found in operand");
2689       // Output code for this constant, type dependent.
2690       fprintf(fp,"    return (int)" );
2691       oper.access_constant(fp, globals, (uint)idx /* , const_type */);
2692       fprintf(fp,";\n");
2693     } else {
2694       assert( false, "Attempting to emit a non-register or non-constant");
2695     }
2696   } 
2697   else if( *encoding == '0' && *(encoding+1) == 'x' ) {
2698     // Hex value
2699     fprintf(fp,"return %s;", encoding);
2700   } else {
2701     assert( false, "Do not support octal or decimal encode constants");
2702   }
2703   fprintf(fp,"  }\n");
2704 
2705   if( emit_position && (position != -1) && (oper.num_edges(globals) > 0) ) {
2706     fprintf(fp,"  virtual int            %s_position() const { return %d; }\n", name, position);
2707     MemInterface *mem_interface = oper._interface->is_MemInterface();
2708     const char *base = mem_interface->_base;
2709     const char *disp = mem_interface->_disp;
2710     if( emit_position && (strcmp(name,"base") == 0) 
2711         && base != NULL && is_regI(base, oper, globals) 
2712         && disp != NULL && is_conP(disp, oper, globals) ) {
2713       // Found a memory access using a constant pointer for a displacement 
2714       // and a base register containing an integer offset.
2715       // In this case the base and disp are reversed with respect to what 
2716       // is expected by MachNode::get_base_and_disp() and MachNode::adr_type().
2717       // Provide a non-NULL return for disp_as_type() that will allow adr_type()
2718       // to correctly compute the access type for alias analysis.
2719       // 
2720       // See BugId 4796752, operand indOffset32X in i486.ad
2721       int idx = rep_var_to_constant_index(disp, oper, globals);
2722       fprintf(fp,"  virtual const TypePtr *disp_as_type() const { return _c%d; }\n", idx);
2723     }
2724   }
2725 }
2726 
2727 //
2728 // Construct the method to copy _idx, inputs and operands to new node.
2729 static void define_fill_new_machnode(bool used, FILE *fp_cpp) {
2730   fprintf(fp_cpp, "\n");
2731   fprintf(fp_cpp, "// Copy _idx, inputs and operands to new node\n");
2732   fprintf(fp_cpp, "void MachNode::fill_new_machnode( MachNode* node, Compile* C) const {\n");
2733   if( !used ) {
2734     fprintf(fp_cpp, "  // This architecture does not have cisc or short branch instructions\n");
2735     fprintf(fp_cpp, "  ShouldNotCallThis();\n");
2736     fprintf(fp_cpp, "}\n");
2737   } else {
2738     // New node must use same node index for access through allocator's tables
2739     fprintf(fp_cpp, "  // New node must use same node index\n");
2740     fprintf(fp_cpp, "  node->set_idx( _idx );\n");
2741     // Copy machine-independent inputs
2742     fprintf(fp_cpp, "  // Copy machine-independent inputs\n");
2743     fprintf(fp_cpp, "  for( uint j = 0; j < req(); j++ ) {\n");
2744     fprintf(fp_cpp, "    node->add_req(in(j));\n");
2745     fprintf(fp_cpp, "  }\n");
2746     // Copy machine operands to new MachNode
2747     fprintf(fp_cpp, "  // Copy my operands, except for cisc position\n");
2748     fprintf(fp_cpp, "  int nopnds = num_opnds();\n");
2749     fprintf(fp_cpp, "  assert( node->num_opnds() == (uint)nopnds, \"Must have same number of operands\");\n");
2750     fprintf(fp_cpp, "  MachOper **to = node->_opnds;\n");
2751     fprintf(fp_cpp, "  for( int i = 0; i < nopnds; i++ ) {\n");
2752     fprintf(fp_cpp, "    if( i != cisc_operand() ) \n");
2753     fprintf(fp_cpp, "      to[i] = _opnds[i]->clone(C);\n");
2754     fprintf(fp_cpp, "  }\n");
2755     fprintf(fp_cpp, "}\n");
2756   }
2757   fprintf(fp_cpp, "\n");
2758 }
2759 
2760 //------------------------------defineClasses----------------------------------
2761 // Define members of MachNode and MachOper classes based on 
2762 // operand and instruction lists
2763 void ArchDesc::defineClasses(FILE *fp) {
2764 
2765   // Define the contents of an array containing the machine register names
2766   defineRegNames(fp, _register);
2767   // Define an array containing the machine register encoding values
2768   defineRegEncodes(fp, _register);
2769   // Generate an enumeration of user-defined register classes
2770   // and a list of register masks, one for each class.
2771   // Only define the RegMask value objects in the expand file.
2772   // Declare each as an extern const RegMask ...; in ad_<arch>.hpp
2773   declare_register_masks(_HPP_file._fp);
2774   // build_register_masks(fp);
2775   build_register_masks(_CPP_EXPAND_file._fp);
2776   // Define the pipe_classes
2777   build_pipe_classes(_CPP_PIPELINE_file._fp);
2778 
2779   // Generate Machine Classes for each operand defined in AD file
2780   fprintf(fp,"\n");
2781   fprintf(fp,"\n");
2782   fprintf(fp,"//------------------Define classes derived from MachOper---------------------\n");
2783   // Iterate through all operands
2784   _operands.reset(); 
2785   OperandForm *oper;
2786   for( ; (oper = (OperandForm*)_operands.iter()) != NULL; ) {
2787     // Ensure this is a machine-world instruction
2788     if ( oper->ideal_only() ) continue;
2789     // !!!!!
2790     // The declaration of labelOper is in machine-independent file: machnode
2791     if ( strcmp(oper->_ident,"label") == 0 ) {
2792       defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);
2793 
2794       fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
2795       fprintf(fp,"  return  new (C) %sOper(_label, _block_num);\n", oper->_ident);
2796       fprintf(fp,"}\n");
2797 
2798       fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
2799               oper->_ident, machOperEnum(oper->_ident));
2800       // // Currently all XXXOper::Hash() methods are identical (990820)
2801       // define_hash(fp, oper->_ident);
2802       // // Currently all XXXOper::Cmp() methods are identical (990820)
2803       // define_cmp(fp, oper->_ident);
2804       fprintf(fp,"\n");
2805 
2806       continue;
2807     }
2808 
2809     // The declaration of methodOper is in machine-independent file: machnode
2810     if ( strcmp(oper->_ident,"method") == 0 ) {
2811       defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);
2812 
2813       fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
2814       fprintf(fp,"  return  new (C) %sOper(_method);\n", oper->_ident);
2815       fprintf(fp,"}\n");
2816 
2817       fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
2818               oper->_ident, machOperEnum(oper->_ident));
2819       // // Currently all XXXOper::Hash() methods are identical (990820)
2820       // define_hash(fp, oper->_ident);
2821       // // Currently all XXXOper::Cmp() methods are identical (990820)
2822       // define_cmp(fp, oper->_ident);
2823       fprintf(fp,"\n");
2824 
2825       continue;
2826     }
2827 
2828     defineIn_RegMask(fp, _globalNames, *oper);
2829     defineClone(_CPP_CLONE_file._fp, _globalNames, *oper);
2830     // // Currently all XXXOper::Hash() methods are identical (990820)
2831     // define_hash(fp, oper->_ident);
2832     // // Currently all XXXOper::Cmp() methods are identical (990820)
2833     // define_cmp(fp, oper->_ident);
2834 
2835     // side-call to generate output that used to be in the header file:
2836     extern void gen_oper_format(FILE *fp, FormDict &globals, OperandForm &oper, bool for_c_file);
2837     gen_oper_format(_CPP_FORMAT_file._fp, _globalNames, *oper, true);
2838 
2839   }
2840 
2841 
2842   // Generate Machine Classes for each instruction defined in AD file
2843   fprintf(fp,"//------------------Define members for classes derived from MachNode----------\n");
2844   // Output the definitions for out_RegMask() // & kill_RegMask()
2845   _instructions.reset();
2846   InstructForm *instr;
2847   MachNodeForm *machnode;
2848   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2849     // Ensure this is a machine-world instruction
2850     if ( instr->ideal_only() ) continue;
2851 
2852     defineOut_RegMask(_CPP_MISC_file._fp, instr->_ident, reg_mask(*instr));
2853   }
2854 
2855   bool used = false;
2856   // Output the definitions for expand rules & peephole rules
2857   _instructions.reset(); 
2858   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2859     // Ensure this is a machine-world instruction
2860     if ( instr->ideal_only() ) continue;
2861     // If there are multiple defs/kills, or an explicit expand rule, build rule
2862     if( instr->expands() || instr->needs_projections() ||
2863         instr->has_temps() ||
2864         instr->_matrule != NULL && 
2865         instr->num_opnds() != instr->num_unique_opnds() ) 
2866       defineExpand(_CPP_EXPAND_file._fp, instr);
2867     // If there is an explicit peephole rule, build it
2868     if ( instr->peepholes() )
2869       definePeephole(_CPP_PEEPHOLE_file._fp, instr);
2870 
2871     // Output code to convert to the cisc version, if applicable
2872     used |= instr->define_cisc_version(*this, fp);
2873 
2874     // Output code to convert to the short branch version, if applicable
2875     used |= instr->define_short_branch_methods(fp);
2876   }
2877 
2878   // Construct the method called by cisc_version() to copy inputs and operands.
2879   define_fill_new_machnode(used, fp);
2880 
2881   // Output the definitions for labels
2882   _instructions.reset(); 
2883   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
2884     // Ensure this is a machine-world instruction
2885     if ( instr->ideal_only() ) continue;
2886 
2887     // Access the fields for operand Label
2888     int label_position = instr->label_position();
2889     if( label_position != -1 ) {
2890       // Set the label
2891       fprintf(fp,"void %sNode::label_set( Label& label, uint block_num ) {\n", instr->_ident);
2892       fprintf(fp,"  labelOper* oper  = (labelOper*)(opnd_array(%d));\n",
2893               label_position );
2894       fprintf(fp,"  oper->_label     = &label;\n");
2895       fprintf(fp,"  oper->_block_num = block_num;\n");
2896       fprintf(fp,"}\n");
2897     }
2898   }
2899 
2900   // Output the definitions for methods
2901   _instructions.reset(); 
2902   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
2903     // Ensure this is a machine-world instruction
2904     if ( instr->ideal_only() ) continue;
2905 
2906     // Access the fields for operand Label
2907     int method_position = instr->method_position();
2908     if( method_position != -1 ) {
2909       // Access the method's address
2910       fprintf(fp,"void %sNode::method_set( intptr_t method ) {\n", instr->_ident);
2911       fprintf(fp,"  ((methodOper*)opnd_array(%d))->_method = method;\n",
2912               method_position );
2913       fprintf(fp,"}\n");
2914       fprintf(fp,"\n");
2915     }
2916   }
2917 
2918   // Define this instruction's number of relocation entries, base is '0'
2919   _instructions.reset(); 
2920   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
2921     // Output the definition for number of relocation entries
2922     uint reloc_size = instr->reloc(_globalNames);
2923     if ( reloc_size != 0 ) {
2924       fprintf(fp,"int  %sNode::reloc()   const {\n", instr->_ident);
2925       fprintf(fp,  "  return  %d;\n", reloc_size );
2926       fprintf(fp,"}\n");
2927       fprintf(fp,"\n");
2928     }
2929   }
2930   fprintf(fp,"\n");
2931 
2932   // Output the definitions for code generation
2933   // 
2934   // address  ___Node::emit(address ptr, PhaseRegAlloc *ra_) const {
2935   //   // ...  encoding defined by user
2936   //   return ptr;
2937   // }
2938   //
2939   _instructions.reset(); 
2940   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2941     // Ensure this is a machine-world instruction
2942     if ( instr->ideal_only() ) continue;
2943 
2944     if (instr->_insencode) defineEmit(fp, *instr);
2945     if (instr->_size)      defineSize(fp, *instr);
2946 
2947     // side-call to generate output that used to be in the header file:
2948     extern void gen_inst_format(FILE *fp, FormDict &globals, InstructForm &oper, bool for_c_file);
2949     gen_inst_format(_CPP_FORMAT_file._fp, _globalNames, *instr, true);
2950   }
2951 
2952   // Output the definitions for alias analysis
2953   _instructions.reset(); 
2954   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2955     // Ensure this is a machine-world instruction
2956     if ( instr->ideal_only() ) continue;
2957 
2958     // Analyze machine instructions that either USE or DEF memory.
2959     int memory_operand = instr->memory_operand(_globalNames);
2960     // Some guys kill all of memory
2961     if ( instr->is_wide_memory_kill(_globalNames) ) {
2962       memory_operand = InstructForm::MANY_MEMORY_OPERANDS;
2963     }
2964 
2965     if ( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
2966       if( memory_operand == InstructForm::MANY_MEMORY_OPERANDS ) {
2967         fprintf(fp,"const TypePtr *%sNode::adr_type() const { return TypePtr::BOTTOM; }\n", instr->_ident);
2968         fprintf(fp,"const MachOper* %sNode::memory_operand() const { return (MachOper*)-1; }\n", instr->_ident);
2969       } else {
2970         fprintf(fp,"const MachOper* %sNode::memory_operand() const { return _opnds[%d]; }\n", instr->_ident, memory_operand);
2971   }
2972     }
2973   }
2974 
2975   // Get the length of the longest identifier
2976   int max_ident_len = 0;
2977   _instructions.reset();
2978 
2979   for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
2980     if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
2981       int ident_len = (int)strlen(instr->_ident);
2982       if( max_ident_len < ident_len )
2983         max_ident_len = ident_len;
2984     }
2985   }
2986 
2987   // Emit specifically for Node(s)
2988   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
2989     max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
2990   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return %s; }\n",
2991     max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
2992   fprintf(_CPP_PIPELINE_file._fp, "\n");
2993 
2994   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
2995     max_ident_len, "MachNode", _pipeline ? "(&pipeline_class_Unknown_Instructions)" : "NULL");
2996   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return pipeline_class(); }\n",
2997     max_ident_len, "MachNode");
2998   fprintf(_CPP_PIPELINE_file._fp, "\n");
2999 
3000   // Output the definitions for machine node specific pipeline data
3001   _machnodes.reset();
3002 
3003   for ( ; (machnode = (MachNodeForm*)_machnodes.iter()) != NULL; ) {
3004     fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
3005       machnode->_ident, ((class PipeClassForm *)_pipeline->_classdict[machnode->_machnode_pipe])->_num);
3006   }
3007 
3008   fprintf(_CPP_PIPELINE_file._fp, "\n");
3009 
3010   // Output the definitions for instruction pipeline static data references
3011   _instructions.reset();
3012 
3013   for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3014     if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
3015       fprintf(_CPP_PIPELINE_file._fp, "\n");
3016       fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline_class() { return (&pipeline_class_%03d); }\n",
3017         max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
3018       fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
3019         max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
3020     }
3021   }
3022 }
3023 
3024 
3025 // -------------------------------- maps ------------------------------------
3026 
3027 // Information needed to generate the ReduceOp mapping for the DFA
3028 class OutputReduceOp : public OutputMap {
3029 public:
3030   OutputReduceOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3031     : OutputMap(hpp, cpp, globals, AD) {};
3032 
3033   void declaration() { fprintf(_hpp, "extern const int   reduceOp[];\n"); }
3034   void definition()  { fprintf(_cpp, "const        int   reduceOp[] = {\n"); }
3035   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3036                        OutputMap::closing();
3037   }
3038   void map(OpClassForm &opc)  { 
3039     const char *reduce = opc._ident;
3040     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3041     else          fprintf(_cpp, "  0");
3042   }
3043   void map(OperandForm &oper) {
3044     // Most operands without match rules, e.g.  eFlagsReg, do not have a result operand
3045     const char *reduce = (oper._matrule ? oper.reduce_result() : NULL);
3046     // operand stackSlot does not have a match rule, but produces a stackSlot
3047     if( oper.is_user_name_for_sReg() != Form::none ) reduce = oper.reduce_result();
3048     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3049     else          fprintf(_cpp, "  0");
3050   }
3051   void map(InstructForm &inst) {
3052     const char *reduce = (inst._matrule ? inst.reduce_result() : NULL);
3053     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3054     else          fprintf(_cpp, "  0");
3055   }
3056   void map(char         *reduce) { 
3057     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3058     else          fprintf(_cpp, "  0");
3059   }
3060 };
3061 
3062 // Information needed to generate the LeftOp mapping for the DFA
3063 class OutputLeftOp : public OutputMap {
3064 public:
3065   OutputLeftOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3066     : OutputMap(hpp, cpp, globals, AD) {};
3067 
3068   void declaration() { fprintf(_hpp, "extern const int   leftOp[];\n"); }
3069   void definition()  { fprintf(_cpp, "const        int   leftOp[] = {\n"); }
3070   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3071                        OutputMap::closing();
3072   }
3073   void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
3074   void map(OperandForm &oper) {
3075     const char *reduce = oper.reduce_left(_globals);
3076     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3077     else          fprintf(_cpp, "  0");
3078   }
3079   void map(char        *name) {
3080     const char *reduce = _AD.reduceLeft(name);
3081     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3082     else          fprintf(_cpp, "  0");
3083   }
3084   void map(InstructForm &inst) {
3085     const char *reduce = inst.reduce_left(_globals);
3086     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3087     else          fprintf(_cpp, "  0");
3088   }
3089 };
3090 
3091 
3092 // Information needed to generate the RightOp mapping for the DFA
3093 class OutputRightOp : public OutputMap {
3094 public:
3095   OutputRightOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3096     : OutputMap(hpp, cpp, globals, AD) {};
3097 
3098   void declaration() { fprintf(_hpp, "extern const int   rightOp[];\n"); }
3099   void definition()  { fprintf(_cpp, "const        int   rightOp[] = {\n"); }
3100   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3101                        OutputMap::closing();
3102   }
3103   void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
3104   void map(OperandForm &oper) {
3105     const char *reduce = oper.reduce_right(_globals);
3106     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3107     else          fprintf(_cpp, "  0");
3108   }
3109   void map(char        *name) {
3110     const char *reduce = _AD.reduceRight(name);
3111     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3112     else          fprintf(_cpp, "  0");
3113   }
3114   void map(InstructForm &inst) {
3115     const char *reduce = inst.reduce_right(_globals);
3116     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3117     else          fprintf(_cpp, "  0");
3118   }
3119 };
3120 
3121 
3122 // Information needed to generate the Rule names for the DFA
3123 class OutputRuleName : public OutputMap {
3124 public:
3125   OutputRuleName(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3126     : OutputMap(hpp, cpp, globals, AD) {};
3127 
3128   void declaration() { fprintf(_hpp, "extern const char *ruleName[];\n"); }
3129   void definition()  { fprintf(_cpp, "const char        *ruleName[] = {\n"); }
3130   void closing()     { fprintf(_cpp, "  \"no trailing comma\"\n");
3131                        OutputMap::closing();
3132   }
3133   void map(OpClassForm &opc)  { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(opc._ident) ); }
3134   void map(OperandForm &oper) { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(oper._ident) ); }
3135   void map(char        *name) { fprintf(_cpp, "  \"%s\"", name ? name : "0"); }
3136   void map(InstructForm &inst){ fprintf(_cpp, "  \"%s\"", inst._ident ? inst._ident : "0"); }
3137 };
3138 
3139 
3140 // Information needed to generate the swallowed mapping for the DFA
3141 class OutputSwallowed : public OutputMap {
3142 public:
3143   OutputSwallowed(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3144     : OutputMap(hpp, cpp, globals, AD) {};
3145 
3146   void declaration() { fprintf(_hpp, "extern const bool  swallowed[];\n"); }
3147   void definition()  { fprintf(_cpp, "const        bool  swallowed[] = {\n"); }
3148   void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
3149                        OutputMap::closing();
3150   }
3151   void map(OperandForm &oper) { // Generate the entry for this opcode
3152     const char *swallowed = oper.swallowed(_globals) ? "true" : "false";
3153     fprintf(_cpp, "  %s", swallowed);
3154   }
3155   void map(OpClassForm &opc)  { fprintf(_cpp, "  false"); }
3156   void map(char        *name) { fprintf(_cpp, "  false"); }
3157   void map(InstructForm &inst){ fprintf(_cpp, "  false"); }
3158 };
3159 
3160 
3161 // Information needed to generate the decision array for instruction chain rule
3162 class OutputInstChainRule : public OutputMap {
3163 public:
3164   OutputInstChainRule(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) 
3165     : OutputMap(hpp, cpp, globals, AD) {};
3166 
3167   void declaration() { fprintf(_hpp, "extern const bool  instruction_chain_rule[];\n"); }
3168   void definition()  { fprintf(_cpp, "const        bool  instruction_chain_rule[] = {\n"); }
3169   void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
3170                        OutputMap::closing();
3171   }
3172   void map(OpClassForm &opc)   { fprintf(_cpp, "  false"); }
3173   void map(OperandForm &oper)  { fprintf(_cpp, "  false"); }
3174   void map(char        *name)  { fprintf(_cpp, "  false"); }
3175   void map(InstructForm &inst) { // Check for simple chain rule
3176     const char *chain = inst.is_simple_chain_rule(_globals) ? "true" : "false";
3177     fprintf(_cpp, "  %s", chain);
3178   }
3179 };
3180 
3181 
3182 //---------------------------build_map------------------------------------
3183 // Build  mapping from enumeration for densely packed operands
3184 // TO result and child types.
3185 void ArchDesc::build_map(OutputMap &map) {
3186   FILE         *fp_hpp = map.decl_file();
3187   FILE         *fp_cpp = map.def_file();
3188   int           idx    = 0;
3189   OperandForm  *op;
3190   OpClassForm  *opc;
3191   InstructForm *inst;
3192 
3193   // Construct this mapping
3194   map.declaration();
3195   fprintf(fp_cpp,"\n");
3196   map.definition();
3197   
3198   // Output the mapping for operands
3199   map.record_position(OutputMap::BEGIN_OPERANDS, idx );
3200   _operands.reset(); 
3201   for(; (op = (OperandForm*)_operands.iter()) != NULL; ) {
3202     // Ensure this is a machine-world instruction
3203     if ( op->ideal_only() )  continue;
3204 
3205     // Generate the entry for this opcode
3206     map.map(*op);    fprintf(fp_cpp, ", // %d\n", idx);
3207     ++idx;
3208   };
3209   fprintf(fp_cpp, "  // last operand\n");
3210 
3211   // Place all user-defined operand classes into the mapping
3212   map.record_position(OutputMap::BEGIN_OPCLASSES, idx );
3213   _opclass.reset(); 
3214   for(; (opc = (OpClassForm*)_opclass.iter()) != NULL; ) {
3215     map.map(*opc);    fprintf(fp_cpp, ", // %d\n", idx);
3216     ++idx;
3217   };
3218   fprintf(fp_cpp, "  // last operand class\n");
3219 
3220   // Place all internally defined operands into the mapping
3221   map.record_position(OutputMap::BEGIN_INTERNALS, idx );
3222   _internalOpNames.reset(); 
3223   char *name = NULL;
3224   for(; (name = (char *)_internalOpNames.iter()) != NULL; ) {
3225     map.map(name);    fprintf(fp_cpp, ", // %d\n", idx);
3226     ++idx;
3227   };
3228   fprintf(fp_cpp, "  // last internally defined operand\n");
3229 
3230   // Place all user-defined instructions into the mapping
3231   if( map.do_instructions() ) {
3232     map.record_position(OutputMap::BEGIN_INSTRUCTIONS, idx );
3233     // Output all simple instruction chain rules first
3234     map.record_position(OutputMap::BEGIN_INST_CHAIN_RULES, idx );
3235     {
3236       _instructions.reset(); 
3237       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3238         // Ensure this is a machine-world instruction
3239         if ( inst->ideal_only() )  continue;
3240         if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
3241         if ( inst->rematerialize(_globalNames, get_registers()) ) continue;
3242         
3243         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3244         ++idx;
3245       };
3246       map.record_position(OutputMap::BEGIN_REMATERIALIZE, idx );
3247       _instructions.reset(); 
3248       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3249         // Ensure this is a machine-world instruction
3250         if ( inst->ideal_only() )  continue;
3251         if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
3252         if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;
3253         
3254         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3255         ++idx;
3256       };
3257       map.record_position(OutputMap::END_INST_CHAIN_RULES, idx );
3258     }
3259     // Output all instructions that are NOT simple chain rules
3260     {
3261       _instructions.reset(); 
3262       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3263         // Ensure this is a machine-world instruction
3264         if ( inst->ideal_only() )  continue;
3265         if ( inst->is_simple_chain_rule(_globalNames) ) continue;
3266         if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;
3267         
3268         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3269         ++idx;
3270       };
3271       map.record_position(OutputMap::END_REMATERIALIZE, idx );
3272       _instructions.reset(); 
3273       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3274         // Ensure this is a machine-world instruction
3275         if ( inst->ideal_only() )  continue;
3276         if ( inst->is_simple_chain_rule(_globalNames) ) continue;
3277         if ( inst->rematerialize(_globalNames, get_registers()) ) continue;
3278         
3279         map.map(*inst);      fprintf(fp_cpp, ", // %d\n", idx);
3280         ++idx;
3281       };
3282     }
3283     fprintf(fp_cpp, "  // last instruction\n");
3284     map.record_position(OutputMap::END_INSTRUCTIONS, idx );
3285   }
3286   // Finish defining table
3287   map.closing();
3288 };
3289 
3290 
3291 // Helper function for buildReduceMaps
3292 char reg_save_policy(const char *calling_convention) {
3293   char callconv;
3294 
3295   if      (!strcmp(calling_convention, "NS"))  callconv = 'N';
3296   else if (!strcmp(calling_convention, "SOE")) callconv = 'E';
3297   else if (!strcmp(calling_convention, "SOC")) callconv = 'C';
3298   else if (!strcmp(calling_convention, "AS"))  callconv = 'A';
3299   else                                         callconv = 'Z';
3300 
3301   return callconv;
3302 }
3303 
3304 //---------------------------generate_assertion_checks-------------------
3305 void ArchDesc::generate_adlc_verification(FILE *fp_cpp) {
3306   fprintf(fp_cpp, "\n");
3307 
3308   fprintf(fp_cpp, "#ifndef PRODUCT\n");
3309   fprintf(fp_cpp, "void Compile::adlc_verification() {\n");
3310   globalDefs().print_asserts(fp_cpp);
3311   fprintf(fp_cpp, "}\n");
3312   fprintf(fp_cpp, "#endif\n");
3313   fprintf(fp_cpp, "\n");
3314 }
3315 
3316 //---------------------------addSourceBlocks-----------------------------
3317 void ArchDesc::addSourceBlocks(FILE *fp_cpp) {
3318   if (_source.count() > 0)
3319     _source.output(fp_cpp);
3320 
3321   generate_adlc_verification(fp_cpp);
3322 }
3323 //---------------------------addHeaderBlocks-----------------------------
3324 void ArchDesc::addHeaderBlocks(FILE *fp_hpp) {
3325   if (_header.count() > 0)
3326     _header.output(fp_hpp); 
3327 }
3328 //-------------------------addPreHeaderBlocks----------------------------
3329 void ArchDesc::addPreHeaderBlocks(FILE *fp_hpp) {
3330   // Output #defines from definition block
3331   globalDefs().print_defines(fp_hpp);
3332 
3333   if (_pre_header.count() > 0)
3334     _pre_header.output(fp_hpp); 
3335 }
3336 
3337 //---------------------------buildReduceMaps-----------------------------
3338 // Build  mapping from enumeration for densely packed operands
3339 // TO result and child types.
3340 void ArchDesc::buildReduceMaps(FILE *fp_hpp, FILE *fp_cpp) {
3341   RegDef       *rdef;
3342   RegDef       *next;
3343 
3344   // The emit bodies currently require functions defined in the source block.
3345 
3346   // Build external declarations for mappings
3347   fprintf(fp_hpp, "\n");
3348   fprintf(fp_hpp, "extern const char  register_save_policy[];\n");
3349   fprintf(fp_hpp, "extern const char  c_reg_save_policy[];\n");
3350   fprintf(fp_hpp, "extern const int   register_save_type[];\n");
3351   fprintf(fp_hpp, "\n");
3352 
3353   // Construct Save-Policy array
3354   fprintf(fp_cpp, "// Map from machine-independent register number to register_save_policy\n");
3355   fprintf(fp_cpp, "const        char register_save_policy[] = {\n");
3356   _register->reset_RegDefs();
3357   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3358     next              = _register->iter_RegDefs();
3359     char policy       = reg_save_policy(rdef->_callconv);
3360     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3361     fprintf(fp_cpp, "  '%c'%s\n", policy, comma);
3362   }
3363   fprintf(fp_cpp, "};\n\n");
3364 
3365   // Construct Native Save-Policy array
3366   fprintf(fp_cpp, "// Map from machine-independent register number to c_reg_save_policy\n");
3367   fprintf(fp_cpp, "const        char c_reg_save_policy[] = {\n");
3368   _register->reset_RegDefs();
3369   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3370     next        = _register->iter_RegDefs();
3371     char policy = reg_save_policy(rdef->_c_conv);
3372     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3373     fprintf(fp_cpp, "  '%c'%s\n", policy, comma);
3374   }
3375   fprintf(fp_cpp, "};\n\n");
3376 
3377   // Construct Register Save Type array
3378   fprintf(fp_cpp, "// Map from machine-independent register number to register_save_type\n");
3379   fprintf(fp_cpp, "const        int register_save_type[] = {\n");
3380   _register->reset_RegDefs();
3381   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3382     next = _register->iter_RegDefs();
3383     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3384     fprintf(fp_cpp, "  %s%s\n", rdef->_idealtype, comma);
3385   }
3386   fprintf(fp_cpp, "};\n\n");
3387 
3388   // Construct the table for reduceOp
3389   OutputReduceOp output_reduce_op(fp_hpp, fp_cpp, _globalNames, *this);
3390   build_map(output_reduce_op);
3391   // Construct the table for leftOp
3392   OutputLeftOp output_left_op(fp_hpp, fp_cpp, _globalNames, *this);
3393   build_map(output_left_op);
3394   // Construct the table for rightOp
3395   OutputRightOp output_right_op(fp_hpp, fp_cpp, _globalNames, *this);
3396   build_map(output_right_op);
3397   // Construct the table of rule names
3398   OutputRuleName output_rule_name(fp_hpp, fp_cpp, _globalNames, *this);
3399   build_map(output_rule_name);
3400   // Construct the boolean table for subsumed operands
3401   OutputSwallowed output_swallowed(fp_hpp, fp_cpp, _globalNames, *this);
3402   build_map(output_swallowed);
3403   // // // Preserve in case we decide to use this table instead of another
3404   //// Construct the boolean table for instruction chain rules
3405   //OutputInstChainRule output_inst_chain(fp_hpp, fp_cpp, _globalNames, *this);
3406   //build_map(output_inst_chain);
3407 
3408 }
3409 
3410 
3411 //---------------------------buildMachOperGenerator---------------------------
3412 
3413 // Recurse through match tree, building path through corresponding state tree,
3414 // Until we reach the constant we are looking for.
3415 static void path_to_constant(FILE *fp, FormDict &globals,
3416                              MatchNode *mnode, uint idx) {
3417   if ( ! mnode) return;
3418   
3419   unsigned    position = 0;
3420   const char *result   = NULL;
3421   const char *name     = NULL;
3422   const char *optype   = NULL;
3423 
3424   // Base Case: access constant in ideal node linked to current state node
3425   // Each type of constant has its own access function
3426   if ( (mnode->_lChild == NULL) && (mnode->_rChild == NULL)
3427        && mnode->base_operand(position, globals, result, name, optype) ) {
3428     if (         strcmp(optype,"ConI") == 0 ) {
3429       fprintf(fp, "_leaf->get_int()");
3430     } else if ( (strcmp(optype,"ConP") == 0) ) {
3431       fprintf(fp, "_leaf->bottom_type()->is_ptr()");
3432     } else if ( (strcmp(optype,"ConF") == 0) ) {
3433       fprintf(fp, "_leaf->getf()");
3434     } else if ( (strcmp(optype,"ConD") == 0) ) {
3435       fprintf(fp, "_leaf->getd()");
3436     } else if ( (strcmp(optype,"ConL") == 0) ) {
3437       fprintf(fp, "_leaf->get_long()");
3438     } else if ( (strcmp(optype,"Con")==0) ) {
3439       // !!!!! - Update if adding a machine-independent constant type
3440       fprintf(fp, "_leaf->get_int()");
3441       assert( false, "Unsupported constant type, pointer or indefinite");
3442     } else if ( (strcmp(optype,"Bool") == 0) ) {
3443       fprintf(fp, "_leaf->as_Bool()->_test._test");
3444     } else {
3445       assert( false, "Unsupported constant type");
3446     }
3447     return;
3448   }
3449 
3450   // If constant is in left child, build path and recurse 
3451   uint lConsts = (mnode->_lChild) ? (mnode->_lChild->num_consts(globals) ) : 0;
3452   uint rConsts = (mnode->_rChild) ? (mnode->_rChild->num_consts(globals) ) : 0;
3453   if ( (mnode->_lChild) && (lConsts > idx) ) {
3454     fprintf(fp, "_kids[0]->");
3455     path_to_constant(fp, globals, mnode->_lChild, idx);
3456     return;
3457   } 
3458   // If constant is in right child, build path and recurse
3459   if ( (mnode->_rChild) && (rConsts > (idx - lConsts) ) ) {
3460     idx = idx - lConsts;
3461     fprintf(fp, "_kids[1]->");
3462     path_to_constant(fp, globals, mnode->_rChild, idx);
3463     return;
3464   }
3465   assert( false, "ShouldNotReachHere()");
3466 }
3467 
3468 // Generate code that is executed when generating a specific Machine Operand
3469 static void genMachOperCase(FILE *fp, FormDict &globalNames, ArchDesc &AD, 
3470                             OperandForm &op) {
3471   const char *opName         = op._ident;
3472   const char *opEnumName     = AD.machOperEnum(opName);
3473   uint        num_consts     = op.num_consts(globalNames);
3474 
3475   // Generate the case statement for this opcode
3476   fprintf(fp, "  case %s:", opEnumName);
3477   fprintf(fp, "\n    return new (C) %sOper(", opName);
3478   // Access parameters for constructor from the stat object
3479   // 
3480   // Build access to condition code value
3481   if ( (num_consts > 0) ) {
3482     uint i = 0;
3483     path_to_constant(fp, globalNames, op._matrule, i);
3484     for ( i = 1; i < num_consts; ++i ) {
3485       fprintf(fp, ", ");
3486       path_to_constant(fp, globalNames, op._matrule, i);
3487     }
3488   }
3489   fprintf(fp, " );\n");
3490 }
3491 
3492 
3493 // Build switch to invoke "new" MachNode or MachOper
3494 void ArchDesc::buildMachOperGenerator(FILE *fp_cpp) {
3495   int idx = 0;
3496 
3497   // Build switch to invoke 'new' for a specific MachOper
3498   fprintf(fp_cpp, "\n");
3499   fprintf(fp_cpp, "\n");
3500   fprintf(fp_cpp, 
3501           "//------------------------- MachOper Generator ---------------\n");
3502   fprintf(fp_cpp, 
3503           "// A switch statement on the dense-packed user-defined type system\n"
3504           "// that invokes 'new' on the corresponding class constructor.\n");
3505   fprintf(fp_cpp, "\n");
3506   fprintf(fp_cpp, "MachOper *State::MachOperGenerator");
3507   fprintf(fp_cpp, "(int opcode, Compile* C)");
3508   fprintf(fp_cpp, "{\n");
3509   fprintf(fp_cpp, "\n");
3510   fprintf(fp_cpp, "  switch(opcode) {\n");
3511 
3512   // Place all user-defined operands into the mapping
3513   _operands.reset();
3514   int  opIndex = 0;
3515   OperandForm *op;
3516   for( ; (op =  (OperandForm*)_operands.iter()) != NULL; ) {
3517     // Ensure this is a machine-world instruction
3518     if ( op->ideal_only() )  continue;
3519     
3520     genMachOperCase(fp_cpp, _globalNames, *this, *op);
3521   };
3522 
3523   // Do not iterate over operand classes for the  operand generator!!!
3524 
3525   // Place all internal operands into the mapping
3526   _internalOpNames.reset();
3527   const char *iopn;
3528   for( ; (iopn =  _internalOpNames.iter()) != NULL; ) {
3529     const char *opEnumName = machOperEnum(iopn);
3530     // Generate the case statement for this opcode
3531     fprintf(fp_cpp, "  case %s:", opEnumName);
3532     fprintf(fp_cpp, "    return NULL;\n");
3533   };
3534 
3535   // Generate the default case for switch(opcode)
3536   fprintf(fp_cpp, "  \n");
3537   fprintf(fp_cpp, "  default:\n");
3538   fprintf(fp_cpp, "    fprintf(stderr, \"Default MachOper Generator invoked for: \\n\");\n");
3539   fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
3540   fprintf(fp_cpp, "    break;\n");
3541   fprintf(fp_cpp, "  }\n");
3542 
3543   // Generate the closing for method Matcher::MachOperGenerator
3544   fprintf(fp_cpp, "  return NULL;\n");
3545   fprintf(fp_cpp, "};\n");
3546 }
3547 
3548 
3549 //---------------------------buildMachNode-------------------------------------
3550 // Build a new MachNode, for MachNodeGenerator or cisc-spilling
3551 void ArchDesc::buildMachNode(FILE *fp_cpp, InstructForm *inst, const char *indent) {
3552   const char *opType  = NULL;
3553   const char *opClass = inst->_ident; 
3554 
3555   // Create the MachNode object
3556   fprintf(fp_cpp, "%s %sNode *node = new (C) %sNode();\n",indent, opClass,opClass);
3557 
3558   if ( (inst->num_post_match_opnds() != 0) ) {
3559     // Instruction that contains operands which are not in match rule.
3560     // 
3561     // Check if the first post-match component may be an interesting def
3562     bool           dont_care = false;
3563     ComponentList &comp_list = inst->_components;
3564     Component     *comp      = NULL;
3565     comp_list.reset();
3566     if ( comp_list.match_iter() != NULL )    dont_care = true;
3567     
3568     // Insert operands that are not in match-rule.
3569     // Only insert a DEF if the do_care flag is set
3570     comp_list.reset();
3571     while ( comp = comp_list.post_match_iter() ) {
3572       // Check if we don't care about DEFs or KILLs that are not USEs
3573       if ( dont_care && (! comp->isa(Component::USE)) ) {
3574         continue;
3575       } 
3576       dont_care = true;
3577       // For each operand not in the match rule, call MachOperGenerator 
3578       // with the enum for the opcode that needs to be built
3579       // and the node just built, the parent of the operand.
3580       ComponentList clist = inst->_components;
3581       int         index  = clist.operand_position(comp->_name, comp->_usedef);
3582       const char *opcode = machOperEnum(comp->_type);
3583       const char *parent = "node";
3584       fprintf(fp_cpp, "%s node->set_opnd_array(%d, ", indent, index);
3585       fprintf(fp_cpp, "MachOperGenerator(%s, C));\n", opcode);
3586       }
3587   } 
3588   else if ( inst->is_chain_of_constant(_globalNames, opType) ) {
3589     // An instruction that chains from a constant!
3590     // In this case, we need to subsume the constant into the node
3591     // at operand position, oper_input_base().
3592     // 
3593     // Fill in the constant
3594     fprintf(fp_cpp, "%s node->_opnd_array[%d] = ", indent, 
3595             inst->oper_input_base(_globalNames));
3596     // #####
3597     // Check for multiple constants and then fill them in.
3598     // Just like MachOperGenerator
3599     const char *opName = inst->_matrule->_rChild->_opType;
3600     fprintf(fp_cpp, "new (C) %sOper(", opName);
3601     // Grab operand form
3602     OperandForm *op = (_globalNames[opName])->is_operand();
3603     // Look up the number of constants
3604     uint num_consts = op->num_consts(_globalNames);
3605     if ( (num_consts > 0) ) {
3606       uint i = 0;
3607       path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
3608       for ( i = 1; i < num_consts; ++i ) {
3609         fprintf(fp_cpp, ", ");
3610         path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
3611       }
3612     }
3613     fprintf(fp_cpp, " );\n");
3614     // #####
3615   }
3616   
3617   // Fill in the bottom_type where requested
3618   if ( inst->captures_bottom_type() ) {
3619     fprintf(fp_cpp, "%s node->_bottom_type = _leaf->bottom_type();\n", indent);
3620   }
3621   if( inst->is_ideal_if() ) {
3622     fprintf(fp_cpp, "%s node->_prob = _leaf->as_If()->_prob;\n", indent);
3623     fprintf(fp_cpp, "%s node->_fcnt = _leaf->as_If()->_fcnt;\n", indent);
3624   }
3625   if( inst->is_ideal_fastlock() ) {
3626     fprintf(fp_cpp, "%s node->_counters = _leaf->as_FastLock()->counters();\n", indent);
3627   }
3628   
3629 }
3630 
3631 //---------------------------declare_cisc_version------------------------------
3632 // Build CISC version of this instruction
3633 void InstructForm::declare_cisc_version(ArchDesc &AD, FILE *fp_hpp) {
3634   if( AD.can_cisc_spill() ) {
3635     InstructForm *inst_cisc = cisc_spill_alternate();
3636     if (inst_cisc != NULL) {
3637       fprintf(fp_hpp, "  virtual int            cisc_operand() const { return %d; }\n", cisc_spill_operand());
3638       fprintf(fp_hpp, "  virtual MachNode      *cisc_version(int offset, Compile* C);\n");
3639       fprintf(fp_hpp, "  virtual void           use_cisc_RegMask();\n");
3640       fprintf(fp_hpp, "  virtual const RegMask *cisc_RegMask() const { return _cisc_RegMask; }\n");
3641     }
3642   }
3643 }
3644 
3645 //---------------------------define_cisc_version-------------------------------
3646 // Build CISC version of this instruction
3647 bool InstructForm::define_cisc_version(ArchDesc &AD, FILE *fp_cpp) {
3648   InstructForm *inst_cisc = this->cisc_spill_alternate();
3649   if( AD.can_cisc_spill() && (inst_cisc != NULL) ) {
3650     const char   *name      = inst_cisc->_ident;
3651     assert( inst_cisc->num_opnds() == this->num_opnds(), "Must have same number of operands");
3652     OperandForm *cisc_oper = AD.cisc_spill_operand();
3653     assert( cisc_oper != NULL, "insanity check");
3654     const char *cisc_oper_name  = cisc_oper->_ident;
3655     assert( cisc_oper_name != NULL, "insanity check");
3656     //
3657     // Set the correct reg_mask_or_stack for the cisc operand
3658     fprintf(fp_cpp, "\n");
3659     fprintf(fp_cpp, "void %sNode::use_cisc_RegMask() {\n", this->_ident);
3660     // Lookup the correct reg_mask_or_stack
3661     const char *reg_mask_name = cisc_reg_mask_name();
3662     fprintf(fp_cpp, "  _cisc_RegMask = &STACK_OR_%s;\n", reg_mask_name);
3663     fprintf(fp_cpp, "}\n");
3664     //
3665     // Construct CISC version of this instruction
3666     fprintf(fp_cpp, "\n");
3667     fprintf(fp_cpp, "// Build CISC version of this instruction\n");
3668     fprintf(fp_cpp, "MachNode *%sNode::cisc_version( int offset, Compile* C ) {\n", this->_ident);
3669     // Create the MachNode object
3670     fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
3671     // Fill in the bottom_type where requested
3672     if ( this->captures_bottom_type() ) {
3673       fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
3674     }
3675     fprintf(fp_cpp, "\n");
3676     fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
3677     fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
3678     // Construct operand to access [stack_pointer + offset]
3679     fprintf(fp_cpp, "  // Construct operand to access [stack_pointer + offset]\n");
3680     fprintf(fp_cpp, "  node->set_opnd_array(cisc_operand(), new (C) %sOper(offset));\n", cisc_oper_name);
3681     fprintf(fp_cpp, "\n");
3682 
3683     // Return result and exit scope
3684     fprintf(fp_cpp, "  return node;\n");
3685     fprintf(fp_cpp, "}\n");
3686     fprintf(fp_cpp, "\n");
3687     return true;
3688   }
3689   return false;
3690 }
3691 
3692 //---------------------------declare_short_branch_methods----------------------
3693 // Build prototypes for short branch methods
3694 void InstructForm::declare_short_branch_methods(FILE *fp_hpp) {
3695   if (has_short_branch_form()) {
3696     fprintf(fp_hpp, "  virtual MachNode      *short_branch_version(Compile* C);\n");
3697   }
3698 }
3699 
3700 //---------------------------define_short_branch_methods-----------------------
3701 // Build definitions for short branch methods
3702 bool InstructForm::define_short_branch_methods(FILE *fp_cpp) {
3703   if (has_short_branch_form()) {
3704     InstructForm *short_branch = short_branch_form();
3705     const char   *name         = short_branch->_ident;
3706 
3707     // Construct short_branch_version() method.
3708     fprintf(fp_cpp, "// Build short branch version of this instruction\n");
3709     fprintf(fp_cpp, "MachNode *%sNode::short_branch_version(Compile* C) {\n", this->_ident);
3710     // Create the MachNode object
3711     fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
3712     if( is_ideal_if() ) {
3713       fprintf(fp_cpp, "  node->_prob = _prob;\n");
3714       fprintf(fp_cpp, "  node->_fcnt = _fcnt;\n");
3715     }
3716     // Fill in the bottom_type where requested
3717     if ( this->captures_bottom_type() ) {
3718       fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
3719     }
3720 
3721     fprintf(fp_cpp, "\n");
3722     // Short branch version must use same node index for access
3723     // through allocator's tables
3724     fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
3725     fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
3726 
3727     // Return result and exit scope
3728     fprintf(fp_cpp, "  return node;\n");
3729     fprintf(fp_cpp, "}\n");
3730     fprintf(fp_cpp,"\n");
3731     return true;
3732   }
3733   return false;
3734 }
3735 
3736 
3737 //---------------------------buildMachNodeGenerator----------------------------
3738 // Build switch to invoke appropriate "new" MachNode for an opcode
3739 void ArchDesc::buildMachNodeGenerator(FILE *fp_cpp) {
3740 
3741   // Build switch to invoke 'new' for a specific MachNode
3742   fprintf(fp_cpp, "\n");
3743   fprintf(fp_cpp, "\n");
3744   fprintf(fp_cpp, 
3745           "//------------------------- MachNode Generator ---------------\n");
3746   fprintf(fp_cpp, 
3747           "// A switch statement on the dense-packed user-defined type system\n"
3748           "// that invokes 'new' on the corresponding class constructor.\n");
3749   fprintf(fp_cpp, "\n");
3750   fprintf(fp_cpp, "MachNode *State::MachNodeGenerator");
3751   fprintf(fp_cpp, "(int opcode, Compile* C)");
3752   fprintf(fp_cpp, "{\n");
3753   fprintf(fp_cpp, "  switch(opcode) {\n");
3754  
3755   // Provide constructor for all user-defined instructions
3756   _instructions.reset(); 
3757   int  opIndex = operandFormCount();
3758   InstructForm *inst;
3759   for( ; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3760     // Ensure that matrule is defined.
3761     if ( inst->_matrule == NULL ) continue;
3762 
3763     int         opcode  = opIndex++;
3764     const char *opClass = inst->_ident; 
3765     char       *opType  = NULL;
3766 
3767     // Generate the case statement for this instruction
3768     fprintf(fp_cpp, "  case %s_rule:", opClass);
3769 
3770     // Start local scope 
3771     fprintf(fp_cpp, "  {\n");
3772     // Generate code to construct the new MachNode
3773     buildMachNode(fp_cpp, inst, "     ");
3774     // Return result and exit scope
3775     fprintf(fp_cpp, "      return node;\n");
3776     fprintf(fp_cpp, "    }\n");
3777   }
3778 
3779   // Generate the default case for switch(opcode)
3780   fprintf(fp_cpp, "  \n");
3781   fprintf(fp_cpp, "  default:\n");
3782   fprintf(fp_cpp, "    fprintf(stderr, \"Default MachNode Generator invoked for: \\n\");\n");
3783   fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
3784   fprintf(fp_cpp, "    break;\n");
3785   fprintf(fp_cpp, "  };\n");
3786 
3787   // Generate the closing for method Matcher::MachNodeGenerator
3788   fprintf(fp_cpp, "  return NULL;\n");
3789   fprintf(fp_cpp, "}\n");
3790 }
3791 
3792 
3793 //---------------------------buildInstructMatchCheck--------------------------
3794 // Output the method to Matcher which checks whether or not a specific
3795 // instruction has a matching rule for the host architecture.
3796 void ArchDesc::buildInstructMatchCheck(FILE *fp_cpp) const {
3797   fprintf(fp_cpp, "\n\n");
3798   fprintf(fp_cpp, "const bool Matcher::has_match_rule(int opcode) {\n");
3799   fprintf(fp_cpp, "  assert(_last_machine_leaf < opcode && opcode < _last_opcode, \"opcode in range\");\n");
3800   fprintf(fp_cpp, "  return _hasMatchRule[opcode];\n");
3801   fprintf(fp_cpp, "}\n\n");
3802 
3803   fprintf(fp_cpp, "const bool Matcher::_hasMatchRule[_last_opcode] = {\n");
3804   int i;
3805   for (i = 0; i < _last_opcode - 1; i++) {
3806     fprintf(fp_cpp, "    %-5s,  // %s\n",
3807             _has_match_rule[i] ? "true" : "false",
3808             NodeClassNames[i]);
3809   }
3810   fprintf(fp_cpp, "    %-5s   // %s\n",
3811           _has_match_rule[i] ? "true" : "false",
3812           NodeClassNames[i]);
3813   fprintf(fp_cpp, "};\n");
3814 }
3815 
3816 //---------------------------buildFrameMethods---------------------------------
3817 // Output the methods to Matcher which specify frame behavior
3818 void ArchDesc::buildFrameMethods(FILE *fp_cpp) {
3819   fprintf(fp_cpp,"\n\n");
3820   // Stack Direction
3821   fprintf(fp_cpp,"bool Matcher::stack_direction() const { return %s; }\n\n",
3822           _frame->_direction ? "true" : "false");
3823   // Sync Stack Slots
3824   fprintf(fp_cpp,"int Compile::sync_stack_slots() const { return %s; }\n\n",
3825           _frame->_sync_stack_slots);
3826   // Java Stack Alignment
3827   fprintf(fp_cpp,"uint Matcher::stack_alignment_in_bytes() { return %s; }\n\n",
3828           _frame->_alignment);
3829   // Java Return Address Location
3830   fprintf(fp_cpp,"OptoReg::Name Matcher::return_addr() const {");
3831   if (_frame->_return_addr_loc) {
3832     fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3833             _frame->_return_addr);
3834   }
3835   else {
3836     fprintf(fp_cpp," return OptoReg::stack2reg(%s); }\n\n",
3837             _frame->_return_addr);
3838   }
3839   // Java Stack Slot Preservation
3840   fprintf(fp_cpp,"uint Compile::in_preserve_stack_slots() ");
3841   fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_in_preserve_slots);
3842   // Top Of Stack Slot Preservation, for both Java and C
3843   fprintf(fp_cpp,"uint Compile::out_preserve_stack_slots() ");
3844   fprintf(fp_cpp,"{ return SharedRuntime::out_preserve_stack_slots(); }\n\n");
3845   // varargs C out slots killed
3846   fprintf(fp_cpp,"uint Compile::varargs_C_out_slots_killed() const ");
3847   fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_varargs_C_out_slots_killed);
3848   // Java Argument Position
3849   fprintf(fp_cpp,"void Matcher::calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length, bool is_outgoing) {\n");
3850   fprintf(fp_cpp,"%s\n", _frame->_calling_convention);
3851   fprintf(fp_cpp,"}\n\n");
3852   // Native Argument Position
3853   fprintf(fp_cpp,"void Matcher::c_calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length) {\n");
3854   fprintf(fp_cpp,"%s\n", _frame->_c_calling_convention);
3855   fprintf(fp_cpp,"}\n\n");
3856   // Java Return Value Location
3857   fprintf(fp_cpp,"OptoRegPair Matcher::return_value(int ideal_reg, bool is_outgoing) {\n");
3858   fprintf(fp_cpp,"%s\n", _frame->_return_value);
3859   fprintf(fp_cpp,"}\n\n");
3860   // Native Return Value Location
3861   fprintf(fp_cpp,"OptoRegPair Matcher::c_return_value(int ideal_reg, bool is_outgoing) {\n");
3862   fprintf(fp_cpp,"%s\n", _frame->_c_return_value);
3863   fprintf(fp_cpp,"}\n\n");
3864 
3865   // Inline Cache Register, mask definition, and encoding
3866   fprintf(fp_cpp,"OptoReg::Name Matcher::inline_cache_reg() {");
3867   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3868           _frame->_inline_cache_reg);
3869   fprintf(fp_cpp,"const RegMask &Matcher::inline_cache_reg_mask() {");
3870   fprintf(fp_cpp," return INLINE_CACHE_REG_mask; }\n\n");
3871   fprintf(fp_cpp,"int Matcher::inline_cache_reg_encode() {");
3872   fprintf(fp_cpp," return _regEncode[inline_cache_reg()]; }\n\n");
3873 
3874   // Interpreter's Method Oop Register, mask definition, and encoding
3875   fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_method_oop_reg() {");
3876   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3877           _frame->_interpreter_method_oop_reg);
3878   fprintf(fp_cpp,"const RegMask &Matcher::interpreter_method_oop_reg_mask() {");
3879   fprintf(fp_cpp," return INTERPRETER_METHOD_OOP_REG_mask; }\n\n");
3880   fprintf(fp_cpp,"int Matcher::interpreter_method_oop_reg_encode() {");
3881   fprintf(fp_cpp," return _regEncode[interpreter_method_oop_reg()]; }\n\n");
3882 
3883   // Interpreter's Frame Pointer Register, mask definition, and encoding
3884   fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_frame_pointer_reg() {");
3885   if (_frame->_interpreter_frame_pointer_reg == NULL)
3886     fprintf(fp_cpp," return OptoReg::Bad; }\n\n");
3887   else
3888     fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3889             _frame->_interpreter_frame_pointer_reg);
3890   fprintf(fp_cpp,"const RegMask &Matcher::interpreter_frame_pointer_reg_mask() {");
3891   if (_frame->_interpreter_frame_pointer_reg == NULL)
3892     fprintf(fp_cpp," static RegMask dummy; return dummy; }\n\n");
3893   else
3894     fprintf(fp_cpp," return INTERPRETER_FRAME_POINTER_REG_mask; }\n\n");
3895 
3896   // Frame Pointer definition
3897   /* CNC - I can not contemplate having a different frame pointer between
3898      Java and native code; makes my head hurt to think about it.
3899   fprintf(fp_cpp,"OptoReg::Name Matcher::frame_pointer() const {");
3900   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3901           _frame->_frame_pointer);
3902   */
3903   // (Native) Frame Pointer definition
3904   fprintf(fp_cpp,"OptoReg::Name Matcher::c_frame_pointer() const {");
3905   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
3906           _frame->_frame_pointer);
3907 
3908   // Number of callee-save + always-save registers for calling convention
3909   fprintf(fp_cpp, "// Number of callee-save + always-save registers\n");
3910   fprintf(fp_cpp, "int  Matcher::number_of_saved_registers() {\n");
3911   RegDef *rdef;
3912   int nof_saved_registers = 0;
3913   _register->reset_RegDefs();
3914   while( (rdef = _register->iter_RegDefs()) != NULL ) {
3915     if( !strcmp(rdef->_callconv, "SOE") ||  !strcmp(rdef->_callconv, "AS") )
3916       ++nof_saved_registers;
3917   }
3918   fprintf(fp_cpp, "  return %d;\n", nof_saved_registers);
3919   fprintf(fp_cpp, "};\n\n");
3920 }
3921 
3922 
3923 
3924 
3925 static int PrintAdlcCisc = 0;
3926 //---------------------------identify_cisc_spilling----------------------------
3927 // Get info for the CISC_oracle and MachNode::cisc_version()
3928 void ArchDesc::identify_cisc_spill_instructions() {
3929 
3930   // Find the user-defined operand for cisc-spilling
3931   if( _frame->_cisc_spilling_operand_name != NULL ) {
3932     const Form *form = _globalNames[_frame->_cisc_spilling_operand_name];
3933     OperandForm *oper = form ? form->is_operand() : NULL;
3934     // Verify the user's suggestion 
3935     if( oper != NULL ) {
3936       // Ensure that match field is defined.
3937       if ( oper->_matrule != NULL )  {
3938         MatchRule &mrule = *oper->_matrule;
3939         if( strcmp(mrule._opType,"AddP") == 0 ) {
3940           MatchNode *left = mrule._lChild;
3941           MatchNode *right= mrule._rChild;
3942           if( left != NULL && right != NULL ) {
3943             const Form *left_op  = _globalNames[left->_opType]->is_operand();
3944             const Form *right_op = _globalNames[right->_opType]->is_operand();
3945             if(  (left_op != NULL && right_op != NULL)
3946               && (left_op->interface_type(_globalNames) == Form::register_interface)
3947               && (right_op->interface_type(_globalNames) == Form::constant_interface) ) {
3948               // Successfully verified operand
3949               set_cisc_spill_operand( oper );
3950               if( _cisc_spill_debug ) {
3951                 fprintf(stderr, "\n\nVerified CISC-spill operand %s\n\n", oper->_ident);
3952              }
3953             }
3954           }
3955         }
3956       }
3957     }
3958   }
3959 
3960   if( cisc_spill_operand() != NULL ) {
3961     // N^2 comparison of instructions looking for a cisc-spilling version
3962     _instructions.reset(); 
3963     InstructForm *instr;
3964     for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3965       // Ensure that match field is defined.
3966       if ( instr->_matrule == NULL )  continue;
3967 
3968       MatchRule &mrule = *instr->_matrule;
3969       Predicate *pred  =  instr->build_predicate();
3970 
3971       // Grab the machine type of the operand
3972       const char *rootOp = instr->_ident;
3973       mrule._machType    = rootOp;
3974 
3975       // Find result type for match
3976       const char *result = instr->reduce_result();
3977 
3978       if( PrintAdlcCisc ) fprintf(stderr, "  new instruction %s \n", instr->_ident ? instr->_ident : " ");
3979       bool  found_cisc_alternate = false;
3980       _instructions.reset2();
3981       InstructForm *instr2;
3982       for( ; !found_cisc_alternate && (instr2 = (InstructForm*)_instructions.iter2()) != NULL; ) {
3983         // Ensure that match field is defined.
3984         if( PrintAdlcCisc ) fprintf(stderr, "  instr2 == %s \n", instr2->_ident ? instr2->_ident : " ");
3985         if ( instr2->_matrule != NULL
3986             && (instr != instr2 )                // Skip self
3987             && (instr2->reduce_result() != NULL) // want same result
3988             && (strcmp(result, instr2->reduce_result()) == 0)) {
3989           MatchRule &mrule2 = *instr2->_matrule;
3990           Predicate *pred2  =  instr2->build_predicate();
3991           found_cisc_alternate = instr->cisc_spills_to(*this, instr2);
3992         }
3993       }
3994     }
3995   }
3996 }
3997 
3998 //---------------------------build_cisc_spilling-------------------------------
3999 // Get info for the CISC_oracle and MachNode::cisc_version()
4000 void ArchDesc::build_cisc_spill_instructions(FILE *fp_hpp, FILE *fp_cpp) {
4001   // Output the table for cisc spilling
4002   fprintf(fp_cpp, "//  The following instructions can cisc-spill\n");
4003   _instructions.reset(); 
4004   InstructForm *inst = NULL;
4005   for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
4006     // Ensure this is a machine-world instruction
4007     if ( inst->ideal_only() )  continue;
4008     const char *inst_name = inst->_ident;
4009     int   operand   = inst->cisc_spill_operand();
4010     if( operand != AdlcVMDeps::Not_cisc_spillable ) {
4011       InstructForm *inst2 = inst->cisc_spill_alternate();
4012       fprintf(fp_cpp, "//  %s can cisc-spill operand %d to %s\n", inst->_ident, operand, inst2->_ident);
4013     }
4014   }
4015   fprintf(fp_cpp, "\n\n");
4016 }
4017 
4018 //---------------------------identify_short_branches----------------------------
4019 // Get info for our short branch replacement oracle.
4020 void ArchDesc::identify_short_branches() {
4021   // Walk over all instructions, checking to see if they match a short
4022   // branching alternate.
4023   _instructions.reset(); 
4024   InstructForm *instr;
4025   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
4026     // The instruction must have a match rule.
4027     if (instr->_matrule != NULL &&
4028         instr->is_short_branch()) {
4029 
4030       _instructions.reset2();
4031       InstructForm *instr2;
4032       while( (instr2 = (InstructForm*)_instructions.iter2()) != NULL ) {
4033         instr2->check_branch_variant(*this, instr);
4034       }
4035     }
4036   }
4037 }
4038 
4039 
4040 //---------------------------identify_unique_operands---------------------------
4041 // Identify unique operands.
4042 void ArchDesc::identify_unique_operands() {
4043   // Walk over all instructions.
4044   _instructions.reset(); 
4045   InstructForm *instr;
4046   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
4047     // Ensure this is a machine-world instruction
4048     if (!instr->ideal_only()) {
4049       instr->set_unique_opnds();
4050     }
4051   }
4052 }