src/share/vm/adlc/output_c.cpp

Fri, 29 Apr 2016 00:06:10 +0800

author
aoqi
date
Fri, 29 Apr 2016 00:06:10 +0800
changeset 1
2d8a650513c2
parent 0
f90c822e73f8
child 6876
710a3c8b516e
permissions
-rw-r--r--

Added MIPS 64-bit port.

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

mercurial