]> wimlib.net Git - wimlib/blobdiff - src/decompress_common.c
subtables
[wimlib] / src / decompress_common.c
index f89fc4f35538370bf1651939cd163f60373d9b30..f47b584f75048c845997df7c7b2186bd020ce0b2 100644 (file)
@@ -3,33 +3,36 @@
  *
  * Code for decompression shared among multiple compression formats.
  *
- * Author:  Eric Biggers
- * Year:    2012 - 2014
+ * The following copying information applies to this specific source code file:
  *
- * The author dedicates this file to the public domain.
- * You can do whatever you want with this file.
+ * Written in 2012-2016 by Eric Biggers <ebiggers3@gmail.com>
+ *
+ * To the extent possible under law, the author(s) have dedicated all copyright
+ * and related and neighboring rights to this software to the public domain
+ * worldwide via the Creative Commons Zero 1.0 Universal Public Domain
+ * Dedication (the "CC0").
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the CC0 for more details.
+ *
+ * You should have received a copy of the CC0 along with this software; if not
+ * see <http://creativecommons.org/publicdomain/zero/1.0/>.
  */
 
 #ifdef HAVE_CONFIG_H
 #  include "config.h"
 #endif
 
-#include "wimlib/assert.h"
-#include "wimlib/decompress_common.h"
-
 #include <string.h>
 
-#define USE_WORD_FILL
-
-#ifdef __GNUC__
-#  ifdef __SSE2__
-#    undef USE_WORD_FILL
-#    define USE_SSE2_FILL
-#    include <emmintrin.h>
-#  endif
+#ifdef __SSE2__
+#  include <emmintrin.h>
 #endif
 
-/* Construct a direct mapping entry in the lookup table.  */
+#include "wimlib/decompress_common.h"
+
+/* Construct a direct mapping entry in the decode table.  */
 #define MAKE_DIRECT_ENTRY(symbol, length) ((symbol) | ((length) << 11))
 
 /*
  *   binary tree.
  *
  * @decode_table:
- *     The array in which to create the decoding table.
- *     This must be 16-byte aligned and must have a length of at least
- *     ((2**table_bits) + 2 * num_syms) entries.
+ *     The array in which to create the decoding table.  This must be
+ *     16-byte aligned and must have a length of at least
+ *     ((2**table_bits) + 2 * num_syms) entries.  This is permitted to
+ *     alias @lens, since all information from @lens is consumed before
+*      anything is written to @decode_table.
  *
  * @num_syms:
  *     The number of symbols in the alphabet; also, the length of the
  *     An array of length @num_syms, indexable by symbol, that gives the
  *     length of the codeword, in bits, for that symbol.  The length can
  *     be 0, which means that the symbol does not have a codeword
- *     assigned.
+ *     assigned.  This is permitted to alias @decode_table, since all
+ *     information from @lens is consumed before anything is written to
+ *     @decode_table.
  *
  * @max_codeword_len:
  *     The longest codeword length allowed in the compression format.
  * code.
  */
 int
