src/share/vm/adlc/output_c.cpp

Fri, 05 Apr 2013 11:09:43 +0200

author
neliasso
date
Fri, 05 Apr 2013 11:09:43 +0200
changeset 4906
705ef39fcaa9
parent 4161
d336b3173277
child 5221
f15fe46d8c00
permissions
-rw-r--r--

8006016: Memory leak at hotspot/src/share/vm/adlc/output_c.cpp
Reviewed-by: kvn, roland
Contributed-by: niclas.adlertz@oracle.com

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

mercurial