home *** CD-ROM | disk | FTP | other *** search
/ Amiga ISO Collection / AmigaUtilCD2.iso / Programming / GCC / GERLIB_DEV08B.LHA / gerlib / libg++ / gperf / src / gen-perf.cc < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-12  |  11.0 KB  |  362 lines

  1. /* Provides high-level routines to manipulate the keywork list 
  2.    structures the code generation output.
  3.    Copyright (C) 1989 Free Software Foundation, Inc.
  4.    written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  5.  
  6. This file is part of GNU GPERF.
  7.  
  8. GNU GPERF is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 1, or (at your option)
  11. any later version.
  12.  
  13. GNU GPERF is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with GNU GPERF; see the file COPYING.  If not, write to
  20. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. #include <stdio.h>
  23. #include <std.h>
  24. #include <assert.h>
  25. #include <ctype.h>
  26. #include <time.h>
  27. #include "options.h"
  28. #include "gen-perf.h"
  29. #include "trace.h"
  30.  
  31. /* Current release version. */
  32. extern char *version_string;
  33.  
  34. /* Efficiently returns the least power of two greater than or equal to X! */
  35. #define POW(X) ((!X)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X)))
  36.  
  37. #include <_G_config.h>
  38. #ifdef _G_SYSV
  39. #define srandom srand
  40. #define random rand
  41. #endif
  42.  
  43. int Vectors::occurrences[ALPHA_SIZE];
  44. int Vectors::asso_values[ALPHA_SIZE];
  45.  
  46. /* Reads input keys, possibly applies the reordering heuristic, sets the
  47.    maximum associated value size (rounded up to the nearest power of 2),
  48.    may initialize the associated values array, and determines the maximum
  49.    hash table size.  Note: using the random numbers is often helpful,
  50.    though not as deterministic, of course! */
  51.  
  52. Gen_Perf::Gen_Perf (void)
  53. {
  54.   T (Trace t ("Gen_Perf::Gen_Perf");)
  55.   int asso_value_max;
  56.   int non_linked_length;
  57.  
  58.   Key_List::read_keys ();
  59.   if (option[ORDER])
  60.     reorder ();
  61.   asso_value_max    = option.get_asso_max ();
  62.   non_linked_length = Key_List::keyword_list_length ();
  63.   num_done          = 1;
  64.   fewest_collisions = 0;
  65.   if (asso_value_max == 0)
  66.     asso_value_max = non_linked_length;
  67.   else if (asso_value_max > 0)
  68.     asso_value_max *= non_linked_length;
  69.   else /* if (asso_value_max < 0) */
  70.     asso_value_max = non_linked_length / -asso_value_max;
  71.   option.set_asso_max (POW (asso_value_max));
  72.   
  73.   if (option[RANDOM])
  74.     {
  75.       srandom (time (0));
  76.       
  77.       for (int i = 0; i < ALPHA_SIZE; i++)
  78.         asso_values[i] = (random () & asso_value_max - 1);
  79.     }
  80.   else
  81.     {
  82.       int asso_value = option.initial_value ();
  83.       
  84.       if (asso_value)           /* Initialize array if user requests non-zero default. */
  85.         for (int i = ALPHA_SIZE - 1; i >= 0; i--)
  86.           asso_values[i] = asso_value & option.get_asso_max () - 1;
  87.     }
  88.   max_hash_value = Key_List::max_key_length () + option.get_asso_max () * 
  89.     option.get_max_keysig_size ();
  90.   
  91.   printf ("/* ");
  92.   if (option[C])
  93.     printf ("C");
  94.   else if (option[CPLUSPLUS])
  95.     printf ("C++");
  96.   printf (" code produced by gperf version %s */\n", version_string);
  97.   Options::print_options ();
  98.  
  99.   if (option[DEBUG])
  100.     fprintf (stderr, "total non-linked keys = %d\nmaximum associated value is %d"
  101.              "\nmaximum size of generated hash table is %d\n",
  102.              non_linked_length, asso_value_max, max_hash_value);
  103. }
  104.  
  105. /* Merge two disjoint hash key multisets to form the ordered disjoint union of the sets.
  106.    (In a multiset, an element can occur multiple times).
  107.    Precondition: both set_1 and set_2 must be ordered. Returns the length
  108.    of the combined set. */
  109.  
  110. inline int 
  111. Gen_Perf::compute_disjoint_union (char *set_1, char *set_2, char *set_3)
  112. {
  113.   T (Trace t ("Gen_Perf::compute_disjoint_union");)
  114.   char *base = set_3;
  115.   
  116.   while (*set_1 && *set_2)
  117.     if (*set_1 == *set_2)
  118.       set_1++, set_2++; 
  119.     else
  120.       {
  121.         *set_3 = *set_1 < *set_2 ? *set_1++ : *set_2++;
  122.         if (set_3 == base || *set_3 != *(set_3-1)) set_3++;
  123.       }
  124.    
  125.   while (*set_1)
  126.     {
  127.       *set_3 = *set_1++; 
  128.       if (set_3 == base || *set_3 != *(set_3-1)) set_3++;
  129.     }
  130.    
  131.   while (*set_2)
  132.     {
  133.       *set_3 = *set_2++; 
  134.       if (set_3 == base || *set_3 != *(set_3-1)) set_3++;
  135.     }
  136.   *set_3 = '\0';
  137.   return set_3 - base;
  138. }
  139.  
  140. /* Sort the UNION_SET in increasing frequency of occurrence.
  141.    This speeds up later processing since we may assume the resulting
  142.    set (Set_3, in this case), is ordered. Uses insertion sort, since
  143.    the UNION_SET is typically short. */
  144.   
  145. inline void 
  146. Gen_Perf::sort_set (char *union_set, int len)
  147. {
  148.   T (Trace t ("Gen_Perf::sort_set");)
  149.   int i, j;
  150.   
  151.   for (i = 0, j = len - 1; i < j; i++)
  152.     {
  153.       char curr, tmp;
  154.  
  155.       for (curr = i + 1, tmp = union_set[curr]; 
  156.            curr > 0 && occurrences[tmp] < occurrences[union_set[curr-1]]; 
  157.            curr--)
  158.         union_set[curr] = union_set[curr - 1];
  159.       
  160.       union_set[curr] = tmp;
  161.     }
  162. }
  163.  
  164. /* Generate a key set's hash value. */
  165.  
  166. inline int 
  167. Gen_Perf::hash (List_Node *key_node) 
  168. {                             
  169.   T (Trace t ("Gen_Perf::hash");)
  170.   int   sum = option[NOLENGTH] ? 0 : key_node->length;
  171.  
  172.   for (char *ptr = key_node->char_set; *ptr; ptr++)
  173.       sum += asso_values[*ptr];
  174.   
  175.   return key_node->hash_value = sum;
  176. }
  177.  
  178. /* Find out how character value change affects successfully hashed items.
  179.    Returns FALSE if no other hash values are affected, else returns TRUE.
  180.    Note that because Option.Get_Asso_Max is a power of two we can guarantee
  181.    that all legal Asso_Values are visited without repetition since
  182.    Option.Get_Jump was forced to be an odd value! */
  183.  
  184. inline int  
  185. Gen_Perf::affects_prev (char c, List_Node *curr)
  186. {
  187.   T (Trace t ("Gen_Perf::affects_prev");)
  188.   int original_char = asso_values[c];
  189.   int total_iterations = !option[FAST]
  190.     ? option.get_asso_max () : option.get_iterations () ? option.get_iterations () : keyword_list_length ();
  191.   
  192.   /* Try all legal associated values. */
  193.  
  194.   for (int i = total_iterations - 1; i >= 0; i--)
  195.     { 
  196.       int collisions = 0;
  197.  
  198.       asso_values[c] = asso_values[c] + (option.get_jump () ? option.get_jump () : random ())
  199.                                          & option.get_asso_max () - 1;
  200.  
  201.       /* Iteration Number array is a win, O(1) intialization time! */
  202.       reset ();     
  203.                                          
  204.       /* See how this asso_value change affects previous keywords.  If
  205.          it does better than before we'll take it! */
  206.  
  207.       for (List_Node *ptr = head;
  208.            !Bool_Array::find (hash (ptr)) || ++collisions < fewest_collisions;
  209.            ptr = ptr->next)
  210.         if (ptr == curr)
  211.           {
  212.             fewest_collisions = collisions;
  213.             if (option[DEBUG])
  214.               fprintf (stderr, "- resolved after %d iterations", total_iterations - i);
  215.             return 0;
  216.           }    
  217.     }
  218.   
  219.   /* Restore original values, no more tries. */
  220.   asso_values[c] = original_char; 
  221.   /* If we're this far it's time to try the next character.... */
  222.   return 1; 
  223. }
  224.  
  225. /* Change a character value, try least-used characters first. */
  226.  
  227. void 
  228. Gen_Perf::change (List_Node *prior, List_Node *curr)
  229. {
  230.   T (Trace t ("Gen_Perf::change");)
  231.   static char *union_set;
  232.  
  233.   if (!union_set)
  234.     union_set = new char [2 * option.get_max_keysig_size () + 1];
  235.  
  236.   if (option[DEBUG])
  237.     {
  238.       fprintf (stderr, "collision on keyword #%d, prior = \"%s\", curr = \"%s\" hash = %d\n",
  239.                num_done, prior->key, curr->key, curr->hash_value);
  240.       fflush (stderr);
  241.     }
  242.   sort_set (union_set, compute_disjoint_union (prior->char_set, curr->char_set, union_set));
  243.  
  244.   /* Try changing some values, if change doesn't alter other values continue normal action. */
  245.   fewest_collisions++;
  246.   
  247.   for (char *temp = union_set; *temp; temp++)
  248.     if (!affects_prev (*temp, curr))
  249.       {
  250.         if (option[DEBUG])
  251.           {
  252.             fprintf (stderr, " by changing asso_value['%c'] (char #%d) to %d\n", 
  253.                      *temp, temp - union_set + 1, asso_values[*temp]);
  254.             fflush (stderr);
  255.           }
  256.         return; /* Good, doesn't affect previous hash values, we'll take it. */
  257.       }
  258.  
  259.   for (List_Node *ptr = head; ptr != curr; ptr = ptr->next)
  260.     hash (ptr);
  261.   
  262.   hash (curr);
  263.  
  264.   if (option[DEBUG])
  265.     {
  266.       fprintf (stderr, "** collision not resolved after %d iterations, %d duplicates remain, continuing...\n", 
  267.                !option[FAST] ? option.get_asso_max () : option.get_iterations () ? option.get_iterations () : keyword_list_length (),
  268.                fewest_collisions + total_duplicates);
  269.       fflush (stderr);
  270.     }
  271. }
  272.  
  273. /* Does the hard stuff....
  274.    Initializes the Iteration Number array, and attempts to find a perfect
  275.    function that will hash all the key words without getting any
  276.    duplications.  This is made much easier since we aren't attempting
  277.    to generate *minimum* functions, only perfect ones.
  278.    If we can't generate a perfect function in one pass *and* the user
  279.    hasn't enabled the DUP option, we'll inform the user to try the
  280.    randomization option, use -D, or choose alternative key positions.  
  281.    The alternatives (e.g., back-tracking) are too time-consuming, i.e,
  282.    exponential in the number of keys. */
  283.  
  284. int
  285. Gen_Perf::operator() (void)
  286. {
  287.   T (Trace t ("Gen_Perf::operator()");)
  288. #ifdef __GNUC__
  289.   STORAGE_TYPE buffer[max_hash_value + 1];
  290. #else
  291.   // Note: we don't use new, because that invokes a custom operator new.
  292.   STORAGE_TYPE *buffer
  293.     = (STORAGE_TYPE*) malloc (sizeof(STORAGE_TYPE) * (max_hash_value + 1));
  294.   if (buffer == NULL)
  295.     abort ();
  296. #endif
  297.  
  298.   Bool_Array::init (buffer, max_hash_value + 1);
  299.   
  300.   for (List_Node *curr = head; curr; curr = curr->next)
  301.     {
  302.       hash (curr);
  303.       
  304.       for (List_Node *ptr = head; ptr != curr; ptr = ptr->next)
  305.         if (ptr->hash_value == curr->hash_value)
  306.           {
  307.             change (ptr, curr);
  308.             break;
  309.           }
  310.       num_done++;
  311.     } 
  312.   
  313.   /* Make one final check, just to make sure nothing weird happened.... */
  314.   
  315.   Bool_Array::reset ();
  316.  
  317.   for (curr = head; curr; curr = curr->next)
  318.     if (Bool_Array::find (hash (curr)))
  319.       if (option[DUP]) /* Keep track of this number... */
  320.         total_duplicates++;
  321.       else /* Yow, big problems.  we're outta here! */
  322.         { 
  323.           report_error ("\nInternal error, duplicate value %d:\n"
  324.                         "try options -D or -r, or use new key positions.\n\n", hash (curr));
  325. #ifndef __GNUC__
  326.       free (buffer);
  327. #endif
  328.           return 1;
  329.         }
  330.  
  331.   /* Sorts the key word list by hash value, and then outputs the list.
  332.      The generated hash table code is only output if the early stage of
  333.      processing turned out O.K. */
  334.  
  335.   sort ();
  336.   output ();
  337. #ifndef __GNUC__
  338.   free (buffer);
  339. #endif
  340.   return 0;
  341. }
  342.  
  343. /* Prints out some diagnostics upon completion. */
  344.  
  345. Gen_Perf::~Gen_Perf (void)
  346. {                             
  347.   T (Trace t ("Gen_Perf::~Gen_Perf");)
  348.   if (option[DEBUG])
  349.     {
  350.       fprintf (stderr, "\ndumping occurrence and associated values tables\n");
  351.       
  352.       for (int i = 0; i < ALPHA_SIZE; i++)
  353.         if (occurrences[i])
  354.           fprintf (stderr, "asso_values[%c] = %6d, occurrences[%c] = %6d\n",
  355.                    i, asso_values[i], i, occurrences[i]);
  356.       
  357.       fprintf (stderr, "end table dumping\n");
  358.       
  359.     }
  360. }
  361.  
  362.