-make_huffman_decode_table(u16 decode_table[const restrict],
+make_huffman_decode_table(u16 decode_table[const],
                          const unsigned num_syms,
                          const unsigned table_bits,
-                         const u8 lens[const restrict],
+                         const u8 lens[const],
                          const unsigned max_codeword_len)
 {
        const unsigned table_num_entries = 1 << table_bits;
+       unsigned offsets[max_codeword_len + 1];
        unsigned len_counts[max_codeword_len + 1];
        u16 sorted_syms[num_syms];
-       int left;
+       s32 remainder;
        void *decode_table_ptr;
        unsigned sym_idx;
        unsigned codeword_len;
-       unsigned stores_per_loop;
-       unsigned decode_table_pos;
-
-#ifdef USE_WORD_FILL
-       const unsigned entries_per_word = WORDSIZE / sizeof(decode_table[0]);
-#endif
 
-#ifdef USE_SSE2_FILL
-       const unsigned entries_per_xmm = sizeof(__m128i) / sizeof(decode_table[0]);
-#endif
-
-       /* Count how many symbols have each possible codeword length.
-        * Note that a length of 0 indicates the corresponding symbol is not
-        * used in the code and therefore does not have a codeword.  */
+       /* Count how many symbols have each codeword length, including 0.  */
        for (unsigned len = 0; len <= max_codeword_len; len++)
                len_counts[len] = 0;
        for (unsigned sym = 0; sym < num_syms; sym++)
                len_counts[lens[sym]]++;
 
-       /* We can assume all lengths are <= max_codeword_len, but we
-        * cannot assume they form a valid prefix code.  A codeword of
-        * length n should require a proportion of the codespace equaling
-        * (1/2)^n.  The code is valid if and only if the codespace is
-        * exactly filled by the lengths, by this measure.  */
-       left = 1;
+       /* It is already guaranteed that all lengths are <= max_codeword_len,
+        * but it cannot be assumed they form a complete prefix code.  A
+        * codeword of length n should require a proportion of the codespace
+        * equaling (1/2)^n.  The code is complete if and only if, by this
+        * measure, the codespace is exactly filled by the lengths.  */
+       remainder = 1;
        for (unsigned len = 1; len <= max_codeword_len; len++) {
-               left <<= 1;
-               left -= len_counts[len];
-               if (unlikely(left < 0)) {
+               remainder <<= 1;
+               remainder -= len_counts[len];
+               if (unlikely(remainder < 0)) {
                        /* The lengths overflow the codespace; that is, the code
                         * is over-subscribed.  */
                        return -1;
                }
        }
 
-       if (unlikely(left != 0)) {
+       if (unlikely(remainder != 0)) {
                /* The lengths do not fill the codespace; that is, they form an
-                * incomplete set.  */
-               if (left == (1 << max_codeword_len)) {
+                * incomplete code.  */
+               if (remainder == (1 << max_codeword_len)) {
                        /* The code is completely empty.  This is arguably
                         * invalid, but in fact it is valid in LZX and XPRESS,
                         * so we must allow it.  By definition, no symbols can
@@ -195,28 +191,21 @@ make_huffman_decode_table(u16 decode_table[const restrict],
                return -1;
        }
 
-       /* Sort the symbols primarily by length and secondarily by symbol order.
-        */
-       {
-               unsigned offsets[max_codeword_len + 1];
+       /* Sort the symbols primarily by increasing codeword length and
+        * secondarily by increasing symbol value. */
 
-               /* Initialize 'offsets' so that offsets[len] for 1 <= len <=
-                * max_codeword_len is the number of codewords shorter than
-                * 'len' bits.  */
-               offsets[1] = 0;
-               for (unsigned len = 1; len < max_codeword_len; len++)
-                       offsets[len + 1] = offsets[len] + len_counts[len];
+       /* Initialize 'offsets' so that 'offsets[len]' is the number of
+        * codewords shorter than 'len' bits, including length 0. */
+       offsets[0] = 0;
+       for (unsigned len = 0; len < max_codeword_len; len++)
+               offsets[len + 1] = offsets[len] + len_counts[len];
 
-               /* Use the 'offsets' array to sort the symbols.
-                * Note that we do not include symbols that are not used in the
-                * code.  Consequently, fewer than 'num_syms' entries in
-                * 'sorted_syms' may be filled.  */
-               for (unsigned sym = 0; sym < num_syms; sym++)
-                       if (lens[sym] != 0)
-                               sorted_syms[offsets[lens[sym]]++] = sym;
-       }
+       /* Use the 'offsets' array to sort the symbols. */
+       for (unsigned sym = 0; sym < num_syms; sym++)
+               sorted_syms[offsets[lens[sym]]++] = sym;
 
-       /* Fill entries for codewords with length <= table_bits
+       /*
+        * Fill entries for codewords with length <= table_bits
         * --- that is, those short enough for a direct mapping.
         *
         * The table will start with entries for the shortest codeword(s), which
@@ -224,15 +213,17 @@ make_huffman_decode_table(u16 decode_table[const restrict],
         * codeword will decrease.  As an optimization, we may begin filling
         * entries with SSE2 vector accesses (8 entries/store), then change to
         * 'machine_word_t' accesses (2 or 4 entries/store), then change to
-        * 16-bit accesses (1 entry/store).  */
+        * 16-bit accesses (1 entry/store).
+        */
        decode_table_ptr = decode_table;
-       sym_idx = 0;
+       sym_idx = offsets[0];
        codeword_len = 1;
-#ifdef USE_SSE2_FILL
-       /* Fill the entries one 128-bit vector at a time.
-        * This is 8 entries per store.  */
-       stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_xmm;
-       for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
+#ifdef __SSE2__
+       /* Fill entries one 128-bit vector (8 entries) at a time. */
+       for (unsigned stores_per_loop = (1 << (table_bits - codeword_len)) /
+                                   (sizeof(__m128i) / sizeof(decode_table[0]));
+            stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
+       {
                unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
                for (; sym_idx < end_sym_idx; sym_idx++) {
                        /* Note: unlike in the machine_word_t version below, the
@@ -240,30 +231,23 @@ make_huffman_decode_table(u16 decode_table[const restrict],
                         * so using it to access the decode table, which is an
                         * array of unsigned shorts, will not violate strict
                         * aliasing.  */
-                       u16 entry;
-                       __m128i v;
-                       __m128i *p;
-                       unsigned n;
-
-                       entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
-
-                       v = _mm_set1_epi16(entry);
-                       p = (__m128i*)decode_table_ptr;
-                       n = stores_per_loop;
+                       __m128i v = _mm_set1_epi16(
+                                       MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
+                                                         codeword_len));
+                       unsigned n = stores_per_loop;
                        do {
-                               *p++ = v;
+                               *(__m128i *)decode_table_ptr = v;
+                               decode_table_ptr += sizeof(__m128i);
                        } while (--n);
-                       decode_table_ptr = p;
                }
        }
-#endif /* USE_SSE2_FILL */
+#endif /* __SSE2__ */
 
-#ifdef USE_WORD_FILL
-       /* Fill the entries one machine word at a time.
-        * On 32-bit systems this is 2 entries per store, while on 64-bit
-        * systems this is 4 entries per store.  */
-       stores_per_loop = (1 << (table_bits - codeword_len)) / entries_per_word;
-       for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
+       /* Fill entries one word (2 or 4 entries) at a time. */
+       for (unsigned stores_per_loop = (1 << (table_bits - codeword_len)) /
+                                       (WORDBYTES / sizeof(decode_table[0]));
+            stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
+       {
                unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
                for (; sym_idx < end_sym_idx; sym_idx++) {
 
@@ -274,138 +258,109 @@ make_huffman_decode_table(u16 decode_table[const restrict],
                         * gcc 'may_alias' extension.  */
                        typedef machine_word_t _may_alias_attribute aliased_word_t;
 
-                       machine_word_t v;
-                       aliased_word_t *p;
-                       unsigned n;
-
-                       BUILD_BUG_ON(WORDSIZE != 4 && WORDSIZE != 8);
+                       aliased_word_t v;
+                       unsigned n = stores_per_loop;
 
+                       STATIC_ASSERT(WORDBITS == 32 || WORDBITS == 64);
                        v = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
                        v |= v << 16;
-                       v |= v << (WORDSIZE == 8 ? 32 : 0);
-
-                       p = (aliased_word_t *)decode_table_ptr;
-                       n = stores_per_loop;
+                       v |= v << (WORDBITS == 64 ? 32 : 0);
 
                        do {
-                               *p++ = v;
+                               *(aliased_word_t *)decode_table_ptr = v;
+                               decode_table_ptr += sizeof(aliased_word_t);
                        } while (--n);
-                       decode_table_ptr = p;
                }
        }
-#endif /* USE_WORD_FILL */
 
-       /* Fill the entries one 16-bit integer at a time.  */
-       stores_per_loop = (1 << (table_bits - codeword_len));
-       for (; stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1) {
+       /* Fill entries one at a time. */
+       for (unsigned stores_per_loop = (1 << (table_bits - codeword_len));
+            stores_per_loop != 0; codeword_len++, stores_per_loop >>= 1)
+       {
                unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
                for (; sym_idx < end_sym_idx; sym_idx++) {
-                       u16 entry;
-                       u16 *p;
-                       unsigned n;
-
-                       entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx], codeword_len);
-
-                       p = (u16*)decode_table_ptr;
-                       n = stores_per_loop;
-
+                       u16 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
+                                                     codeword_len);
+                       unsigned n = stores_per_loop;
                        do {
-                               *p++ = entry;
+                               *(u16 *)decode_table_ptr = entry;
+                               decode_table_ptr += sizeof(u16);
                        } while (--n);
-
-                       decode_table_ptr = p;
                }
        }
 
-       /* If we've filled in the entire table, we are done.  Otherwise,
-        * there are codewords longer than table_bits for which we must
-        * generate binary trees.  */
-
-       decode_table_pos = (u16*)decode_table_ptr - decode_table;
-       if (decode_table_pos != table_num_entries) {
-               unsigned j;
-               unsigned next_free_tree_slot;
-               unsigned cur_codeword;
-
-               /* First, zero out the remaining entries.  This is
-                * necessary so that these entries appear as
-                * "unallocated" in the next part.  Each of these entries
-                * will eventually be filled with the representation of
-                * the root node of a binary tree.  */
-               j = decode_table_pos;
-               do {
-                       decode_table[j] = 0;
-               } while (++j != table_num_entries);
-
-               /* We allocate child nodes starting at the end of the
-                * direct lookup table.  Note that there should be
-                * 2*num_syms extra entries for this purpose, although
-                * fewer than this may actually be needed.  */
-               next_free_tree_slot = table_num_entries;
-
-               /* Iterate through each codeword with length greater than
-                * 'table_bits', primarily in order of codeword length
-                * and secondarily in order of symbol.  */
-               for (cur_codeword = decode_table_pos << 1;
-                    codeword_len <= max_codeword_len;
-                    codeword_len++, cur_codeword <<= 1)
-               {
-                       unsigned end_sym_idx = sym_idx + len_counts[codeword_len];
-                       for (; sym_idx < end_sym_idx; sym_idx++, cur_codeword++)
-                       {
-                               /* 'sym' is the symbol represented by the
-                                * codeword.  */
-                               unsigned sym = sorted_syms[sym_idx];
+       unsigned codeword = ((u16 *)decode_table_ptr - decode_table) << 1;
+       unsigned cur_subtable_pos = table_num_entries;
+       unsigned cur_subtable_bits = table_bits;
+       unsigned cur_subtable_prefix = -1;
 
-                               unsigned extra_bits = codeword_len - table_bits;
+       /* Fill in the remaining entries if any.  These entries will require
+        * subtables. */
+       while (sym_idx < num_syms) {
 
-                               unsigned node_idx = cur_codeword >> extra_bits;
+               while (len_counts[codeword_len] == 0) {
+                       codeword_len++;
+                       codeword <<= 1;
+               }
 
-                               /* Go through each bit of the current codeword
-                                * beyond the prefix of length @table_bits and
-                                * walk the appropriate binary tree, allocating
-                                * any slots that have not yet been allocated.
-                                *
-                                * Note that the 'pointer' entry to the binary
-                                * tree, which is stored in the direct lookup
-                                * portion of the table, is represented
-                                * identically to other internal (non-leaf)
-                                * nodes of the binary tree; it can be thought
-                                * of as simply the root of the tree.  The
-                                * representation of these internal nodes is
-                                * simply the index of the left child combined
-                                * with the special bits 0xC000 to distingush
-                                * the entry from direct mapping and leaf node
-                                * entries.  */
-                               do {
+               unsigned prefix = codeword >> (codeword_len - table_bits);
+
+               /* Start a new subtable if the first 'table_bits' bits of the
+                * codeword don't match the prefix for the previous subtable, or
+                * if this will be the first subtable. */
+               if (prefix != cur_subtable_prefix) {
+
+                       cur_subtable_prefix = prefix;
+
+                       /* Calculate the subtable length.  If the codeword
+                        * length exceeds 'table_bits' by n, the subtable needs
+                        * at least 2**n entries.  But it may need more; if
+                        * there are fewer than 2**n codewords of length
+                        * 'table_bits + n' remaining, then n will need to be
+                        * incremented to bring in longer codewords until the
+                        * subtable can be filled completely.  Note that it
+                        * always will, eventually, be possible to fill the
+                        * subtable, since the only case where we may have an
+                        * incomplete code is a single codeword of length 1,
+                        * and that never requires any subtables.  */
+                       cur_subtable_bits = codeword_len - table_bits;
+                       remainder = (s32)1 << cur_subtable_bits;
+                       for (;;) {
+                               remainder -= len_counts[table_bits +
+                                                       cur_subtable_bits];
+                               if (remainder <= 0)
+                                       break;
+                               cur_subtable_bits++;
+                               remainder <<= 1;
+                       }
 
-                                       /* At least one bit remains in the
-                                        * codeword, but the current node is an
-                                        * unallocated leaf.  Change it to an
-                                        * internal node.  */
-                                       if (decode_table[node_idx] == 0) {
-                                               decode_table[node_idx] =
-                                                       next_free_tree_slot | 0xC000;
-                                               decode_table[next_free_tree_slot++] = 0;
-                                               decode_table[next_free_tree_slot++] = 0;
-                                       }
+                       /* Create the entry that points from the main table to
+                        * the subtable.  This entry contains the index of the
+                        * start of the subtable and the number of bits with
+                        * which the subtable is indexed (the log base 2 of the
+                        * number of entries it contains).  */
+                       decode_table[cur_subtable_prefix] =
+                               0x8000 | (cur_subtable_bits << 12) |
+                               (cur_subtable_pos - table_num_entries);
+               }
 
-                                       /* Go to the left child if the next bit
-                                        * in the codeword is 0; otherwise go to
-                                        * the right child.  */
-                                       node_idx = decode_table[node_idx] & 0x3FFF;
-                                       --extra_bits;
-                                       node_idx += (cur_codeword >> extra_bits) & 1;
-                               } while (extra_bits != 0);
+               u16 entry = MAKE_DIRECT_ENTRY(sorted_syms[sym_idx],
+                                             codeword_len - table_bits);
+               unsigned n = 1 << (cur_subtable_bits - (codeword_len - table_bits));
 
-                               /* We've traversed the tree using the entire
-                                * codeword, and we're now at the entry where
-                                * the actual symbol will be stored.  This is
-                                * distinguished from internal nodes by not
-                                * having its high two bits set.  */
-                               decode_table[node_idx] = sym;
-                       }
-               }
+               do {
+                       decode_table[cur_subtable_pos++] = entry;
+               } while (--n);
+
+               /* Advance to the next symbol.  This will either increase the
+                * codeword length, or keep the same codeword length but
+                * increase the symbol value.  Note: since we are using
+                * bit-reversed codewords, we don't need to explicitly append
+                * zeroes to the codeword when the codeword length increases. */
+               ++sym_idx;
+               len_counts[codeword_len]--;
+               codeword++;
        }
+
        return 0;
 }