Coverage Report

Created: 2025-11-09 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zstd/lib/compress/zstd_lazy.c
Line
Count
Source
1
/*
2
 * Copyright (c) Meta Platforms, Inc. and affiliates.
3
 * All rights reserved.
4
 *
5
 * This source code is licensed under both the BSD-style license (found in the
6
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
 * in the COPYING file in the root directory of this source tree).
8
 * You may select, at your option, one of the above-listed licenses.
9
 */
10
11
#include "zstd_compress_internal.h"
12
#include "zstd_lazy.h"
13
#include "../common/bits.h" /* ZSTD_countTrailingZeros64 */
14
15
#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \
16
 || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \
17
 || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \
18
 || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR)
19
20
358M
#define kLazySkippingStep 8
21
22
23
/*-*************************************
24
*  Binary Tree search
25
***************************************/
26
27
static
28
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
29
void ZSTD_updateDUBT(ZSTD_MatchState_t* ms,
30
                const BYTE* ip, const BYTE* iend,
31
                U32 mls)
32
80.3M
{
33
80.3M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
34
80.3M
    U32* const hashTable = ms->hashTable;
35
80.3M
    U32  const hashLog = cParams->hashLog;
36
37
80.3M
    U32* const bt = ms->chainTable;
38
80.3M
    U32  const btLog  = cParams->chainLog - 1;
39
80.3M
    U32  const btMask = (1 << btLog) - 1;
40
41
80.3M
    const BYTE* const base = ms->window.base;
42
80.3M
    U32 const target = (U32)(ip - base);
43
80.3M
    U32 idx = ms->nextToUpdate;
44
45
80.3M
    if (idx != target)
46
18.4M
        DEBUGLOG(7, "ZSTD_updateDUBT, from %u to %u (dictLimit:%u)",
47
80.3M
                    idx, target, ms->window.dictLimit);
48
80.3M
    assert(ip + 8 <= iend);   /* condition for ZSTD_hashPtr */
49
80.3M
    (void)iend;
50
51
80.3M
    assert(idx >= ms->window.dictLimit);   /* condition for valid base+idx */
52
315M
    for ( ; idx < target ; idx++) {
53
235M
        size_t const h  = ZSTD_hashPtr(base + idx, hashLog, mls);   /* assumption : ip + 8 <= iend */
54
235M
        U32    const matchIndex = hashTable[h];
55
56
235M
        U32*   const nextCandidatePtr = bt + 2*(idx&btMask);
57
235M
        U32*   const sortMarkPtr  = nextCandidatePtr + 1;
58
59
235M
        DEBUGLOG(8, "ZSTD_updateDUBT: insert %u", idx);
60
235M
        hashTable[h] = idx;   /* Update Hash Table */
61
235M
        *nextCandidatePtr = matchIndex;   /* update BT like a chain */
62
235M
        *sortMarkPtr = ZSTD_DUBT_UNSORTED_MARK;
63
235M
    }
64
80.3M
    ms->nextToUpdate = target;
65
80.3M
}
66
67
68
/** ZSTD_insertDUBT1() :
69
 *  sort one already inserted but unsorted position
70
 *  assumption : curr >= btlow == (curr - btmask)
71
 *  doesn't fail */
72
static
73
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
74
void ZSTD_insertDUBT1(const ZSTD_MatchState_t* ms,
75
                 U32 curr, const BYTE* inputEnd,
76
                 U32 nbCompares, U32 btLow,
77
                 const ZSTD_dictMode_e dictMode)
78
43.5M
{
79
43.5M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
80
43.5M
    U32* const bt = ms->chainTable;
81
43.5M
    U32  const btLog  = cParams->chainLog - 1;
82
43.5M
    U32  const btMask = (1 << btLog) - 1;
83
43.5M
    size_t commonLengthSmaller=0, commonLengthLarger=0;
84
43.5M
    const BYTE* const base = ms->window.base;
85
43.5M
    const BYTE* const dictBase = ms->window.dictBase;
86
43.5M
    const U32 dictLimit = ms->window.dictLimit;
87
43.5M
    const BYTE* const ip = (curr>=dictLimit) ? base + curr : dictBase + curr;
88
43.5M
    const BYTE* const iend = (curr>=dictLimit) ? inputEnd : dictBase + dictLimit;
89
43.5M
    const BYTE* const dictEnd = dictBase + dictLimit;
90
43.5M
    const BYTE* const prefixStart = base + dictLimit;
91
43.5M
    const BYTE* match;
92
43.5M
    U32* smallerPtr = bt + 2*(curr&btMask);
93
43.5M
    U32* largerPtr  = smallerPtr + 1;
94
43.5M
    U32 matchIndex = *smallerPtr;   /* this candidate is unsorted : next sorted candidate is reached through *smallerPtr, while *largerPtr contains previous unsorted candidate (which is already saved and can be overwritten) */
95
43.5M
    U32 dummy32;   /* to be nullified at the end */
96
43.5M
    U32 const windowValid = ms->window.lowLimit;
97
43.5M
    U32 const maxDistance = 1U << cParams->windowLog;
98
43.5M
    U32 const windowLow = (curr - windowValid > maxDistance) ? curr - maxDistance : windowValid;
99
100
101
43.5M
    DEBUGLOG(8, "ZSTD_insertDUBT1(%u) (dictLimit=%u, lowLimit=%u)",
102
43.5M
                curr, dictLimit, windowLow);
103
43.5M
    assert(curr >= btLow);
104
43.5M
    assert(ip < iend);   /* condition for ZSTD_count */
105
106
259M
    for (; nbCompares && (matchIndex > windowLow); --nbCompares) {
107
225M
        U32* const nextPtr = bt + 2*(matchIndex & btMask);
108
225M
        size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger);   /* guaranteed minimum nb of common bytes */
109
225M
        assert(matchIndex < curr);
110
        /* note : all candidates are now supposed sorted,
111
         * but it's still possible to have nextPtr[1] == ZSTD_DUBT_UNSORTED_MARK
112
         * when a real index has the same value as ZSTD_DUBT_UNSORTED_MARK */
113
114
225M
        if ( (dictMode != ZSTD_extDict)
115
43.5M
          || (matchIndex+matchLength >= dictLimit)  /* both in current segment*/
116
213M
          || (curr < dictLimit) /* both in extDict */) {
117
213M
            const BYTE* const mBase = ( (dictMode != ZSTD_extDict)
118
31.8M
                                     || (matchIndex+matchLength >= dictLimit)) ?
119
209M
                                        base : dictBase;
120
213M
            assert( (matchIndex+matchLength >= dictLimit)   /* might be wrong if extDict is incorrectly set to 0 */
121
213M
                 || (curr < dictLimit) );
122
213M
            match = mBase + matchIndex;
123
213M
            matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
124
213M
        } else {
125
11.7M
            match = dictBase + matchIndex;
126
11.7M
            matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
127
11.7M
            if (matchIndex+matchLength >= dictLimit)
128
14.1k
                match = base + matchIndex;   /* preparation for next read of match[matchLength] */
129
11.7M
        }
130
131
225M
        DEBUGLOG(8, "ZSTD_insertDUBT1: comparing %u with %u : found %u common bytes ",
132
225M
                    curr, matchIndex, (U32)matchLength);
133
134
225M
        if (ip+matchLength == iend) {   /* equal : no way to know if inf or sup */
135
145k
            break;   /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
136
145k
        }
137
138
225M
        if (match[matchLength] < ip[matchLength]) {  /* necessarily within buffer */
139
            /* match is smaller than current */
140
94.7M
            *smallerPtr = matchIndex;             /* update smaller idx */
141
94.7M
            commonLengthSmaller = matchLength;    /* all smaller will now have at least this guaranteed common length */
142
94.7M
            if (matchIndex <= btLow) { smallerPtr=&dummy32; break; }   /* beyond tree size, stop searching */
143
90.4M
            DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is smaller : next => %u",
144
90.4M
                        matchIndex, btLow, nextPtr[1]);
145
90.4M
            smallerPtr = nextPtr+1;               /* new "candidate" => larger than match, which was smaller than target */
146
90.4M
            matchIndex = nextPtr[1];              /* new matchIndex, larger than previous and closer to current */
147
130M
        } else {
148
            /* match is larger than current */
149
130M
            *largerPtr = matchIndex;
150
130M
            commonLengthLarger = matchLength;
151
130M
            if (matchIndex <= btLow) { largerPtr=&dummy32; break; }   /* beyond tree size, stop searching */
152
125M
            DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is larger => %u",
153
125M
                        matchIndex, btLow, nextPtr[0]);
154
125M
            largerPtr = nextPtr;
155
125M
            matchIndex = nextPtr[0];
156
125M
    }   }
157
158
43.5M
    *smallerPtr = *largerPtr = 0;
159
43.5M
}
160
161
162
static
163
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
164
size_t ZSTD_DUBT_findBetterDictMatch (
165
        const ZSTD_MatchState_t* ms,
166
        const BYTE* const ip, const BYTE* const iend,
167
        size_t* offsetPtr,
168
        size_t bestLength,
169
        U32 nbCompares,
170
        U32 const mls,
171
        const ZSTD_dictMode_e dictMode)
172
1.10M
{
173
1.10M
    const ZSTD_MatchState_t * const dms = ms->dictMatchState;
174
1.10M
    const ZSTD_compressionParameters* const dmsCParams = &dms->cParams;
175
1.10M
    const U32 * const dictHashTable = dms->hashTable;
176
1.10M
    U32         const hashLog = dmsCParams->hashLog;
177
1.10M
    size_t      const h  = ZSTD_hashPtr(ip, hashLog, mls);
178
1.10M
    U32               dictMatchIndex = dictHashTable[h];
179
180
1.10M
    const BYTE* const base = ms->window.base;
181
1.10M
    const BYTE* const prefixStart = base + ms->window.dictLimit;
182
1.10M
    U32         const curr = (U32)(ip-base);
183
1.10M
    const BYTE* const dictBase = dms->window.base;
184
1.10M
    const BYTE* const dictEnd = dms->window.nextSrc;
185
1.10M
    U32         const dictHighLimit = (U32)(dms->window.nextSrc - dms->window.base);
186
1.10M
    U32         const dictLowLimit = dms->window.lowLimit;
187
1.10M
    U32         const dictIndexDelta = ms->window.lowLimit - dictHighLimit;
188
189
1.10M
    U32*        const dictBt = dms->chainTable;
190
1.10M
    U32         const btLog  = dmsCParams->chainLog - 1;
191
1.10M
    U32         const btMask = (1 << btLog) - 1;
192
1.10M
    U32         const btLow = (btMask >= dictHighLimit - dictLowLimit) ? dictLowLimit : dictHighLimit - btMask;
193
194
1.10M
    size_t commonLengthSmaller=0, commonLengthLarger=0;
195
196
1.10M
    (void)dictMode;
197
1.10M
    assert(dictMode == ZSTD_dictMatchState);
198
199
2.30M
    for (; nbCompares && (dictMatchIndex > dictLowLimit); --nbCompares) {
200
1.81M
        U32* const nextPtr = dictBt + 2*(dictMatchIndex & btMask);
201
1.81M
        size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger);   /* guaranteed minimum nb of common bytes */
202
1.81M
        const BYTE* match = dictBase + dictMatchIndex;
203
1.81M
        matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
204
1.81M
        if (dictMatchIndex+matchLength >= dictHighLimit)
205
3.90k
            match = base + dictMatchIndex + dictIndexDelta;   /* to prepare for next usage of match[matchLength] */
206
207
1.81M
        if (matchLength > bestLength) {
208
138k
            U32 matchIndex = dictMatchIndex + dictIndexDelta;
209
138k
            if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(curr-matchIndex+1) - ZSTD_highbit32((U32)offsetPtr[0]+1)) ) {
210
128k
                DEBUGLOG(9, "ZSTD_DUBT_findBetterDictMatch(%u) : found better match length %u -> %u and offsetCode %u -> %u (dictMatchIndex %u, matchIndex %u)",
211
128k
                    curr, (U32)bestLength, (U32)matchLength, (U32)*offsetPtr, OFFSET_TO_OFFBASE(curr - matchIndex), dictMatchIndex, matchIndex);
212
128k
                bestLength = matchLength, *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
213
128k
            }
214
138k
            if (ip+matchLength == iend) {   /* reached end of input : ip[matchLength] is not valid, no way to know if it's larger or smaller than match */
215
3.98k
                break;   /* drop, to guarantee consistency (miss a little bit of compression) */
216
3.98k
            }
217
138k
        }
218
219
1.81M
        if (match[matchLength] < ip[matchLength]) {
220
914k
            if (dictMatchIndex <= btLow) { break; }   /* beyond tree size, stop the search */
221
605k
            commonLengthSmaller = matchLength;    /* all smaller will now have at least this guaranteed common length */
222
605k
            dictMatchIndex = nextPtr[1];              /* new matchIndex larger than previous (closer to current) */
223
899k
        } else {
224
            /* match is larger than current */
225
899k
            if (dictMatchIndex <= btLow) { break; }   /* beyond tree size, stop the search */
226
595k
            commonLengthLarger = matchLength;
227
595k
            dictMatchIndex = nextPtr[0];
228
595k
        }
229
1.81M
    }
230
231
1.10M
    if (bestLength >= MINMATCH) {
232
301k
        U32 const mIndex = curr - (U32)OFFBASE_TO_OFFSET(*offsetPtr); (void)mIndex;
233
301k
        DEBUGLOG(8, "ZSTD_DUBT_findBetterDictMatch(%u) : found match of length %u and offsetCode %u (pos %u)",
234
301k
                    curr, (U32)bestLength, (U32)*offsetPtr, mIndex);
235
301k
    }
236
1.10M
    return bestLength;
237
238
1.10M
}
239
240
241
static
242
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
243
size_t ZSTD_DUBT_findBestMatch(ZSTD_MatchState_t* ms,
244
                        const BYTE* const ip, const BYTE* const iend,
245
                        size_t* offBasePtr,
246
                        U32 const mls,
247
                        const ZSTD_dictMode_e dictMode)
248
80.3M
{
249
80.3M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
250
80.3M
    U32*   const hashTable = ms->hashTable;
251
80.3M
    U32    const hashLog = cParams->hashLog;
252
80.3M
    size_t const h  = ZSTD_hashPtr(ip, hashLog, mls);
253
80.3M
    U32          matchIndex  = hashTable[h];
254
255
80.3M
    const BYTE* const base = ms->window.base;
256
80.3M
    U32    const curr = (U32)(ip-base);
257
80.3M
    U32    const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);
258
259
80.3M
    U32*   const bt = ms->chainTable;
260
80.3M
    U32    const btLog  = cParams->chainLog - 1;
261
80.3M
    U32    const btMask = (1 << btLog) - 1;
262
80.3M
    U32    const btLow = (btMask >= curr) ? 0 : curr - btMask;
263
80.3M
    U32    const unsortLimit = MAX(btLow, windowLow);
264
265
80.3M
    U32*         nextCandidate = bt + 2*(matchIndex&btMask);
266
80.3M
    U32*         unsortedMark = bt + 2*(matchIndex&btMask) + 1;
267
80.3M
    U32          nbCompares = 1U << cParams->searchLog;
268
80.3M
    U32          nbCandidates = nbCompares;
269
80.3M
    U32          previousCandidate = 0;
270
271
80.3M
    DEBUGLOG(7, "ZSTD_DUBT_findBestMatch (%u) ", curr);
272
80.3M
    assert(ip <= iend-8);   /* required for h calculation */
273
80.4M
    assert(dictMode != ZSTD_dedicatedDictSearch);
274
275
    /* reach end of unsorted candidates list */
276
124M
    while ( (matchIndex > unsortLimit)
277
75.1M
         && (*unsortedMark == ZSTD_DUBT_UNSORTED_MARK)
278
45.2M
         && (nbCandidates > 1) ) {
279
43.5M
        DEBUGLOG(8, "ZSTD_DUBT_findBestMatch: candidate %u is unsorted",
280
43.5M
                    matchIndex);
281
43.5M
        *unsortedMark = previousCandidate;  /* the unsortedMark becomes a reversed chain, to move up back to original position */
282
43.5M
        previousCandidate = matchIndex;
283
43.5M
        matchIndex = *nextCandidate;
284
43.5M
        nextCandidate = bt + 2*(matchIndex&btMask);
285
43.5M
        unsortedMark = bt + 2*(matchIndex&btMask) + 1;
286
43.5M
        nbCandidates --;
287
43.5M
    }
288
289
    /* nullify last candidate if it's still unsorted
290
     * simplification, detrimental to compression ratio, beneficial for speed */
291
80.4M
    if ( (matchIndex > unsortLimit)
292
31.6M
      && (*unsortedMark==ZSTD_DUBT_UNSORTED_MARK) ) {
293
1.64M
        DEBUGLOG(7, "ZSTD_DUBT_findBestMatch: nullify last unsorted candidate %u",
294
1.64M
                    matchIndex);
295
1.64M
        *nextCandidate = *unsortedMark = 0;
296
1.64M
    }
297
298
    /* batch sort stacked candidates */
299
80.4M
    matchIndex = previousCandidate;
300
124M
    while (matchIndex) {  /* will end on matchIndex == 0 */
301
43.5M
        U32* const nextCandidateIdxPtr = bt + 2*(matchIndex&btMask) + 1;
302
43.5M
        U32 const nextCandidateIdx = *nextCandidateIdxPtr;
303
43.5M
        ZSTD_insertDUBT1(ms, matchIndex, iend,
304
43.5M
                         nbCandidates, unsortLimit, dictMode);
305
43.5M
        matchIndex = nextCandidateIdx;
306
43.5M
        nbCandidates++;
307
43.5M
    }
308
309
    /* find longest match */
310
80.4M
    {   size_t commonLengthSmaller = 0, commonLengthLarger = 0;
311
80.4M
        const BYTE* const dictBase = ms->window.dictBase;
312
80.4M
        const U32 dictLimit = ms->window.dictLimit;
313
80.4M
        const BYTE* const dictEnd = dictBase + dictLimit;
314
80.4M
        const BYTE* const prefixStart = base + dictLimit;
315
80.4M
        U32* smallerPtr = bt + 2*(curr&btMask);
316
80.4M
        U32* largerPtr  = bt + 2*(curr&btMask) + 1;
317
80.4M
        U32 matchEndIdx = curr + 8 + 1;
318
80.4M
        U32 dummy32;   /* to be nullified at the end */
319
80.4M
        size_t bestLength = 0;
320
321
80.4M
        matchIndex  = hashTable[h];
322
80.4M
        hashTable[h] = curr;   /* Update Hash Table */
323
324
184M
        for (; nbCompares && (matchIndex > windowLow); --nbCompares) {
325
131M
            U32* const nextPtr = bt + 2*(matchIndex & btMask);
326
131M
            size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger);   /* guaranteed minimum nb of common bytes */
327
131M
            const BYTE* match;
328
329
131M
            if ((dictMode != ZSTD_extDict) || (matchIndex+matchLength >= dictLimit)) {
330
128M
                match = base + matchIndex;
331
128M
                matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
332
128M
            } else {
333
2.69M
                match = dictBase + matchIndex;
334
2.69M
                matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
335
2.69M
                if (matchIndex+matchLength >= dictLimit)
336
7.23k
                    match = base + matchIndex;   /* to prepare for next usage of match[matchLength] */
337
2.69M
            }
338
339
131M
            if (matchLength > bestLength) {
340
33.8M
                if (matchLength > matchEndIdx - matchIndex)
341
653k
                    matchEndIdx = matchIndex + (U32)matchLength;
342
33.8M
                if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(curr - matchIndex + 1) - ZSTD_highbit32((U32)*offBasePtr)) )
343
33.1M
                    bestLength = matchLength, *offBasePtr = OFFSET_TO_OFFBASE(curr - matchIndex);
344
33.8M
                if (ip+matchLength == iend) {   /* equal : no way to know if inf or sup */
345
216k
                    if (dictMode == ZSTD_dictMatchState) {
346
6.62k
                        nbCompares = 0; /* in addition to avoiding checking any
347
                                         * further in this loop, make sure we
348
                                         * skip checking in the dictionary. */
349
6.62k
                    }
350
216k
                    break;   /* drop, to guarantee consistency (miss a little bit of compression) */
351
216k
                }
352
33.8M
            }
353
354
130M
            if (match[matchLength] < ip[matchLength]) {
355
                /* match is smaller than current */
356
63.4M
                *smallerPtr = matchIndex;             /* update smaller idx */
357
63.4M
                commonLengthSmaller = matchLength;    /* all smaller will now have at least this guaranteed common length */
358
63.4M
                if (matchIndex <= btLow) { smallerPtr=&dummy32; break; }   /* beyond tree size, stop the search */
359
49.8M
                smallerPtr = nextPtr+1;               /* new "smaller" => larger of match */
360
49.8M
                matchIndex = nextPtr[1];              /* new matchIndex larger than previous (closer to current) */
361
67.5M
            } else {
362
                /* match is larger than current */
363
67.5M
                *largerPtr = matchIndex;
364
67.5M
                commonLengthLarger = matchLength;
365
67.5M
                if (matchIndex <= btLow) { largerPtr=&dummy32; break; }   /* beyond tree size, stop the search */
366
54.3M
                largerPtr = nextPtr;
367
54.3M
                matchIndex = nextPtr[0];
368
54.3M
        }   }
369
370
80.4M
        *smallerPtr = *largerPtr = 0;
371
372
80.4M
        assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
373
80.4M
        if (dictMode == ZSTD_dictMatchState && nbCompares) {
374
1.10M
            bestLength = ZSTD_DUBT_findBetterDictMatch(
375
1.10M
                    ms, ip, iend,
376
1.10M
                    offBasePtr, bestLength, nbCompares,
377
1.10M
                    mls, dictMode);
378
1.10M
        }
379
380
80.4M
        assert(matchEndIdx > curr+8); /* ensure nextToUpdate is increased */
381
80.4M
        ms->nextToUpdate = matchEndIdx - 8;   /* skip repetitive patterns */
382
80.4M
        if (bestLength >= MINMATCH) {
383
18.8M
            U32 const mIndex = curr - (U32)OFFBASE_TO_OFFSET(*offBasePtr); (void)mIndex;
384
18.8M
            DEBUGLOG(8, "ZSTD_DUBT_findBestMatch(%u) : found match of length %u and offsetCode %u (pos %u)",
385
18.8M
                        curr, (U32)bestLength, (U32)*offBasePtr, mIndex);
386
18.8M
        }
387
80.4M
        return bestLength;
388
80.4M
    }
389
80.4M
}
390
391
392
/** ZSTD_BtFindBestMatch() : Tree updater, providing best match */
393
FORCE_INLINE_TEMPLATE
394
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
395
size_t ZSTD_BtFindBestMatch( ZSTD_MatchState_t* ms,
396
                const BYTE* const ip, const BYTE* const iLimit,
397
                      size_t* offBasePtr,
398
                const U32 mls /* template */,
399
                const ZSTD_dictMode_e dictMode)
400
81.1M
{
401
81.1M
    DEBUGLOG(7, "ZSTD_BtFindBestMatch");
402
81.1M
    if (ip < ms->window.base + ms->nextToUpdate) return 0;   /* skipped area */
403
80.3M
    ZSTD_updateDUBT(ms, ip, iLimit, mls);
404
80.3M
    return ZSTD_DUBT_findBestMatch(ms, ip, iLimit, offBasePtr, mls, dictMode);
405
81.1M
}
406
407
/***********************************
408
* Dedicated dict search
409
***********************************/
410
411
void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_MatchState_t* ms, const BYTE* const ip)
412
7.89k
{
413
7.89k
    const BYTE* const base = ms->window.base;
414
7.89k
    U32 const target = (U32)(ip - base);
415
7.89k
    U32* const hashTable = ms->hashTable;
416
7.89k
    U32* const chainTable = ms->chainTable;
417
7.89k
    U32 const chainSize = 1 << ms->cParams.chainLog;
418
7.89k
    U32 idx = ms->nextToUpdate;
419
7.89k
    U32 const minChain = chainSize < target - idx ? target - chainSize : idx;
420
7.89k
    U32 const bucketSize = 1 << ZSTD_LAZY_DDSS_BUCKET_LOG;
421
7.89k
    U32 const cacheSize = bucketSize - 1;
422
7.89k
    U32 const chainAttempts = (1 << ms->cParams.searchLog) - cacheSize;
423
7.89k
    U32 const chainLimit = chainAttempts > 255 ? 255 : chainAttempts;
424
425
    /* We know the hashtable is oversized by a factor of `bucketSize`.
426
     * We are going to temporarily pretend `bucketSize == 1`, keeping only a
427
     * single entry. We will use the rest of the space to construct a temporary
428
     * chaintable.
429
     */
430
7.89k
    U32 const hashLog = ms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG;
431
7.89k
    U32* const tmpHashTable = hashTable;
432
7.89k
    U32* const tmpChainTable = hashTable + ((size_t)1 << hashLog);
433
7.89k
    U32 const tmpChainSize = (U32)((1 << ZSTD_LAZY_DDSS_BUCKET_LOG) - 1) << hashLog;
434
7.89k
    U32 const tmpMinChain = tmpChainSize < target ? target - tmpChainSize : idx;
435
7.89k
    U32 hashIdx;
436
437
7.89k
    assert(ms->cParams.chainLog <= 24);
438
7.89k
    assert(ms->cParams.hashLog > ms->cParams.chainLog);
439
7.89k
    assert(idx != 0);
440
7.89k
    assert(tmpMinChain <= minChain);
441
442
    /* fill conventional hash table and conventional chain table */
443
9.60M
    for ( ; idx < target; idx++) {
444
9.59M
        U32 const h = (U32)ZSTD_hashPtr(base + idx, hashLog, ms->cParams.minMatch);
445
9.59M
        if (idx >= tmpMinChain) {
446
3.82M
            tmpChainTable[idx - tmpMinChain] = hashTable[h];
447
3.82M
        }
448
9.59M
        tmpHashTable[h] = idx;
449
9.59M
    }
450
451
    /* sort chains into ddss chain table */
452
7.89k
    {
453
7.89k
        U32 chainPos = 0;
454
2.87M
        for (hashIdx = 0; hashIdx < (1U << hashLog); hashIdx++) {
455
2.86M
            U32 count;
456
2.86M
            U32 countBeyondMinChain = 0;
457
2.86M
            U32 i = tmpHashTable[hashIdx];
458
5.06M
            for (count = 0; i >= tmpMinChain && count < cacheSize; count++) {
459
                /* skip through the chain to the first position that won't be
460
                 * in the hash cache bucket */
461
2.20M
                if (i < minChain) {
462
1.04M
                    countBeyondMinChain++;
463
1.04M
                }
464
2.20M
                i = tmpChainTable[i - tmpMinChain];
465
2.20M
            }
466
2.86M
            if (count == cacheSize) {
467
987k
                for (count = 0; count < chainLimit;) {
468
968k
                    if (i < minChain) {
469
576k
                        if (!i || ++countBeyondMinChain > cacheSize) {
470
                            /* only allow pulling `cacheSize` number of entries
471
                             * into the cache or chainTable beyond `minChain`,
472
                             * to replace the entries pulled out of the
473
                             * chainTable into the cache. This lets us reach
474
                             * back further without increasing the total number
475
                             * of entries in the chainTable, guaranteeing the
476
                             * DDSS chain table will fit into the space
477
                             * allocated for the regular one. */
478
315k
                            break;
479
315k
                        }
480
576k
                    }
481
652k
                    chainTable[chainPos++] = i;
482
652k
                    count++;
483
652k
                    if (i < tmpMinChain) {
484
72.3k
                        break;
485
72.3k
                    }
486
580k
                    i = tmpChainTable[i - tmpMinChain];
487
580k
                }
488
2.45M
            } else {
489
2.45M
                count = 0;
490
2.45M
            }
491
2.86M
            if (count) {
492
216k
                tmpHashTable[hashIdx] = ((chainPos - count) << 8) + count;
493
2.64M
            } else {
494
2.64M
                tmpHashTable[hashIdx] = 0;
495
2.64M
            }
496
2.86M
        }
497
7.89k
        assert(chainPos <= chainSize); /* I believe this is guaranteed... */
498
7.89k
    }
499
500
    /* move chain pointers into the last entry of each hash bucket */
501
2.87M
    for (hashIdx = (1 << hashLog); hashIdx; ) {
502
2.86M
        U32 const bucketIdx = --hashIdx << ZSTD_LAZY_DDSS_BUCKET_LOG;
503
2.86M
        U32 const chainPackedPointer = tmpHashTable[hashIdx];
504
2.86M
        U32 i;
505
11.4M
        for (i = 0; i < cacheSize; i++) {
506
8.59M
            hashTable[bucketIdx + i] = 0;
507
8.59M
        }
508
2.86M
        hashTable[bucketIdx + bucketSize - 1] = chainPackedPointer;
509
2.86M
    }
510
511
    /* fill the buckets of the hash table */
512
9.60M
    for (idx = ms->nextToUpdate; idx < target; idx++) {
513
9.59M
        U32 const h = (U32)ZSTD_hashPtr(base + idx, hashLog, ms->cParams.minMatch)
514
9.59M
                   << ZSTD_LAZY_DDSS_BUCKET_LOG;
515
9.59M
        U32 i;
516
        /* Shift hash cache down 1. */
517
28.7M
        for (i = cacheSize - 1; i; i--)
518
19.1M
            hashTable[h + i] = hashTable[h + i - 1];
519
9.59M
        hashTable[h] = idx;
520
9.59M
    }
521
522
7.89k
    ms->nextToUpdate = target;
523
7.89k
}
524
525
/* Returns the longest match length found in the dedicated dict search structure.
526
 * If none are longer than the argument ml, then ml will be returned.
527
 */
528
FORCE_INLINE_TEMPLATE
529
size_t ZSTD_dedicatedDictSearch_lazy_search(size_t* offsetPtr, size_t ml, U32 nbAttempts,
530
                                            const ZSTD_MatchState_t* const dms,
531
                                            const BYTE* const ip, const BYTE* const iLimit,
532
                                            const BYTE* const prefixStart, const U32 curr,
533
7.35M
                                            const U32 dictLimit, const size_t ddsIdx) {
534
7.35M
    const U32 ddsLowestIndex  = dms->window.dictLimit;
535
7.35M
    const BYTE* const ddsBase = dms->window.base;
536
7.35M
    const BYTE* const ddsEnd  = dms->window.nextSrc;
537
7.35M
    const U32 ddsSize         = (U32)(ddsEnd - ddsBase);
538
7.35M
    const U32 ddsIndexDelta   = dictLimit - ddsSize;
539
7.35M
    const U32 bucketSize      = (1 << ZSTD_LAZY_DDSS_BUCKET_LOG);
540
7.35M
    const U32 bucketLimit     = nbAttempts < bucketSize - 1 ? nbAttempts : bucketSize - 1;
541
7.35M
    U32 ddsAttempt;
542
7.35M
    U32 matchIndex;
543
544
29.4M
    for (ddsAttempt = 0; ddsAttempt < bucketSize - 1; ddsAttempt++) {
545
22.0M
        PREFETCH_L1(ddsBase + dms->hashTable[ddsIdx + ddsAttempt]);
546
22.0M
    }
547
548
7.35M
    {
549
7.35M
        U32 const chainPackedPointer = dms->hashTable[ddsIdx + bucketSize - 1];
550
7.35M
        U32 const chainIndex = chainPackedPointer >> 8;
551
552
7.35M
        PREFETCH_L1(&dms->chainTable[chainIndex]);
553
7.35M
    }
554
555
23.1M
    for (ddsAttempt = 0; ddsAttempt < bucketLimit; ddsAttempt++) {
556
17.8M
        size_t currentMl=0;
557
17.8M
        const BYTE* match;
558
17.8M
        matchIndex = dms->hashTable[ddsIdx + ddsAttempt];
559
17.8M
        match = ddsBase + matchIndex;
560
561
17.8M
        if (!matchIndex) {
562
2.05M
            return ml;
563
2.05M
        }
564
565
        /* guaranteed by table construction */
566
15.8M
        (void)ddsLowestIndex;
567
15.8M
        assert(matchIndex >= ddsLowestIndex);
568
15.8M
        assert(match+4 <= ddsEnd);
569
15.8M
        if (MEM_read32(match) == MEM_read32(ip)) {
570
            /* assumption : matchIndex <= dictLimit-4 (by table construction) */
571
1.42M
            currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, ddsEnd, prefixStart) + 4;
572
1.42M
        }
573
574
        /* save best solution */
575
15.8M
        if (currentMl > ml) {
576
442k
            ml = currentMl;
577
442k
            *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + ddsIndexDelta));
578
442k
            if (ip+currentMl == iLimit) {
579
                /* best possible, avoids read overflow on next attempt */
580
20.2k
                return ml;
581
20.2k
            }
582
442k
        }
583
15.8M
    }
584
585
5.28M
    {
586
5.28M
        U32 const chainPackedPointer = dms->hashTable[ddsIdx + bucketSize - 1];
587
5.28M
        U32 chainIndex = chainPackedPointer >> 8;
588
5.28M
        U32 const chainLength = chainPackedPointer & 0xFF;
589
5.28M
        U32 const chainAttempts = nbAttempts - ddsAttempt;
590
5.28M
        U32 const chainLimit = chainAttempts > chainLength ? chainLength : chainAttempts;
591
5.28M
        U32 chainAttempt;
592
593
10.5M
        for (chainAttempt = 0 ; chainAttempt < chainLimit; chainAttempt++) {
594
5.26M
            PREFETCH_L1(ddsBase + dms->chainTable[chainIndex + chainAttempt]);
595
5.26M
        }
596
597
10.4M
        for (chainAttempt = 0 ; chainAttempt < chainLimit; chainAttempt++, chainIndex++) {
598
5.20M
            size_t currentMl=0;
599
5.20M
            const BYTE* match;
600
5.20M
            matchIndex = dms->chainTable[chainIndex];
601
5.20M
            match = ddsBase + matchIndex;
602
603
            /* guaranteed by table construction */
604
5.20M
            assert(matchIndex >= ddsLowestIndex);
605
5.20M
            assert(match+4 <= ddsEnd);
606
5.20M
            if (MEM_read32(match) == MEM_read32(ip)) {
607
                /* assumption : matchIndex <= dictLimit-4 (by table construction) */
608
2.01M
                currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, ddsEnd, prefixStart) + 4;
609
2.01M
            }
610
611
            /* save best solution */
612
5.20M
            if (currentMl > ml) {
613
138k
                ml = currentMl;
614
138k
                *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + ddsIndexDelta));
615
138k
                if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
616
138k
            }
617
5.20M
        }
618
5.28M
    }
619
5.28M
    return ml;
620
5.28M
}
621
622
623
/* *********************************
624
*  Hash Chain
625
***********************************/
626
1.10G
#define NEXT_IN_CHAIN(d, mask)   chainTable[(d) & (mask)]
627
628
/* Update chains up to ip (excluded)
629
   Assumption : always within prefix (i.e. not within extDict) */
630
FORCE_INLINE_TEMPLATE
631
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
632
U32 ZSTD_insertAndFindFirstIndex_internal(
633
                        ZSTD_MatchState_t* ms,
634
                        const ZSTD_compressionParameters* const cParams,
635
                        const BYTE* ip, U32 const mls, U32 const lazySkipping)
636
143M
{
637
143M
    U32* const hashTable  = ms->hashTable;
638
143M
    const U32 hashLog = cParams->hashLog;
639
143M
    U32* const chainTable = ms->chainTable;
640
143M
    const U32 chainMask = (1 << cParams->chainLog) - 1;
641
143M
    const BYTE* const base = ms->window.base;
642
143M
    const U32 target = (U32)(ip - base);
643
143M
    U32 idx = ms->nextToUpdate;
644
645
603M
    while(idx < target) { /* catch up */
646
461M
        size_t const h = ZSTD_hashPtr(base+idx, hashLog, mls);
647
461M
        NEXT_IN_CHAIN(idx, chainMask) = hashTable[h];
648
461M
        hashTable[h] = idx;
649
461M
        idx++;
650
        /* Stop inserting every position when in the lazy skipping mode. */
651
461M
        if (lazySkipping)
652
1.76M
            break;
653
461M
    }
654
655
143M
    ms->nextToUpdate = target;
656
143M
    return hashTable[ZSTD_hashPtr(ip, hashLog, mls)];
657
143M
}
658
659
28.6k
U32 ZSTD_insertAndFindFirstIndex(ZSTD_MatchState_t* ms, const BYTE* ip) {
660
28.6k
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
661
28.6k
    return ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, ms->cParams.minMatch, /* lazySkipping*/ 0);
662
28.6k
}
663
664
/* inlining is important to hardwire a hot branch (template emulation) */
665
FORCE_INLINE_TEMPLATE
666
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
667
size_t ZSTD_HcFindBestMatch(
668
                        ZSTD_MatchState_t* ms,
669
                        const BYTE* const ip, const BYTE* const iLimit,
670
                        size_t* offsetPtr,
671
                        const U32 mls, const ZSTD_dictMode_e dictMode)
672
142M
{
673
142M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
674
142M
    U32* const chainTable = ms->chainTable;
675
142M
    const U32 chainSize = (1 << cParams->chainLog);
676
142M
    const U32 chainMask = chainSize-1;
677
142M
    const BYTE* const base = ms->window.base;
678
142M
    const BYTE* const dictBase = ms->window.dictBase;
679
142M
    const U32 dictLimit = ms->window.dictLimit;
680
142M
    const BYTE* const prefixStart = base + dictLimit;
681
142M
    const BYTE* const dictEnd = dictBase + dictLimit;
682
142M
    const U32 curr = (U32)(ip-base);
683
142M
    const U32 maxDistance = 1U << cParams->windowLog;
684
142M
    const U32 lowestValid = ms->window.lowLimit;
685
142M
    const U32 withinMaxDistance = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
686
142M
    const U32 isDictionary = (ms->loadedDictEnd != 0);
687
142M
    const U32 lowLimit = isDictionary ? lowestValid : withinMaxDistance;
688
142M
    const U32 minChain = curr > chainSize ? curr - chainSize : 0;
689
142M
    U32 nbAttempts = 1U << cParams->searchLog;
690
142M
    size_t ml=4-1;
691
692
142M
    const ZSTD_MatchState_t* const dms = ms->dictMatchState;
693
142M
    const U32 ddsHashLog = dictMode == ZSTD_dedicatedDictSearch
694
142M
                         ? dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG : 0;
695
142M
    const size_t ddsIdx = dictMode == ZSTD_dedicatedDictSearch
696
142M
                        ? ZSTD_hashPtr(ip, ddsHashLog, mls) << ZSTD_LAZY_DDSS_BUCKET_LOG : 0;
697
698
142M
    U32 matchIndex;
699
700
142M
    if (dictMode == ZSTD_dedicatedDictSearch) {
701
2.22M
        const U32* entry = &dms->hashTable[ddsIdx];
702
2.22M
        PREFETCH_L1(entry);
703
2.22M
    }
704
705
    /* HC4 match finder */
706
142M
    matchIndex = ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, mls, ms->lazySkipping);
707
708
787M
    for ( ; (matchIndex>=lowLimit) & (nbAttempts>0) ; nbAttempts--) {
709
714M
        size_t currentMl=0;
710
714M
        if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
711
697M
            const BYTE* const match = base + matchIndex;
712
697M
            assert(matchIndex >= dictLimit);   /* ensures this is true if dictMode != ZSTD_extDict */
713
            /* read 4B starting from (match + ml + 1 - sizeof(U32)) */
714
697M
            if (MEM_read32(match + ml - 3) == MEM_read32(ip + ml - 3))   /* potentially better */
715
39.3M
                currentMl = ZSTD_count(ip, match, iLimit);
716
697M
        } else {
717
16.2M
            const BYTE* const match = dictBase + matchIndex;
718
16.2M
            assert(match+4 <= dictEnd);
719
16.2M
            if (MEM_read32(match) == MEM_read32(ip))   /* assumption : matchIndex <= dictLimit-4 (by table construction) */
720
3.26M
                currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
721
16.2M
        }
722
723
        /* save best solution */
724
714M
        if (currentMl > ml) {
725
35.8M
            ml = currentMl;
726
35.8M
            *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
727
35.8M
            if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
728
35.8M
        }
729
730
713M
        if (matchIndex <= minChain) break;
731
644M
        matchIndex = NEXT_IN_CHAIN(matchIndex, chainMask);
732
644M
    }
733
734
142M
    assert(nbAttempts <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
735
143M
    if (dictMode == ZSTD_dedicatedDictSearch) {
736
2.22M
        ml = ZSTD_dedicatedDictSearch_lazy_search(offsetPtr, ml, nbAttempts, dms,
737
2.22M
                                                  ip, iLimit, prefixStart, curr, dictLimit, ddsIdx);
738
140M
    } else if (dictMode == ZSTD_dictMatchState) {
739
2.51M
        const U32* const dmsChainTable = dms->chainTable;
740
2.51M
        const U32 dmsChainSize         = (1 << dms->cParams.chainLog);
741
2.51M
        const U32 dmsChainMask         = dmsChainSize - 1;
742
2.51M
        const U32 dmsLowestIndex       = dms->window.dictLimit;
743
2.51M
        const BYTE* const dmsBase      = dms->window.base;
744
2.51M
        const BYTE* const dmsEnd       = dms->window.nextSrc;
745
2.51M
        const U32 dmsSize              = (U32)(dmsEnd - dmsBase);
746
2.51M
        const U32 dmsIndexDelta        = dictLimit - dmsSize;
747
2.51M
        const U32 dmsMinChain = dmsSize > dmsChainSize ? dmsSize - dmsChainSize : 0;
748
749
2.51M
        matchIndex = dms->hashTable[ZSTD_hashPtr(ip, dms->cParams.hashLog, mls)];
750
751
7.90M
        for ( ; (matchIndex>=dmsLowestIndex) & (nbAttempts>0) ; nbAttempts--) {
752
6.65M
            size_t currentMl=0;
753
6.65M
            const BYTE* const match = dmsBase + matchIndex;
754
6.65M
            assert(match+4 <= dmsEnd);
755
6.65M
            if (MEM_read32(match) == MEM_read32(ip))   /* assumption : matchIndex <= dictLimit-4 (by table construction) */
756
1.51M
                currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
757
758
            /* save best solution */
759
6.65M
            if (currentMl > ml) {
760
177k
                ml = currentMl;
761
177k
                assert(curr > matchIndex + dmsIndexDelta);
762
177k
                *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + dmsIndexDelta));
763
177k
                if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
764
177k
            }
765
766
6.64M
            if (matchIndex <= dmsMinChain) break;
767
768
5.38M
            matchIndex = dmsChainTable[matchIndex & dmsChainMask];
769
5.38M
        }
770
2.51M
    }
771
772
143M
    return ml;
773
143M
}
774
775
/* *********************************
776
* (SIMD) Row-based matchfinder
777
***********************************/
778
/* Constants for row-based hash */
779
786M
#define ZSTD_ROW_HASH_TAG_MASK ((1u << ZSTD_ROW_HASH_TAG_BITS) - 1)
780
#define ZSTD_ROW_HASH_MAX_ENTRIES 64    /* absolute maximum number of entries per row, for all configurations */
781
782
1.52G
#define ZSTD_ROW_HASH_CACHE_MASK (ZSTD_ROW_HASH_CACHE_SIZE - 1)
783
784
typedef U64 ZSTD_VecMask;   /* Clarifies when we are interacting with a U64 representing a mask of matches */
785
786
/* ZSTD_VecMask_next():
787
 * Starting from the LSB, returns the idx of the next non-zero bit.
788
 * Basically counting the nb of trailing zeroes.
789
 */
790
432M
MEM_STATIC U32 ZSTD_VecMask_next(ZSTD_VecMask val) {
791
432M
    return ZSTD_countTrailingZeros64(val);
792
432M
}
793
794
/* ZSTD_row_nextIndex():
795
 * Returns the next index to insert at within a tagTable row, and updates the "head"
796
 * value to reflect the update. Essentially cycles backwards from [1, {entries per row})
797
 */
798
780M
FORCE_INLINE_TEMPLATE U32 ZSTD_row_nextIndex(BYTE* const tagRow, U32 const rowMask) {
799
780M
    U32 next = (*tagRow-1) & rowMask;
800
780M
    next += (next == 0) ? rowMask : 0; /* skip first position */
801
780M
    *tagRow = (BYTE)next;
802
780M
    return next;
803
780M
}
804
805
/* ZSTD_isAligned():
806
 * Checks that a pointer is aligned to "align" bytes which must be a power of 2.
807
 */
808
1.56G
MEM_STATIC int ZSTD_isAligned(void const* ptr, size_t align) {
809
1.56G
    assert((align & (align - 1)) == 0);
810
1.56G
    return (((size_t)ptr) & (align - 1)) == 0;
811
1.56G
}
812
813
/* ZSTD_row_prefetch():
814
 * Performs prefetching for the hashTable and tagTable at a given row.
815
 */
816
782M
FORCE_INLINE_TEMPLATE void ZSTD_row_prefetch(U32 const* hashTable, BYTE const* tagTable, U32 const relRow, U32 const rowLog) {
817
782M
    PREFETCH_L1(hashTable + relRow);
818
782M
    if (rowLog >= 5) {
819
398M
        PREFETCH_L1(hashTable + relRow + 16);
820
        /* Note: prefetching more of the hash table does not appear to be beneficial for 128-entry rows */
821
398M
    }
822
782M
    PREFETCH_L1(tagTable + relRow);
823
782M
    if (rowLog == 6) {
824
221M
        PREFETCH_L1(tagTable + relRow + 32);
825
221M
    }
826
782M
    assert(rowLog == 4 || rowLog == 5 || rowLog == 6);
827
782M
    assert(ZSTD_isAligned(hashTable + relRow, 64));                 /* prefetched hash row always 64-byte aligned */
828
782M
    assert(ZSTD_isAligned(tagTable + relRow, (size_t)1 << rowLog)); /* prefetched tagRow sits on correct multiple of bytes (32,64,128) */
829
782M
}
830
831
/* ZSTD_row_fillHashCache():
832
 * Fill up the hash cache starting at idx, prefetching up to ZSTD_ROW_HASH_CACHE_SIZE entries,
833
 * but not beyond iLimit.
834
 */
835
FORCE_INLINE_TEMPLATE
836
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
837
void ZSTD_row_fillHashCache(ZSTD_MatchState_t* ms, const BYTE* base,
838
                                   U32 const rowLog, U32 const mls,
839
                                   U32 idx, const BYTE* const iLimit)
840
3.52M
{
841
3.52M
    U32 const* const hashTable = ms->hashTable;
842
3.52M
    BYTE const* const tagTable = ms->tagTable;
843
3.52M
    U32 const hashLog = ms->rowHashLog;
844
3.52M
    U32 const maxElemsToPrefetch = (base + idx) > iLimit ? 0 : (U32)(iLimit - (base + idx) + 1);
845
3.52M
    U32 const lim = idx + MIN(ZSTD_ROW_HASH_CACHE_SIZE, maxElemsToPrefetch);
846
847
31.4M
    for (; idx < lim; ++idx) {
848
27.9M
        U32 const hash = (U32)ZSTD_hashPtrSalted(base + idx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt);
849
27.9M
        U32 const row = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
850
27.9M
        ZSTD_row_prefetch(hashTable, tagTable, row, rowLog);
851
27.9M
        ms->hashCache[idx & ZSTD_ROW_HASH_CACHE_MASK] = hash;
852
27.9M
    }
853
854
3.52M
    DEBUGLOG(6, "ZSTD_row_fillHashCache(): [%u %u %u %u %u %u %u %u]", ms->hashCache[0], ms->hashCache[1],
855
3.52M
                                                     ms->hashCache[2], ms->hashCache[3], ms->hashCache[4],
856
3.52M
                                                     ms->hashCache[5], ms->hashCache[6], ms->hashCache[7]);
857
3.52M
}
858
859
/* ZSTD_row_nextCachedHash():
860
 * Returns the hash of base + idx, and replaces the hash in the hash cache with the byte at
861
 * base + idx + ZSTD_ROW_HASH_CACHE_SIZE. Also prefetches the appropriate rows from hashTable and tagTable.
862
 */
863
FORCE_INLINE_TEMPLATE
864
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
865
U32 ZSTD_row_nextCachedHash(U32* cache, U32 const* hashTable,
866
                                                  BYTE const* tagTable, BYTE const* base,
867
                                                  U32 idx, U32 const hashLog,
868
                                                  U32 const rowLog, U32 const mls,
869
                                                  U64 const hashSalt)
870
749M
{
871
749M
    U32 const newHash = (U32)ZSTD_hashPtrSalted(base+idx+ZSTD_ROW_HASH_CACHE_SIZE, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, hashSalt);
872
749M
    U32 const row = (newHash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
873
749M
    ZSTD_row_prefetch(hashTable, tagTable, row, rowLog);
874
749M
    {   U32 const hash = cache[idx & ZSTD_ROW_HASH_CACHE_MASK];
875
749M
        cache[idx & ZSTD_ROW_HASH_CACHE_MASK] = newHash;
876
749M
        return hash;
877
749M
    }
878
749M
}
879
880
/* ZSTD_row_update_internalImpl():
881
 * Updates the hash table with positions starting from updateStartIdx until updateEndIdx.
882
 */
883
FORCE_INLINE_TEMPLATE
884
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
885
void ZSTD_row_update_internalImpl(ZSTD_MatchState_t* ms,
886
                                  U32 updateStartIdx, U32 const updateEndIdx,
887
                                  U32 const mls, U32 const rowLog,
888
                                  U32 const rowMask, U32 const useCache)
889
243M
{
890
243M
    U32* const hashTable = ms->hashTable;
891
243M
    BYTE* const tagTable = ms->tagTable;
892
243M
    U32 const hashLog = ms->rowHashLog;
893
243M
    const BYTE* const base = ms->window.base;
894
895
243M
    DEBUGLOG(6, "ZSTD_row_update_internalImpl(): updateStartIdx=%u, updateEndIdx=%u", updateStartIdx, updateEndIdx);
896
777M
    for (; updateStartIdx < updateEndIdx; ++updateStartIdx) {
897
534M
        U32 const hash = useCache ? ZSTD_row_nextCachedHash(ms->hashCache, hashTable, tagTable, base, updateStartIdx, hashLog, rowLog, mls, ms->hashSalt)
898
534M
                                  : (U32)ZSTD_hashPtrSalted(base + updateStartIdx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt);
899
534M
        U32 const relRow = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
900
534M
        U32* const row = hashTable + relRow;
901
534M
        BYTE* tagRow = tagTable + relRow;
902
534M
        U32 const pos = ZSTD_row_nextIndex(tagRow, rowMask);
903
904
534M
        assert(hash == ZSTD_hashPtrSalted(base + updateStartIdx, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, ms->hashSalt));
905
534M
        tagRow[pos] = hash & ZSTD_ROW_HASH_TAG_MASK;
906
534M
        row[pos] = updateStartIdx;
907
534M
    }
908
243M
}
909
910
/* ZSTD_row_update_internal():
911
 * Inserts the byte at ip into the appropriate position in the hash table, and updates ms->nextToUpdate.
912
 * Skips sections of long matches as is necessary.
913
 */
914
FORCE_INLINE_TEMPLATE
915
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
916
void ZSTD_row_update_internal(ZSTD_MatchState_t* ms, const BYTE* ip,
917
                              U32 const mls, U32 const rowLog,
918
                              U32 const rowMask, U32 const useCache)
919
243M
{
920
243M
    U32 idx = ms->nextToUpdate;
921
243M
    const BYTE* const base = ms->window.base;
922
243M
    const U32 target = (U32)(ip - base);
923
243M
    const U32 kSkipThreshold = 384;
924
243M
    const U32 kMaxMatchStartPositionsToUpdate = 96;
925
243M
    const U32 kMaxMatchEndPositionsToUpdate = 32;
926
927
243M
    if (useCache) {
928
        /* Only skip positions when using hash cache, i.e.
929
         * if we are loading a dict, don't skip anything.
930
         * If we decide to skip, then we only update a set number
931
         * of positions at the beginning and end of the match.
932
         */
933
243M
        if (UNLIKELY(target - idx > kSkipThreshold)) {
934
335k
            U32 const bound = idx + kMaxMatchStartPositionsToUpdate;
935
335k
            ZSTD_row_update_internalImpl(ms, idx, bound, mls, rowLog, rowMask, useCache);
936
335k
            idx = target - kMaxMatchEndPositionsToUpdate;
937
335k
            ZSTD_row_fillHashCache(ms, base, rowLog, mls, idx, ip+1);
938
335k
        }
939
243M
    }
940
243M
    assert(target >= idx);
941
243M
    ZSTD_row_update_internalImpl(ms, idx, target, mls, rowLog, rowMask, useCache);
942
243M
    ms->nextToUpdate = target;
943
243M
}
944
945
/* ZSTD_row_update():
946
 * External wrapper for ZSTD_row_update_internal(). Used for filling the hashtable during dictionary
947
 * processing.
948
 */
949
27.9k
void ZSTD_row_update(ZSTD_MatchState_t* const ms, const BYTE* ip) {
950
27.9k
    const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
951
27.9k
    const U32 rowMask = (1u << rowLog) - 1;
952
27.9k
    const U32 mls = MIN(ms->cParams.minMatch, 6 /* mls caps out at 6 */);
953
954
27.9k
    DEBUGLOG(5, "ZSTD_row_update(), rowLog=%u", rowLog);
955
27.9k
    ZSTD_row_update_internal(ms, ip, mls, rowLog, rowMask, 0 /* don't use cache */);
956
27.9k
}
957
958
/* Returns the mask width of bits group of which will be set to 1. Given not all
959
 * architectures have easy movemask instruction, this helps to iterate over
960
 * groups of bits easier and faster.
961
 */
962
FORCE_INLINE_TEMPLATE U32
963
ZSTD_row_matchMaskGroupWidth(const U32 rowEntries)
964
499M
{
965
499M
    assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
966
499M
    assert(rowEntries <= ZSTD_ROW_HASH_MAX_ENTRIES);
967
499M
    (void)rowEntries;
968
#if defined(ZSTD_ARCH_ARM_NEON)
969
    /* NEON path only works for little endian */
970
    if (!MEM_isLittleEndian()) {
971
        return 1;
972
    }
973
    if (rowEntries == 16) {
974
        return 4;
975
    }
976
    if (rowEntries == 32) {
977
        return 2;
978
    }
979
    if (rowEntries == 64) {
980
        return 1;
981
    }
982
#endif
983
499M
    return 1;
984
499M
}
985
986
#if defined(ZSTD_ARCH_X86_SSE2)
987
FORCE_INLINE_TEMPLATE ZSTD_VecMask
988
ZSTD_row_getSSEMask(int nbChunks, const BYTE* const src, const BYTE tag, const U32 head)
989
252M
{
990
252M
    const __m128i comparisonMask = _mm_set1_epi8((char)tag);
991
252M
    int matches[4] = {0};
992
252M
    int i;
993
252M
    assert(nbChunks == 1 || nbChunks == 2 || nbChunks == 4);
994
793M
    for (i=0; i<nbChunks; i++) {
995
541M
        const __m128i chunk = _mm_loadu_si128((const __m128i*)(const void*)(src + 16*i));
996
541M
        const __m128i equalMask = _mm_cmpeq_epi8(chunk, comparisonMask);
997
541M
        matches[i] = _mm_movemask_epi8(equalMask);
998
541M
    }
999
252M
    if (nbChunks == 1) return ZSTD_rotateRight_U16((U16)matches[0], head);
1000
134M
    if (nbChunks == 2) return ZSTD_rotateRight_U32((U32)matches[1] << 16 | (U32)matches[0], head);
1001
134M
    assert(nbChunks == 4);
1002
77.5M
    return ZSTD_rotateRight_U64((U64)matches[3] << 48 | (U64)matches[2] << 32 | (U64)matches[1] << 16 | (U64)matches[0], head);
1003
77.5M
}
1004
#endif
1005
1006
#if defined(ZSTD_ARCH_ARM_NEON)
1007
FORCE_INLINE_TEMPLATE ZSTD_VecMask
1008
ZSTD_row_getNEONMask(const U32 rowEntries, const BYTE* const src, const BYTE tag, const U32 headGrouped)
1009
{
1010
    assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
1011
    if (rowEntries == 16) {
1012
        /* vshrn_n_u16 shifts by 4 every u16 and narrows to 8 lower bits.
1013
         * After that groups of 4 bits represent the equalMask. We lower
1014
         * all bits except the highest in these groups by doing AND with
1015
         * 0x88 = 0b10001000.
1016
         */
1017
        const uint8x16_t chunk = vld1q_u8(src);
1018
        const uint16x8_t equalMask = vreinterpretq_u16_u8(vceqq_u8(chunk, vdupq_n_u8(tag)));
1019
        const uint8x8_t res = vshrn_n_u16(equalMask, 4);
1020
        const U64 matches = vget_lane_u64(vreinterpret_u64_u8(res), 0);
1021
        return ZSTD_rotateRight_U64(matches, headGrouped) & 0x8888888888888888ull;
1022
    } else if (rowEntries == 32) {
1023
        /* Same idea as with rowEntries == 16 but doing AND with
1024
         * 0x55 = 0b01010101.
1025
         */
1026
        const uint16x8x2_t chunk = vld2q_u16((const uint16_t*)(const void*)src);
1027
        const uint8x16_t chunk0 = vreinterpretq_u8_u16(chunk.val[0]);
1028
        const uint8x16_t chunk1 = vreinterpretq_u8_u16(chunk.val[1]);
1029
        const uint8x16_t dup = vdupq_n_u8(tag);
1030
        const uint8x8_t t0 = vshrn_n_u16(vreinterpretq_u16_u8(vceqq_u8(chunk0, dup)), 6);
1031
        const uint8x8_t t1 = vshrn_n_u16(vreinterpretq_u16_u8(vceqq_u8(chunk1, dup)), 6);
1032
        const uint8x8_t res = vsli_n_u8(t0, t1, 4);
1033
        const U64 matches = vget_lane_u64(vreinterpret_u64_u8(res), 0) ;
1034
        return ZSTD_rotateRight_U64(matches, headGrouped) & 0x5555555555555555ull;
1035
    } else { /* rowEntries == 64 */
1036
        const uint8x16x4_t chunk = vld4q_u8(src);
1037
        const uint8x16_t dup = vdupq_n_u8(tag);
1038
        const uint8x16_t cmp0 = vceqq_u8(chunk.val[0], dup);
1039
        const uint8x16_t cmp1 = vceqq_u8(chunk.val[1], dup);
1040
        const uint8x16_t cmp2 = vceqq_u8(chunk.val[2], dup);
1041
        const uint8x16_t cmp3 = vceqq_u8(chunk.val[3], dup);
1042
1043
        const uint8x16_t t0 = vsriq_n_u8(cmp1, cmp0, 1);
1044
        const uint8x16_t t1 = vsriq_n_u8(cmp3, cmp2, 1);
1045
        const uint8x16_t t2 = vsriq_n_u8(t1, t0, 2);
1046
        const uint8x16_t t3 = vsriq_n_u8(t2, t2, 4);
1047
        const uint8x8_t t4 = vshrn_n_u16(vreinterpretq_u16_u8(t3), 4);
1048
        const U64 matches = vget_lane_u64(vreinterpret_u64_u8(t4), 0);
1049
        return ZSTD_rotateRight_U64(matches, headGrouped);
1050
    }
1051
}
1052
#endif
1053
#if defined(ZSTD_ARCH_RISCV_RVV) && (__riscv_xlen == 64)
1054
FORCE_INLINE_TEMPLATE ZSTD_VecMask
1055
ZSTD_row_getRVVMask(int rowEntries, const BYTE* const src, const BYTE tag, const U32 head)
1056
{
1057
    ZSTD_VecMask matches;
1058
    size_t vl;
1059
1060
    if (rowEntries == 16) {
1061
        vl = __riscv_vsetvl_e8m1(16);
1062
        {
1063
            vuint8m1_t chunk = __riscv_vle8_v_u8m1(src, vl);
1064
            vbool8_t mask = __riscv_vmseq_vx_u8m1_b8(chunk, tag, vl);
1065
            vuint16m1_t mask_u16 = __riscv_vreinterpret_v_b8_u16m1(mask);
1066
            matches = __riscv_vmv_x_s_u16m1_u16(mask_u16);
1067
            return ZSTD_rotateRight_U16((U16)matches, head);
1068
        }
1069
1070
    } else if (rowEntries == 32) {
1071
        vl = __riscv_vsetvl_e8m2(32);
1072
        {
1073
            vuint8m2_t chunk = __riscv_vle8_v_u8m2(src, vl);
1074
            vbool4_t mask = __riscv_vmseq_vx_u8m2_b4(chunk, tag, vl);
1075
            vuint32m1_t mask_u32 = __riscv_vreinterpret_v_b4_u32m1(mask);
1076
            matches = __riscv_vmv_x_s_u32m1_u32(mask_u32);
1077
            return ZSTD_rotateRight_U32((U32)matches, head);
1078
        }
1079
    } else { // rowEntries = 64
1080
        vl = __riscv_vsetvl_e8m4(64);
1081
        {
1082
            vuint8m4_t chunk = __riscv_vle8_v_u8m4(src, vl);
1083
            vbool2_t mask = __riscv_vmseq_vx_u8m4_b2(chunk, tag, vl);
1084
            vuint64m1_t mask_u64 = __riscv_vreinterpret_v_b2_u64m1(mask);
1085
            matches = __riscv_vmv_x_s_u64m1_u64(mask_u64);
1086
            return ZSTD_rotateRight_U64(matches, head);
1087
        }
1088
    }
1089
}
1090
#endif
1091
1092
/* Returns a ZSTD_VecMask (U64) that has the nth group (determined by
1093
 * ZSTD_row_matchMaskGroupWidth) of bits set to 1 if the newly-computed "tag"
1094
 * matches the hash at the nth position in a row of the tagTable.
1095
 * Each row is a circular buffer beginning at the value of "headGrouped". So we
1096
 * must rotate the "matches" bitfield to match up with the actual layout of the
1097
 * entries within the hashTable */
1098
FORCE_INLINE_TEMPLATE ZSTD_VecMask
1099
ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGrouped, const U32 rowEntries)
1100
252M
{
1101
252M
    const BYTE* const src = tagRow;
1102
252M
    assert((rowEntries == 16) || (rowEntries == 32) || rowEntries == 64);
1103
252M
    assert(rowEntries <= ZSTD_ROW_HASH_MAX_ENTRIES);
1104
252M
    assert(ZSTD_row_matchMaskGroupWidth(rowEntries) * rowEntries <= sizeof(ZSTD_VecMask) * 8);
1105
1106
252M
#if defined(ZSTD_ARCH_X86_SSE2)
1107
1108
252M
    return ZSTD_row_getSSEMask(rowEntries / 16, src, tag, headGrouped);
1109
1110
#elif defined(ZSTD_ARCH_RISCV_RVV) && (__riscv_xlen == 64)
1111
1112
    return ZSTD_row_getRVVMask(rowEntries, src, tag, headGrouped);
1113
1114
#else
1115
1116
#if defined(ZSTD_ARCH_ARM_NEON)
1117
  /* This NEON path only works for little endian - otherwise use SWAR below */
1118
    if (MEM_isLittleEndian()) {
1119
        return ZSTD_row_getNEONMask(rowEntries, src, tag, headGrouped);
1120
    }
1121
1122
1123
#endif
1124
    /* SWAR */
1125
    {   const int chunkSize = sizeof(size_t);
1126
        const size_t shiftAmount = ((chunkSize * 8) - chunkSize);
1127
        const size_t xFF = ~((size_t)0);
1128
        const size_t x01 = xFF / 0xFF;
1129
        const size_t x80 = x01 << 7;
1130
        const size_t splatChar = tag * x01;
1131
        ZSTD_VecMask matches = 0;
1132
        int i = rowEntries - chunkSize;
1133
        assert((sizeof(size_t) == 4) || (sizeof(size_t) == 8));
1134
        if (MEM_isLittleEndian()) { /* runtime check so have two loops */
1135
            const size_t extractMagic = (xFF / 0x7F) >> chunkSize;
1136
            do {
1137
                size_t chunk = MEM_readST(&src[i]);
1138
                chunk ^= splatChar;
1139
                chunk = (((chunk | x80) - x01) | chunk) & x80;
1140
                matches <<= chunkSize;
1141
                matches |= (chunk * extractMagic) >> shiftAmount;
1142
                i -= chunkSize;
1143
            } while (i >= 0);
1144
        } else { /* big endian: reverse bits during extraction */
1145
            const size_t msb = xFF ^ (xFF >> 1);
1146
            const size_t extractMagic = (msb / 0x1FF) | msb;
1147
            do {
1148
                size_t chunk = MEM_readST(&src[i]);
1149
                chunk ^= splatChar;
1150
                chunk = (((chunk | x80) - x01) | chunk) & x80;
1151
                matches <<= chunkSize;
1152
                matches |= ((chunk >> 7) * extractMagic) >> shiftAmount;
1153
                i -= chunkSize;
1154
            } while (i >= 0);
1155
        }
1156
        matches = ~matches;
1157
        if (rowEntries == 16) {
1158
            return ZSTD_rotateRight_U16((U16)matches, headGrouped);
1159
        } else if (rowEntries == 32) {
1160
            return ZSTD_rotateRight_U32((U32)matches, headGrouped);
1161
        } else {
1162
            return ZSTD_rotateRight_U64((U64)matches, headGrouped);
1163
        }
1164
    }
1165
#endif
1166
252M
}
1167
1168
/* The high-level approach of the SIMD row based match finder is as follows:
1169
 * - Figure out where to insert the new entry:
1170
 *      - Generate a hash for current input position and split it into a one byte of tag and `rowHashLog` bits of index.
1171
 *           - The hash is salted by a value that changes on every context reset, so when the same table is used
1172
 *             we will avoid collisions that would otherwise slow us down by introducing phantom matches.
1173
 *      - The hashTable is effectively split into groups or "rows" of 15 or 31 entries of U32, and the index determines
1174
 *        which row to insert into.
1175
 *      - Determine the correct position within the row to insert the entry into. Each row of 15 or 31 can
1176
 *        be considered as a circular buffer with a "head" index that resides in the tagTable (overall 16 or 32 bytes
1177
 *        per row).
1178
 * - Use SIMD to efficiently compare the tags in the tagTable to the 1-byte tag calculated for the position and
1179
 *   generate a bitfield that we can cycle through to check the collisions in the hash table.
1180
 * - Pick the longest match.
1181
 * - Insert the tag into the equivalent row and position in the tagTable.
1182
 */
1183
FORCE_INLINE_TEMPLATE
1184
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1185
size_t ZSTD_RowFindBestMatch(
1186
                        ZSTD_MatchState_t* ms,
1187
                        const BYTE* const ip, const BYTE* const iLimit,
1188
                        size_t* offsetPtr,
1189
                        const U32 mls, const ZSTD_dictMode_e dictMode,
1190
                        const U32 rowLog)
1191
247M
{
1192
247M
    U32* const hashTable = ms->hashTable;
1193
247M
    BYTE* const tagTable = ms->tagTable;
1194
247M
    U32* const hashCache = ms->hashCache;
1195
247M
    const U32 hashLog = ms->rowHashLog;
1196
247M
    const ZSTD_compressionParameters* const cParams = &ms->cParams;
1197
247M
    const BYTE* const base = ms->window.base;
1198
247M
    const BYTE* const dictBase = ms->window.dictBase;
1199
247M
    const U32 dictLimit = ms->window.dictLimit;
1200
247M
    const BYTE* const prefixStart = base + dictLimit;
1201
247M
    const BYTE* const dictEnd = dictBase + dictLimit;
1202
247M
    const U32 curr = (U32)(ip-base);
1203
247M
    const U32 maxDistance = 1U << cParams->windowLog;
1204
247M
    const U32 lowestValid = ms->window.lowLimit;
1205
247M
    const U32 withinMaxDistance = (curr - lowestValid > maxDistance) ? curr - maxDistance : lowestValid;
1206
247M
    const U32 isDictionary = (ms->loadedDictEnd != 0);
1207
247M
    const U32 lowLimit = isDictionary ? lowestValid : withinMaxDistance;
1208
247M
    const U32 rowEntries = (1U << rowLog);
1209
247M
    const U32 rowMask = rowEntries - 1;
1210
247M
    const U32 cappedSearchLog = MIN(cParams->searchLog, rowLog); /* nb of searches is capped at nb entries per row */
1211
247M
    const U32 groupWidth = ZSTD_row_matchMaskGroupWidth(rowEntries);
1212
247M
    const U64 hashSalt = ms->hashSalt;
1213
247M
    U32 nbAttempts = 1U << cappedSearchLog;
1214
247M
    size_t ml=4-1;
1215
247M
    U32 hash;
1216
1217
    /* DMS/DDS variables that may be referenced laster */
1218
247M
    const ZSTD_MatchState_t* const dms = ms->dictMatchState;
1219
1220
    /* Initialize the following variables to satisfy static analyzer */
1221
247M
    size_t ddsIdx = 0;
1222
247M
    U32 ddsExtraAttempts = 0; /* cctx hash tables are limited in searches, but allow extra searches into DDS */
1223
247M
    U32 dmsTag = 0;
1224
247M
    U32* dmsRow = NULL;
1225
247M
    BYTE* dmsTagRow = NULL;
1226
1227
247M
    if (dictMode == ZSTD_dedicatedDictSearch) {
1228
5.13M
        const U32 ddsHashLog = dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG;
1229
5.13M
        {   /* Prefetch DDS hashtable entry */
1230
5.13M
            ddsIdx = ZSTD_hashPtr(ip, ddsHashLog, mls) << ZSTD_LAZY_DDSS_BUCKET_LOG;
1231
5.13M
            PREFETCH_L1(&dms->hashTable[ddsIdx]);
1232
5.13M
        }
1233
5.13M
        ddsExtraAttempts = cParams->searchLog > rowLog ? 1U << (cParams->searchLog - rowLog) : 0;
1234
5.13M
    }
1235
1236
247M
    if (dictMode == ZSTD_dictMatchState) {
1237
        /* Prefetch DMS rows */
1238
5.07M
        U32* const dmsHashTable = dms->hashTable;
1239
5.07M
        BYTE* const dmsTagTable = dms->tagTable;
1240
5.07M
        U32 const dmsHash = (U32)ZSTD_hashPtr(ip, dms->rowHashLog + ZSTD_ROW_HASH_TAG_BITS, mls);
1241
5.07M
        U32 const dmsRelRow = (dmsHash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
1242
5.07M
        dmsTag = dmsHash & ZSTD_ROW_HASH_TAG_MASK;
1243
5.07M
        dmsTagRow = (BYTE*)(dmsTagTable + dmsRelRow);
1244
5.07M
        dmsRow = dmsHashTable + dmsRelRow;
1245
5.07M
        ZSTD_row_prefetch(dmsHashTable, dmsTagTable, dmsRelRow, rowLog);
1246
5.07M
    }
1247
1248
    /* Update the hashTable and tagTable up to (but not including) ip */
1249
247M
    if (!ms->lazySkipping) {
1250
243M
        ZSTD_row_update_internal(ms, ip, mls, rowLog, rowMask, 1 /* useCache */);
1251
243M
        hash = ZSTD_row_nextCachedHash(hashCache, hashTable, tagTable, base, curr, hashLog, rowLog, mls, hashSalt);
1252
243M
    } else {
1253
        /* Stop inserting every position when in the lazy skipping mode.
1254
         * The hash cache is also not kept up to date in this mode.
1255
         */
1256
3.99M
        hash = (U32)ZSTD_hashPtrSalted(ip, hashLog + ZSTD_ROW_HASH_TAG_BITS, mls, hashSalt);
1257
3.99M
        ms->nextToUpdate = curr;
1258
3.99M
    }
1259
247M
    ms->hashSaltEntropy += hash; /* collect salt entropy */
1260
1261
247M
    {   /* Get the hash for ip, compute the appropriate row */
1262
247M
        U32 const relRow = (hash >> ZSTD_ROW_HASH_TAG_BITS) << rowLog;
1263
247M
        U32 const tag = hash & ZSTD_ROW_HASH_TAG_MASK;
1264
247M
        U32* const row = hashTable + relRow;
1265
247M
        BYTE* tagRow = (BYTE*)(tagTable + relRow);
1266
247M
        U32 const headGrouped = (*tagRow & rowMask) * groupWidth;
1267
247M
        U32 matchBuffer[ZSTD_ROW_HASH_MAX_ENTRIES];
1268
247M
        size_t numMatches = 0;
1269
247M
        size_t currMatch = 0;
1270
247M
        ZSTD_VecMask matches = ZSTD_row_getMatchMask(tagRow, (BYTE)tag, headGrouped, rowEntries);
1271
1272
        /* Cycle through the matches and prefetch */
1273
670M
        for (; (matches > 0) && (nbAttempts > 0); matches &= (matches - 1)) {
1274
429M
            U32 const matchPos = ((headGrouped + ZSTD_VecMask_next(matches)) / groupWidth) & rowMask;
1275
429M
            U32 const matchIndex = row[matchPos];
1276
429M
            if(matchPos == 0) continue;
1277
429M
            assert(numMatches < rowEntries);
1278
429M
            if (matchIndex < lowLimit)
1279
6.06M
                break;
1280
422M
            if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
1281
417M
                PREFETCH_L1(base + matchIndex);
1282
417M
            } else {
1283
5.67M
                PREFETCH_L1(dictBase + matchIndex);
1284
5.67M
            }
1285
422M
            matchBuffer[numMatches++] = matchIndex;
1286
422M
            --nbAttempts;
1287
422M
        }
1288
1289
        /* Speed opt: insert current byte into hashtable too. This allows us to avoid one iteration of the loop
1290
           in ZSTD_row_update_internal() at the next search. */
1291
247M
        {
1292
247M
            U32 const pos = ZSTD_row_nextIndex(tagRow, rowMask);
1293
247M
            tagRow[pos] = (BYTE)tag;
1294
247M
            row[pos] = ms->nextToUpdate++;
1295
247M
        }
1296
1297
        /* Return the longest match */
1298
664M
        for (; currMatch < numMatches; ++currMatch) {
1299
417M
            U32 const matchIndex = matchBuffer[currMatch];
1300
417M
            size_t currentMl=0;
1301
417M
            assert(matchIndex < curr);
1302
417M
            assert(matchIndex >= lowLimit);
1303
1304
417M
            if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
1305
411M
                const BYTE* const match = base + matchIndex;
1306
411M
                assert(matchIndex >= dictLimit);   /* ensures this is true if dictMode != ZSTD_extDict */
1307
                /* read 4B starting from (match + ml + 1 - sizeof(U32)) */
1308
411M
                if (MEM_read32(match + ml - 3) == MEM_read32(ip + ml - 3))   /* potentially better */
1309
86.6M
                    currentMl = ZSTD_count(ip, match, iLimit);
1310
411M
            } else {
1311
5.57M
                const BYTE* const match = dictBase + matchIndex;
1312
5.57M
                assert(match+4 <= dictEnd);
1313
5.57M
                if (MEM_read32(match) == MEM_read32(ip))   /* assumption : matchIndex <= dictLimit-4 (by table construction) */
1314
5.21M
                    currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
1315
5.57M
            }
1316
1317
            /* Save best solution */
1318
417M
            if (currentMl > ml) {
1319
79.3M
                ml = currentMl;
1320
79.3M
                *offsetPtr = OFFSET_TO_OFFBASE(curr - matchIndex);
1321
79.3M
                if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
1322
79.3M
            }
1323
417M
        }
1324
247M
    }
1325
1326
247M
    assert(nbAttempts <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */
1327
247M
    if (dictMode == ZSTD_dedicatedDictSearch) {
1328
5.13M
        ml = ZSTD_dedicatedDictSearch_lazy_search(offsetPtr, ml, nbAttempts + ddsExtraAttempts, dms,
1329
5.13M
                                                  ip, iLimit, prefixStart, curr, dictLimit, ddsIdx);
1330
241M
    } else if (dictMode == ZSTD_dictMatchState) {
1331
        /* TODO: Measure and potentially add prefetching to DMS */
1332
5.07M
        const U32 dmsLowestIndex       = dms->window.dictLimit;
1333
5.07M
        const BYTE* const dmsBase      = dms->window.base;
1334
5.07M
        const BYTE* const dmsEnd       = dms->window.nextSrc;
1335
5.07M
        const U32 dmsSize              = (U32)(dmsEnd - dmsBase);
1336
5.07M
        const U32 dmsIndexDelta        = dictLimit - dmsSize;
1337
1338
5.07M
        {   U32 const headGrouped = (*dmsTagRow & rowMask) * groupWidth;
1339
5.07M
            U32 matchBuffer[ZSTD_ROW_HASH_MAX_ENTRIES];
1340
5.07M
            size_t numMatches = 0;
1341
5.07M
            size_t currMatch = 0;
1342
5.07M
            ZSTD_VecMask matches = ZSTD_row_getMatchMask(dmsTagRow, (BYTE)dmsTag, headGrouped, rowEntries);
1343
1344
7.89M
            for (; (matches > 0) && (nbAttempts > 0); matches &= (matches - 1)) {
1345
2.83M
                U32 const matchPos = ((headGrouped + ZSTD_VecMask_next(matches)) / groupWidth) & rowMask;
1346
2.83M
                U32 const matchIndex = dmsRow[matchPos];
1347
2.83M
                if(matchPos == 0) continue;
1348
2.80M
                if (matchIndex < dmsLowestIndex)
1349
18.5k
                    break;
1350
2.78M
                PREFETCH_L1(dmsBase + matchIndex);
1351
2.78M
                matchBuffer[numMatches++] = matchIndex;
1352
2.78M
                --nbAttempts;
1353
2.78M
            }
1354
1355
            /* Return the longest match */
1356
7.83M
            for (; currMatch < numMatches; ++currMatch) {
1357
2.76M
                U32 const matchIndex = matchBuffer[currMatch];
1358
2.76M
                size_t currentMl=0;
1359
2.76M
                assert(matchIndex >= dmsLowestIndex);
1360
2.76M
                assert(matchIndex < curr);
1361
1362
2.76M
                {   const BYTE* const match = dmsBase + matchIndex;
1363
2.76M
                    assert(match+4 <= dmsEnd);
1364
2.76M
                    if (MEM_read32(match) == MEM_read32(ip))
1365
2.19M
                        currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
1366
2.76M
                }
1367
1368
2.76M
                if (currentMl > ml) {
1369
333k
                    ml = currentMl;
1370
333k
                    assert(curr > matchIndex + dmsIndexDelta);
1371
333k
                    *offsetPtr = OFFSET_TO_OFFBASE(curr - (matchIndex + dmsIndexDelta));
1372
333k
                    if (ip+currentMl == iLimit) break;
1373
333k
                }
1374
2.76M
            }
1375
5.07M
        }
1376
5.07M
    }
1377
247M
    return ml;
1378
247M
}
1379
1380
1381
/**
1382
 * Generate search functions templated on (dictMode, mls, rowLog).
1383
 * These functions are outlined for code size & compilation time.
1384
 * ZSTD_searchMax() dispatches to the correct implementation function.
1385
 *
1386
 * TODO: The start of the search function involves loading and calculating a
1387
 * bunch of constants from the ZSTD_MatchState_t. These computations could be
1388
 * done in an initialization function, and saved somewhere in the match state.
1389
 * Then we could pass a pointer to the saved state instead of the match state,
1390
 * and avoid duplicate computations.
1391
 *
1392
 * TODO: Move the match re-winding into searchMax. This improves compression
1393
 * ratio, and unlocks further simplifications with the next TODO.
1394
 *
1395
 * TODO: Try moving the repcode search into searchMax. After the re-winding
1396
 * and repcode search are in searchMax, there is no more logic in the match
1397
 * finder loop that requires knowledge about the dictMode. So we should be
1398
 * able to avoid force inlining it, and we can join the extDict loop with
1399
 * the single segment loop. It should go in searchMax instead of its own
1400
 * function to avoid having multiple virtual function calls per search.
1401
 */
1402
1403
81.1M
#define ZSTD_BT_SEARCH_FN(dictMode, mls) ZSTD_BtFindBestMatch_##dictMode##_##mls
1404
142M
#define ZSTD_HC_SEARCH_FN(dictMode, mls) ZSTD_HcFindBestMatch_##dictMode##_##mls
1405
247M
#define ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog) ZSTD_RowFindBestMatch_##dictMode##_##mls##_##rowLog
1406
1407
#define ZSTD_SEARCH_FN_ATTRS FORCE_NOINLINE
1408
1409
#define GEN_ZSTD_BT_SEARCH_FN(dictMode, mls)                                           \
1410
    ZSTD_SEARCH_FN_ATTRS size_t ZSTD_BT_SEARCH_FN(dictMode, mls)(                      \
1411
            ZSTD_MatchState_t* ms,                                                     \
1412
            const BYTE* ip, const BYTE* const iLimit,                                  \
1413
            size_t* offBasePtr)                                                        \
1414
81.1M
    {                                                                                  \
1415
81.1M
        assert(MAX(4, MIN(6, ms->cParams.minMatch)) == mls);                           \
1416
81.1M
        return ZSTD_BtFindBestMatch(ms, ip, iLimit, offBasePtr, mls, ZSTD_##dictMode); \
1417
81.1M
    }                                                                                  \
1418
1419
#define GEN_ZSTD_HC_SEARCH_FN(dictMode, mls)                                          \
1420
    ZSTD_SEARCH_FN_ATTRS size_t ZSTD_HC_SEARCH_FN(dictMode, mls)(                     \
1421
            ZSTD_MatchState_t* ms,                                                    \
1422
            const BYTE* ip, const BYTE* const iLimit,                                 \
1423
            size_t* offsetPtr)                                                        \
1424
142M
    {                                                                                 \
1425
142M
        assert(MAX(4, MIN(6, ms->cParams.minMatch)) == mls);                          \
1426
142M
        return ZSTD_HcFindBestMatch(ms, ip, iLimit, offsetPtr, mls, ZSTD_##dictMode); \
1427
142M
    }                                                                                 \
1428
1429
#define GEN_ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog)                                          \
1430
    ZSTD_SEARCH_FN_ATTRS size_t ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog)(                     \
1431
            ZSTD_MatchState_t* ms,                                                             \
1432
            const BYTE* ip, const BYTE* const iLimit,                                          \
1433
            size_t* offsetPtr)                                                                 \
1434
247M
    {                                                                                          \
1435
247M
        assert(MAX(4, MIN(6, ms->cParams.minMatch)) == mls);                                   \
1436
247M
        assert(MAX(4, MIN(6, ms->cParams.searchLog)) == rowLog);                               \
1437
247M
        return ZSTD_RowFindBestMatch(ms, ip, iLimit, offsetPtr, mls, ZSTD_##dictMode, rowLog); \
1438
247M
    }                                                                                          \
1439
1440
#define ZSTD_FOR_EACH_ROWLOG(X, dictMode, mls) \
1441
116M
    X(dictMode, mls, 4)                        \
1442
116M
    X(dictMode, mls, 5)                        \
1443
75.9M
    X(dictMode, mls, 6)
1444
1445
#define ZSTD_FOR_EACH_MLS_ROWLOG(X, dictMode) \
1446
    ZSTD_FOR_EACH_ROWLOG(X, dictMode, 4)      \
1447
    ZSTD_FOR_EACH_ROWLOG(X, dictMode, 5)      \
1448
    ZSTD_FOR_EACH_ROWLOG(X, dictMode, 6)
1449
1450
#define ZSTD_FOR_EACH_MLS(X, dictMode) \
1451
189M
    X(dictMode, 4)                     \
1452
151M
    X(dictMode, 5)                     \
1453
131M
    X(dictMode, 6)
1454
1455
#define ZSTD_FOR_EACH_DICT_MODE(X, ...) \
1456
    X(__VA_ARGS__, noDict)              \
1457
    X(__VA_ARGS__, extDict)             \
1458
    X(__VA_ARGS__, dictMatchState)      \
1459
    X(__VA_ARGS__, dedicatedDictSearch)
1460
1461
/* Generate row search fns for each combination of (dictMode, mls, rowLog) */
1462
8.15G
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_4_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_4_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_4_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_5_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_5_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_5_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_6_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_6_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_noDict_6_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_4_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_4_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_4_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_5_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_5_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_5_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_6_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_6_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_extDict_6_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_4_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_4_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_4_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_5_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_5_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_5_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_6_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_6_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dictMatchState_6_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_4_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_4_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_4_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_5_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_5_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_5_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_6_4
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_6_5
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
zstd_lazy.c:ZSTD_RowFindBestMatch_dedicatedDictSearch_6_6
Line
Count
Source
1462
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS_ROWLOG, GEN_ZSTD_ROW_SEARCH_FN)
1463
8.15G
/* Generate binary Tree search fns for each combination of (dictMode, mls) */
1464
8.15G
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_noDict_4
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_noDict_5
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_noDict_6
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_extDict_4
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_extDict_5
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_extDict_6
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_dictMatchState_4
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_dictMatchState_5
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
zstd_lazy.c:ZSTD_BtFindBestMatch_dictMatchState_6
Line
Count
Source
1464
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_BT_SEARCH_FN)
Unexecuted instantiation: zstd_lazy.c:ZSTD_BtFindBestMatch_dedicatedDictSearch_4
Unexecuted instantiation: zstd_lazy.c:ZSTD_BtFindBestMatch_dedicatedDictSearch_5
Unexecuted instantiation: zstd_lazy.c:ZSTD_BtFindBestMatch_dedicatedDictSearch_6
1465
1.34G
/* Generate hash chain search fns for each combination of (dictMode, mls) */
1466
2.34G
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_noDict_4
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_noDict_5
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_noDict_6
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_extDict_4
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_extDict_5
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_extDict_6
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_dictMatchState_4
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_dictMatchState_5
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_dictMatchState_6
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_dedicatedDictSearch_4
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_dedicatedDictSearch_5
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
zstd_lazy.c:ZSTD_HcFindBestMatch_dedicatedDictSearch_6
Line
Count
Source
1466
ZSTD_FOR_EACH_DICT_MODE(ZSTD_FOR_EACH_MLS, GEN_ZSTD_HC_SEARCH_FN)
1467
2.34G
1468
2.34G
typedef enum { search_hashChain=0, search_binaryTree=1, search_rowHash=2 } searchMethod_e;
1469
2.34G
1470
2.34G
#define GEN_ZSTD_CALL_BT_SEARCH_FN(dictMode, mls)                         \
1471
2.34G
    case mls:                                                             \
1472
81.1M
        return ZSTD_BT_SEARCH_FN(dictMode, mls)(ms, ip, iend, offsetPtr);
1473
#define GEN_ZSTD_CALL_HC_SEARCH_FN(dictMode, mls)                         \
1474
142M
    case mls:                                                             \
1475
142M
        return ZSTD_HC_SEARCH_FN(dictMode, mls)(ms, ip, iend, offsetPtr);
1476
#define GEN_ZSTD_CALL_ROW_SEARCH_FN(dictMode, mls, rowLog)                         \
1477
247M
    case rowLog:                                                                   \
1478
247M
        return ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog)(ms, ip, iend, offsetPtr);
1479
1480
#define ZSTD_SWITCH_MLS(X, dictMode)   \
1481
471M
    switch (mls) {                     \
1482
471M
        ZSTD_FOR_EACH_MLS(X, dictMode) \
1483
471M
    }
1484
1485
#define ZSTD_SWITCH_ROWLOG(dictMode, mls)                                    \
1486
0
    case mls:                                                                \
1487
0
        switch (rowLog) {                                                    \
1488
247M
            ZSTD_FOR_EACH_ROWLOG(GEN_ZSTD_CALL_ROW_SEARCH_FN, dictMode, mls) \
1489
0
        }                                                                    \
1490
0
        ZSTD_UNREACHABLE;                                                    \
1491
0
        break;
1492
1493
#define ZSTD_SWITCH_SEARCH_METHOD(dictMode)                       \
1494
471M
    switch (searchMethod) {                                       \
1495
142M
        case search_hashChain:                                    \
1496
142M
            ZSTD_SWITCH_MLS(GEN_ZSTD_CALL_HC_SEARCH_FN, dictMode) \
1497
142M
            break;                                                \
1498
142M
        case search_binaryTree:                                   \
1499
81.1M
            ZSTD_SWITCH_MLS(GEN_ZSTD_CALL_BT_SEARCH_FN, dictMode) \
1500
81.1M
            break;                                                \
1501
247M
        case search_rowHash:                                      \
1502
247M
            ZSTD_SWITCH_MLS(ZSTD_SWITCH_ROWLOG, dictMode)         \
1503
247M
            break;                                                \
1504
471M
    }                                                             \
1505
471M
    ZSTD_UNREACHABLE;
1506
1507
/**
1508
 * Searches for the longest match at @p ip.
1509
 * Dispatches to the correct implementation function based on the
1510
 * (searchMethod, dictMode, mls, rowLog). We use switch statements
1511
 * here instead of using an indirect function call through a function
1512
 * pointer because after Spectre and Meltdown mitigations, indirect
1513
 * function calls can be very costly, especially in the kernel.
1514
 *
1515
 * NOTE: dictMode and searchMethod should be templated, so those switch
1516
 * statements should be optimized out. Only the mls & rowLog switches
1517
 * should be left.
1518
 *
1519
 * @param ms The match state.
1520
 * @param ip The position to search at.
1521
 * @param iend The end of the input data.
1522
 * @param[out] offsetPtr Stores the match offset into this pointer.
1523
 * @param mls The minimum search length, in the range [4, 6].
1524
 * @param rowLog The row log (if applicable), in the range [4, 6].
1525
 * @param searchMethod The search method to use (templated).
1526
 * @param dictMode The dictMode (templated).
1527
 *
1528
 * @returns The length of the longest match found, or < mls if no match is found.
1529
 * If a match is found its offset is stored in @p offsetPtr.
1530
 */
1531
FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax(
1532
    ZSTD_MatchState_t* ms,
1533
    const BYTE* ip,
1534
    const BYTE* iend,
1535
    size_t* offsetPtr,
1536
    U32 const mls,
1537
    U32 const rowLog,
1538
    searchMethod_e const searchMethod,
1539
    ZSTD_dictMode_e const dictMode)
1540
471M
{
1541
471M
    if (dictMode == ZSTD_noDict) {
1542
392M
        ZSTD_SWITCH_SEARCH_METHOD(noDict)
1543
78.7M
    } else if (dictMode == ZSTD_extDict) {
1544
62.6M
        ZSTD_SWITCH_SEARCH_METHOD(extDict)
1545
16.1M
    } else if (dictMode == ZSTD_dictMatchState) {
1546
8.78M
        ZSTD_SWITCH_SEARCH_METHOD(dictMatchState)
1547
7.35M
    } else if (dictMode == ZSTD_dedicatedDictSearch) {
1548
7.35M
        ZSTD_SWITCH_SEARCH_METHOD(dedicatedDictSearch)
1549
0
    }
1550
18.4E
    ZSTD_UNREACHABLE;
1551
0
    return 0;
1552
18.4E
}
1553
1554
/* *******************************
1555
*  Common parser - lazy strategy
1556
*********************************/
1557
1558
FORCE_INLINE_TEMPLATE
1559
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1560
size_t ZSTD_compressBlock_lazy_generic(
1561
                        ZSTD_MatchState_t* ms, SeqStore_t* seqStore,
1562
                        U32 rep[ZSTD_REP_NUM],
1563
                        const void* src, size_t srcSize,
1564
                        const searchMethod_e searchMethod, const U32 depth,
1565
                        ZSTD_dictMode_e const dictMode)
1566
4.24M
{
1567
4.24M
    const BYTE* const istart = (const BYTE*)src;
1568
4.24M
    const BYTE* ip = istart;
1569
4.24M
    const BYTE* anchor = istart;
1570
4.24M
    const BYTE* const iend = istart + srcSize;
1571
4.24M
    const BYTE* const ilimit = (searchMethod == search_rowHash) ? iend - 8 - ZSTD_ROW_HASH_CACHE_SIZE : iend - 8;
1572
4.24M
    const BYTE* const base = ms->window.base;
1573
4.24M
    const U32 prefixLowestIndex = ms->window.dictLimit;
1574
4.24M
    const BYTE* const prefixLowest = base + prefixLowestIndex;
1575
4.24M
    const U32 mls = BOUNDED(4, ms->cParams.minMatch, 6);
1576
4.24M
    const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
1577
1578
4.24M
    U32 offset_1 = rep[0], offset_2 = rep[1];
1579
4.24M
    U32 offsetSaved1 = 0, offsetSaved2 = 0;
1580
1581
4.24M
    const int isDMS = dictMode == ZSTD_dictMatchState;
1582
4.24M
    const int isDDS = dictMode == ZSTD_dedicatedDictSearch;
1583
4.24M
    const int isDxS = isDMS || isDDS;
1584
4.24M
    const ZSTD_MatchState_t* const dms = ms->dictMatchState;
1585
4.24M
    const U32 dictLowestIndex      = isDxS ? dms->window.dictLimit : 0;
1586
4.24M
    const BYTE* const dictBase     = isDxS ? dms->window.base : NULL;
1587
4.24M
    const BYTE* const dictLowest   = isDxS ? dictBase + dictLowestIndex : NULL;
1588
4.24M
    const BYTE* const dictEnd      = isDxS ? dms->window.nextSrc : NULL;
1589
4.24M
    const U32 dictIndexDelta       = isDxS ?
1590
690k
                                     prefixLowestIndex - (U32)(dictEnd - dictBase) :
1591
4.24M
                                     0;
1592
4.24M
    const U32 dictAndPrefixLength = (U32)((ip - prefixLowest) + (dictEnd - dictLowest));
1593
1594
4.24M
    DEBUGLOG(5, "ZSTD_compressBlock_lazy_generic (dictMode=%u) (searchFunc=%u)", (U32)dictMode, (U32)searchMethod);
1595
4.24M
    ip += (dictAndPrefixLength == 0);
1596
4.24M
    if (dictMode == ZSTD_noDict) {
1597
3.55M
        U32 const curr = (U32)(ip - base);
1598
3.55M
        U32 const windowLow = ZSTD_getLowestPrefixIndex(ms, curr, ms->cParams.windowLog);
1599
3.55M
        U32 const maxRep = curr - windowLow;
1600
3.55M
        if (offset_2 > maxRep) offsetSaved2 = offset_2, offset_2 = 0;
1601
3.55M
        if (offset_1 > maxRep) offsetSaved1 = offset_1, offset_1 = 0;
1602
3.55M
    }
1603
4.24M
    if (isDxS) {
1604
        /* dictMatchState repCode checks don't currently handle repCode == 0
1605
         * disabling. */
1606
690k
        assert(offset_1 <= dictAndPrefixLength);
1607
690k
        assert(offset_2 <= dictAndPrefixLength);
1608
690k
    }
1609
1610
    /* Reset the lazy skipping state */
1611
4.24M
    ms->lazySkipping = 0;
1612
1613
4.24M
    if (searchMethod == search_rowHash) {
1614
2.68M
        ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
1615
2.68M
    }
1616
1617
    /* Match Loop */
1618
4.24M
#if defined(__GNUC__) && defined(__x86_64__)
1619
    /* I've measured random a 5% speed loss on levels 5 & 6 (greedy) when the
1620
     * code alignment is perturbed. To fix the instability align the loop on 32-bytes.
1621
     */
1622
4.24M
    __asm__(".p2align 5");
1623
4.24M
#endif
1624
357M
    while (ip < ilimit) {
1625
352M
        size_t matchLength=0;
1626
705M
        size_t offBase = REPCODE1_TO_OFFBASE;
1627
705M
        const BYTE* start=ip+1;
1628
705M
        DEBUGLOG(7, "search baseline (depth 0)");
1629
1630
        /* check repCode */
1631
705M
        if (isDxS) {
1632
13.8M
            const U32 repIndex = (U32)(ip - base) + 1 - offset_1;
1633
13.8M
            const BYTE* repMatch = ((dictMode == ZSTD_dictMatchState || dictMode == ZSTD_dedicatedDictSearch)
1634
13.8M
                                && repIndex < prefixLowestIndex) ?
1635
2.99M
                                   dictBase + (repIndex - dictIndexDelta) :
1636
13.8M
                                   base + repIndex;
1637
13.8M
            if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex))
1638
13.8M
                && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
1639
485k
                const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
1640
485k
                matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
1641
485k
                if (depth==0) goto _storeSequence;
1642
485k
            }
1643
13.8M
        }
1644
352M
        if ( dictMode == ZSTD_noDict
1645
339M
          && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
1646
15.3M
            matchLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
1647
15.3M
            if (depth==0) goto _storeSequence;
1648
15.3M
        }
1649
1650
        /* first search (depth 0) */
1651
349M
        {   size_t offbaseFound = 999999999;
1652
349M
            size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &offbaseFound, mls, rowLog, searchMethod, dictMode);
1653
349M
            if (ml2 > matchLength)
1654
292M
                matchLength = ml2, start = ip, offBase = offbaseFound;
1655
349M
        }
1656
1657
349M
        if (matchLength < 4) {
1658
310M
            size_t const step = ((size_t)(ip-anchor) >> kSearchStrength) + 1;   /* jump faster over incompressible sections */;
1659
310M
            ip += step;
1660
            /* Enter the lazy skipping mode once we are skipping more than 8 bytes at a time.
1661
             * In this mode we stop inserting every position into our tables, and only insert
1662
             * positions that we search, which is one in step positions.
1663
             * The exact cutoff is flexible, I've just chosen a number that is reasonably high,
1664
             * so we minimize the compression ratio loss in "normal" scenarios. This mode gets
1665
             * triggered once we've gone 2KB without finding any matches.
1666
             */
1667
310M
            ms->lazySkipping = step > kLazySkippingStep;
1668
310M
            continue;
1669
310M
        }
1670
1671
        /* let's try to find a better solution */
1672
39.2M
        if (depth>=1)
1673
37.5M
        while (ip<ilimit) {
1674
37.5M
            DEBUGLOG(7, "search depth 1");
1675
37.5M
            ip ++;
1676
37.5M
            if ( (dictMode == ZSTD_noDict)
1677
36.0M
              && (offBase) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
1678
13.0M
                size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
1679
13.0M
                int const gain2 = (int)(mlRep * 3);
1680
13.0M
                int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
1681
13.0M
                if ((mlRep >= 4) && (gain2 > gain1))
1682
2.75M
                    matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
1683
13.0M
            }
1684
37.5M
            if (isDxS) {
1685
1.49M
                const U32 repIndex = (U32)(ip - base) - offset_1;
1686
1.49M
                const BYTE* repMatch = repIndex < prefixLowestIndex ?
1687
281k
                               dictBase + (repIndex - dictIndexDelta) :
1688
1.49M
                               base + repIndex;
1689
1.49M
                if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex))
1690
1.48M
                    && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
1691
428k
                    const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
1692
428k
                    size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
1693
428k
                    int const gain2 = (int)(mlRep * 3);
1694
428k
                    int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
1695
428k
                    if ((mlRep >= 4) && (gain2 > gain1))
1696
92.2k
                        matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
1697
428k
                }
1698
1.49M
            }
1699
37.5M
            {   size_t ofbCandidate=999999999;
1700
37.5M
                size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, dictMode);
1701
37.5M
                int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate));   /* raw approx */
1702
37.5M
                int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 4);
1703
37.5M
                if ((ml2 >= 4) && (gain2 > gain1)) {
1704
3.17M
                    matchLength = ml2, offBase = ofbCandidate, start = ip;
1705
3.17M
                    continue;   /* search a better one */
1706
3.17M
            }   }
1707
1708
            /* let's find an even better one */
1709
34.3M
            if ((depth==2) && (ip<ilimit)) {
1710
21.7M
                DEBUGLOG(7, "search depth 2");
1711
21.7M
                ip ++;
1712
21.7M
                if ( (dictMode == ZSTD_noDict)
1713
20.8M
                  && (offBase) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
1714
6.93M
                    size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
1715
6.93M
                    int const gain2 = (int)(mlRep * 4);
1716
6.93M
                    int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
1717
6.93M
                    if ((mlRep >= 4) && (gain2 > gain1))
1718
905k
                        matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
1719
6.93M
                }
1720
21.7M
                if (isDxS) {
1721
884k
                    const U32 repIndex = (U32)(ip - base) - offset_1;
1722
884k
                    const BYTE* repMatch = repIndex < prefixLowestIndex ?
1723
158k
                                   dictBase + (repIndex - dictIndexDelta) :
1724
884k
                                   base + repIndex;
1725
884k
                    if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex))
1726
880k
                        && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
1727
231k
                        const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
1728
231k
                        size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
1729
231k
                        int const gain2 = (int)(mlRep * 4);
1730
231k
                        int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
1731
231k
                        if ((mlRep >= 4) && (gain2 > gain1))
1732
30.3k
                            matchLength = mlRep, offBase = REPCODE1_TO_OFFBASE, start = ip;
1733
231k
                    }
1734
884k
                }
1735
21.7M
                {   size_t ofbCandidate=999999999;
1736
21.7M
                    size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, dictMode);
1737
21.7M
                    int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate));   /* raw approx */
1738
21.7M
                    int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 7);
1739
21.7M
                    if ((ml2 >= 4) && (gain2 > gain1)) {
1740
639k
                        matchLength = ml2, offBase = ofbCandidate, start = ip;
1741
639k
                        continue;
1742
639k
            }   }   }
1743
33.7M
            break;  /* nothing found : store previous solution */
1744
34.3M
        }
1745
1746
        /* NOTE:
1747
         * Pay attention that `start[-value]` can lead to strange undefined behavior
1748
         * notably if `value` is unsigned, resulting in a large positive `-value`.
1749
         */
1750
        /* catch up */
1751
39.2M
        if (OFFBASE_IS_OFFSET(offBase)) {
1752
27.9M
            if (dictMode == ZSTD_noDict) {
1753
29.3M
                while ( ((start > anchor) & (start - OFFBASE_TO_OFFSET(offBase) > prefixLowest))
1754
18.2M
                     && (start[-1] == (start-OFFBASE_TO_OFFSET(offBase))[-1]) )  /* only search for offset within prefix */
1755
2.68M
                    { start--; matchLength++; }
1756
26.6M
            }
1757
27.9M
            if (isDxS) {
1758
1.23M
                U32 const matchIndex = (U32)((size_t)(start-base) - OFFBASE_TO_OFFSET(offBase));
1759
1.23M
                const BYTE* match = (matchIndex < prefixLowestIndex) ? dictBase + matchIndex - dictIndexDelta : base + matchIndex;
1760
1.23M
                const BYTE* const mStart = (matchIndex < prefixLowestIndex) ? dictLowest : prefixLowest;
1761
1.53M
                while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; }  /* catch up */
1762
1.23M
            }
1763
27.9M
            offset_2 = offset_1; offset_1 = (U32)OFFBASE_TO_OFFSET(offBase);
1764
27.9M
        }
1765
        /* store sequence */
1766
42.5M
_storeSequence:
1767
42.5M
        {   size_t const litLength = (size_t)(start - anchor);
1768
42.5M
            ZSTD_storeSeq(seqStore, litLength, anchor, iend, (U32)offBase, matchLength);
1769
42.5M
            anchor = ip = start + matchLength;
1770
42.5M
        }
1771
42.5M
        if (ms->lazySkipping) {
1772
            /* We've found a match, disable lazy skipping mode, and refill the hash cache. */
1773
18.2k
            if (searchMethod == search_rowHash) {
1774
11.9k
                ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
1775
11.9k
            }
1776
18.2k
            ms->lazySkipping = 0;
1777
18.2k
        }
1778
1779
        /* check immediate repcode */
1780
42.5M
        if (isDxS) {
1781
1.73M
            while (ip <= ilimit) {
1782
1.58M
                U32 const current2 = (U32)(ip-base);
1783
1.58M
                U32 const repIndex = current2 - offset_2;
1784
1.58M
                const BYTE* repMatch = repIndex < prefixLowestIndex ?
1785
337k
                        dictBase - dictIndexDelta + repIndex :
1786
1.58M
                        base + repIndex;
1787
1.58M
                if ( (ZSTD_index_overlap_check(prefixLowestIndex, repIndex))
1788
1.57M
                   && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
1789
94.8k
                    const BYTE* const repEnd2 = repIndex < prefixLowestIndex ? dictEnd : iend;
1790
94.8k
                    matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd2, prefixLowest) + 4;
1791
94.8k
                    offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase;   /* swap offset_2 <=> offset_1 */
1792
94.8k
                    ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
1793
94.8k
                    ip += matchLength;
1794
94.8k
                    anchor = ip;
1795
94.8k
                    continue;
1796
94.8k
                }
1797
1.48M
                break;
1798
1.58M
            }
1799
1.64M
        }
1800
1801
42.5M
        if (dictMode == ZSTD_noDict) {
1802
43.2M
            while ( ((ip <= ilimit) & (offset_2>0))
1803
42.0M
                 && (MEM_read32(ip) == MEM_read32(ip - offset_2)) ) {
1804
                /* store sequence */
1805
2.34M
                matchLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
1806
2.34M
                offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase; /* swap repcodes */
1807
2.34M
                ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
1808
2.34M
                ip += matchLength;
1809
2.34M
                anchor = ip;
1810
2.34M
                continue;   /* faster when present ... (?) */
1811
2.34M
    }   }   }
1812
1813
    /* If offset_1 started invalid (offsetSaved1 != 0) and became valid (offset_1 != 0),
1814
     * rotate saved offsets. See comment in ZSTD_compressBlock_fast_noDict for more context. */
1815
4.32M
    offsetSaved2 = ((offsetSaved1 != 0) && (offset_1 != 0)) ? offsetSaved1 : offsetSaved2;
1816
1817
    /* save reps for next block */
1818
4.32M
    rep[0] = offset_1 ? offset_1 : offsetSaved1;
1819
4.32M
    rep[1] = offset_2 ? offset_2 : offsetSaved2;
1820
1821
    /* Return the last literals size */
1822
4.32M
    return (size_t)(iend - anchor);
1823
4.24M
}
1824
#endif /* build exclusions */
1825
1826
1827
#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR
1828
size_t ZSTD_compressBlock_greedy(
1829
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1830
        void const* src, size_t srcSize)
1831
259k
{
1832
259k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict);
1833
259k
}
1834
1835
size_t ZSTD_compressBlock_greedy_dictMatchState(
1836
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1837
        void const* src, size_t srcSize)
1838
13.3k
{
1839
13.3k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState);
1840
13.3k
}
1841
1842
size_t ZSTD_compressBlock_greedy_dedicatedDictSearch(
1843
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1844
        void const* src, size_t srcSize)
1845
12.1k
{
1846
12.1k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch);
1847
12.1k
}
1848
1849
size_t ZSTD_compressBlock_greedy_row(
1850
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1851
        void const* src, size_t srcSize)
1852
541k
{
1853
541k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict);
1854
541k
}
1855
1856
size_t ZSTD_compressBlock_greedy_dictMatchState_row(
1857
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1858
        void const* src, size_t srcSize)
1859
41.8k
{
1860
41.8k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState);
1861
41.8k
}
1862
1863
size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row(
1864
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1865
        void const* src, size_t srcSize)
1866
26.5k
{
1867
26.5k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch);
1868
26.5k
}
1869
#endif
1870
1871
#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR
1872
size_t ZSTD_compressBlock_lazy(
1873
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1874
        void const* src, size_t srcSize)
1875
340k
{
1876
340k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict);
1877
340k
}
1878
1879
size_t ZSTD_compressBlock_lazy_dictMatchState(
1880
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1881
        void const* src, size_t srcSize)
1882
16.2k
{
1883
16.2k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState);
1884
16.2k
}
1885
1886
size_t ZSTD_compressBlock_lazy_dedicatedDictSearch(
1887
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1888
        void const* src, size_t srcSize)
1889
17.5k
{
1890
17.5k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch);
1891
17.5k
}
1892
1893
size_t ZSTD_compressBlock_lazy_row(
1894
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1895
        void const* src, size_t srcSize)
1896
683k
{
1897
683k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict);
1898
683k
}
1899
1900
size_t ZSTD_compressBlock_lazy_dictMatchState_row(
1901
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1902
        void const* src, size_t srcSize)
1903
37.5k
{
1904
37.5k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState);
1905
37.5k
}
1906
1907
size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row(
1908
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1909
        void const* src, size_t srcSize)
1910
60.4k
{
1911
60.4k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dedicatedDictSearch);
1912
60.4k
}
1913
#endif
1914
1915
#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR
1916
size_t ZSTD_compressBlock_lazy2(
1917
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1918
        void const* src, size_t srcSize)
1919
371k
{
1920
371k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict);
1921
371k
}
1922
1923
size_t ZSTD_compressBlock_lazy2_dictMatchState(
1924
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1925
        void const* src, size_t srcSize)
1926
25.3k
{
1927
25.3k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState);
1928
25.3k
}
1929
1930
size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch(
1931
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1932
        void const* src, size_t srcSize)
1933
28.3k
{
1934
28.3k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch);
1935
28.3k
}
1936
1937
size_t ZSTD_compressBlock_lazy2_row(
1938
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1939
        void const* src, size_t srcSize)
1940
903k
{
1941
903k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict);
1942
903k
}
1943
1944
size_t ZSTD_compressBlock_lazy2_dictMatchState_row(
1945
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1946
        void const* src, size_t srcSize)
1947
182k
{
1948
182k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState);
1949
182k
}
1950
1951
size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row(
1952
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1953
        void const* src, size_t srcSize)
1954
209k
{
1955
209k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch);
1956
209k
}
1957
#endif
1958
1959
#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR
1960
size_t ZSTD_compressBlock_btlazy2(
1961
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1962
        void const* src, size_t srcSize)
1963
457k
{
1964
457k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict);
1965
457k
}
1966
1967
size_t ZSTD_compressBlock_btlazy2_dictMatchState(
1968
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
1969
        void const* src, size_t srcSize)
1970
19.0k
{
1971
19.0k
    return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState);
1972
19.0k
}
1973
#endif
1974
1975
#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \
1976
 || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \
1977
 || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \
1978
 || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR)
1979
FORCE_INLINE_TEMPLATE
1980
ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
1981
size_t ZSTD_compressBlock_lazy_extDict_generic(
1982
                        ZSTD_MatchState_t* ms, SeqStore_t* seqStore,
1983
                        U32 rep[ZSTD_REP_NUM],
1984
                        const void* src, size_t srcSize,
1985
                        const searchMethod_e searchMethod, const U32 depth)
1986
742k
{
1987
742k
    const BYTE* const istart = (const BYTE*)src;
1988
742k
    const BYTE* ip = istart;
1989
742k
    const BYTE* anchor = istart;
1990
742k
    const BYTE* const iend = istart + srcSize;
1991
742k
    const BYTE* const ilimit = searchMethod == search_rowHash ? iend - 8 - ZSTD_ROW_HASH_CACHE_SIZE : iend - 8;
1992
742k
    const BYTE* const base = ms->window.base;
1993
742k
    const U32 dictLimit = ms->window.dictLimit;
1994
742k
    const BYTE* const prefixStart = base + dictLimit;
1995
742k
    const BYTE* const dictBase = ms->window.dictBase;
1996
742k
    const BYTE* const dictEnd  = dictBase + dictLimit;
1997
742k
    const BYTE* const dictStart  = dictBase + ms->window.lowLimit;
1998
742k
    const U32 windowLog = ms->cParams.windowLog;
1999
742k
    const U32 mls = BOUNDED(4, ms->cParams.minMatch, 6);
2000
742k
    const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6);
2001
2002
742k
    U32 offset_1 = rep[0], offset_2 = rep[1];
2003
2004
742k
    DEBUGLOG(5, "ZSTD_compressBlock_lazy_extDict_generic (searchFunc=%u)", (U32)searchMethod);
2005
2006
    /* Reset the lazy skipping state */
2007
742k
    ms->lazySkipping = 0;
2008
2009
    /* init */
2010
742k
    ip += (ip == prefixStart);
2011
742k
    if (searchMethod == search_rowHash) {
2012
492k
        ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
2013
492k
    }
2014
2015
    /* Match Loop */
2016
742k
#if defined(__GNUC__) && defined(__x86_64__)
2017
    /* I've measured random a 5% speed loss on levels 5 & 6 (greedy) when the
2018
     * code alignment is perturbed. To fix the instability align the loop on 32-bytes.
2019
     */
2020
742k
    __asm__(".p2align 5");
2021
742k
#endif
2022
55.5M
    while (ip < ilimit) {
2023
54.8M
        size_t matchLength=0;
2024
109M
        size_t offBase = REPCODE1_TO_OFFBASE;
2025
109M
        const BYTE* start=ip+1;
2026
109M
        U32 curr = (U32)(ip-base);
2027
2028
        /* check repCode */
2029
109M
        {   const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr+1, windowLog);
2030
109M
            const U32 repIndex = (U32)(curr+1 - offset_1);
2031
109M
            const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
2032
109M
            const BYTE* const repMatch = repBase + repIndex;
2033
109M
            if ( (ZSTD_index_overlap_check(dictLimit, repIndex))
2034
54.8M
               & (offset_1 <= curr+1 - windowLow) ) /* note: we are searching at curr+1 */
2035
54.6M
            if (MEM_read32(ip+1) == MEM_read32(repMatch)) {
2036
                /* repcode detected we should take it */
2037
2.39M
                const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
2038
2.39M
                matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repEnd, prefixStart) + 4;
2039
2.39M
                if (depth==0) goto _storeSequence;
2040
2.39M
        }   }
2041
2042
        /* first search (depth 0) */
2043
54.3M
        {   size_t ofbCandidate = 999999999;
2044
54.3M
            size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
2045
54.3M
            if (ml2 > matchLength)
2046
47.7M
                matchLength = ml2, start = ip, offBase = ofbCandidate;
2047
54.3M
        }
2048
2049
54.3M
        if (matchLength < 4) {
2050
48.5M
            size_t const step = ((size_t)(ip-anchor) >> kSearchStrength);
2051
48.5M
            ip += step + 1;   /* jump faster over incompressible sections */
2052
            /* Enter the lazy skipping mode once we are skipping more than 8 bytes at a time.
2053
             * In this mode we stop inserting every position into our tables, and only insert
2054
             * positions that we search, which is one in step positions.
2055
             * The exact cutoff is flexible, I've just chosen a number that is reasonably high,
2056
             * so we minimize the compression ratio loss in "normal" scenarios. This mode gets
2057
             * triggered once we've gone 2KB without finding any matches.
2058
             */
2059
48.5M
            ms->lazySkipping = step > kLazySkippingStep;
2060
48.5M
            continue;
2061
48.5M
        }
2062
2063
        /* let's try to find a better solution */
2064
5.82M
        if (depth>=1)
2065
5.45M
        while (ip<ilimit) {
2066
5.45M
            ip ++;
2067
5.45M
            curr++;
2068
            /* check repCode */
2069
5.45M
            if (offBase) {
2070
5.45M
                const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr, windowLog);
2071
5.45M
                const U32 repIndex = (U32)(curr - offset_1);
2072
5.45M
                const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
2073
5.45M
                const BYTE* const repMatch = repBase + repIndex;
2074
5.45M
                if ( (ZSTD_index_overlap_check(dictLimit, repIndex))
2075
5.45M
                   & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
2076
5.44M
                if (MEM_read32(ip) == MEM_read32(repMatch)) {
2077
                    /* repcode detected */
2078
2.04M
                    const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
2079
2.04M
                    size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
2080
2.04M
                    int const gain2 = (int)(repLength * 3);
2081
2.04M
                    int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offBase) + 1);
2082
2.04M
                    if ((repLength >= 4) && (gain2 > gain1))
2083
492k
                        matchLength = repLength, offBase = REPCODE1_TO_OFFBASE, start = ip;
2084
2.04M
            }   }
2085
2086
            /* search match, depth 1 */
2087
5.45M
            {   size_t ofbCandidate = 999999999;
2088
5.45M
                size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
2089
5.45M
                int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate));   /* raw approx */
2090
5.45M
                int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 4);
2091
5.45M
                if ((ml2 >= 4) && (gain2 > gain1)) {
2092
439k
                    matchLength = ml2, offBase = ofbCandidate, start = ip;
2093
439k
                    continue;   /* search a better one */
2094
439k
            }   }
2095
2096
            /* let's find an even better one */
2097
5.01M
            if ((depth==2) && (ip<ilimit)) {
2098
2.84M
                ip ++;
2099
2.84M
                curr++;
2100
                /* check repCode */
2101
2.84M
                if (offBase) {
2102
2.84M
                    const U32 windowLow = ZSTD_getLowestMatchIndex(ms, curr, windowLog);
2103
2.84M
                    const U32 repIndex = (U32)(curr - offset_1);
2104
2.84M
                    const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
2105
2.84M
                    const BYTE* const repMatch = repBase + repIndex;
2106
2.84M
                    if ( (ZSTD_index_overlap_check(dictLimit, repIndex))
2107
2.84M
                       & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
2108
2.84M
                    if (MEM_read32(ip) == MEM_read32(repMatch)) {
2109
                        /* repcode detected */
2110
818k
                        const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
2111
818k
                        size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
2112
818k
                        int const gain2 = (int)(repLength * 4);
2113
818k
                        int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 1);
2114
818k
                        if ((repLength >= 4) && (gain2 > gain1))
2115
119k
                            matchLength = repLength, offBase = REPCODE1_TO_OFFBASE, start = ip;
2116
818k
                }   }
2117
2118
                /* search match, depth 2 */
2119
2.84M
                {   size_t ofbCandidate = 999999999;
2120
2.84M
                    size_t const ml2 = ZSTD_searchMax(ms, ip, iend, &ofbCandidate, mls, rowLog, searchMethod, ZSTD_extDict);
2121
2.84M
                    int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)ofbCandidate));   /* raw approx */
2122
2.84M
                    int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offBase) + 7);
2123
2.84M
                    if ((ml2 >= 4) && (gain2 > gain1)) {
2124
79.8k
                        matchLength = ml2, offBase = ofbCandidate, start = ip;
2125
79.8k
                        continue;
2126
79.8k
            }   }   }
2127
4.93M
            break;  /* nothing found : store previous solution */
2128
5.01M
        }
2129
2130
        /* catch up */
2131
5.82M
        if (OFFBASE_IS_OFFSET(offBase)) {
2132
4.04M
            U32 const matchIndex = (U32)((size_t)(start-base) - OFFBASE_TO_OFFSET(offBase));
2133
4.04M
            const BYTE* match = (matchIndex < dictLimit) ? dictBase + matchIndex : base + matchIndex;
2134
4.04M
            const BYTE* const mStart = (matchIndex < dictLimit) ? dictStart : prefixStart;
2135
4.58M
            while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; }  /* catch up */
2136
4.04M
            offset_2 = offset_1; offset_1 = (U32)OFFBASE_TO_OFFSET(offBase);
2137
4.04M
        }
2138
2139
        /* store sequence */
2140
6.28M
_storeSequence:
2141
6.28M
        {   size_t const litLength = (size_t)(start - anchor);
2142
6.28M
            ZSTD_storeSeq(seqStore, litLength, anchor, iend, (U32)offBase, matchLength);
2143
6.28M
            anchor = ip = start + matchLength;
2144
6.28M
        }
2145
6.28M
        if (ms->lazySkipping) {
2146
            /* We've found a match, disable lazy skipping mode, and refill the hash cache. */
2147
3.37k
            if (searchMethod == search_rowHash) {
2148
2.48k
                ZSTD_row_fillHashCache(ms, base, rowLog, mls, ms->nextToUpdate, ilimit);
2149
2.48k
            }
2150
3.37k
            ms->lazySkipping = 0;
2151
3.37k
        }
2152
2153
        /* check immediate repcode */
2154
6.65M
        while (ip <= ilimit) {
2155
6.45M
            const U32 repCurrent = (U32)(ip-base);
2156
6.45M
            const U32 windowLow = ZSTD_getLowestMatchIndex(ms, repCurrent, windowLog);
2157
6.45M
            const U32 repIndex = repCurrent - offset_2;
2158
6.45M
            const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
2159
6.45M
            const BYTE* const repMatch = repBase + repIndex;
2160
6.45M
            if ( (ZSTD_index_overlap_check(dictLimit, repIndex))
2161
6.45M
               & (offset_2 <= repCurrent - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */
2162
6.44M
            if (MEM_read32(ip) == MEM_read32(repMatch)) {
2163
                /* repcode detected we should take it */
2164
368k
                const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
2165
368k
                matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
2166
368k
                offBase = offset_2; offset_2 = offset_1; offset_1 = (U32)offBase;   /* swap offset history */
2167
368k
                ZSTD_storeSeq(seqStore, 0, anchor, iend, REPCODE1_TO_OFFBASE, matchLength);
2168
368k
                ip += matchLength;
2169
368k
                anchor = ip;
2170
368k
                continue;   /* faster when present ... (?) */
2171
368k
            }
2172
6.08M
            break;
2173
6.45M
    }   }
2174
2175
    /* Save reps for next block */
2176
742k
    rep[0] = offset_1;
2177
742k
    rep[1] = offset_2;
2178
2179
    /* Return the last literals size */
2180
742k
    return (size_t)(iend - anchor);
2181
742k
}
2182
#endif /* build exclusions */
2183
2184
#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR
2185
size_t ZSTD_compressBlock_greedy_extDict(
2186
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2187
        void const* src, size_t srcSize)
2188
37.5k
{
2189
37.5k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0);
2190
37.5k
}
2191
2192
size_t ZSTD_compressBlock_greedy_extDict_row(
2193
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2194
        void const* src, size_t srcSize)
2195
96.7k
{
2196
96.7k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0);
2197
96.7k
}
2198
#endif
2199
2200
#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR
2201
size_t ZSTD_compressBlock_lazy_extDict(
2202
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2203
        void const* src, size_t srcSize)
2204
2205
77.2k
{
2206
77.2k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1);
2207
77.2k
}
2208
2209
size_t ZSTD_compressBlock_lazy_extDict_row(
2210
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2211
        void const* src, size_t srcSize)
2212
2213
183k
{
2214
183k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1);
2215
183k
}
2216
#endif
2217
2218
#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR
2219
size_t ZSTD_compressBlock_lazy2_extDict(
2220
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2221
        void const* src, size_t srcSize)
2222
2223
77.8k
{
2224
77.8k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2);
2225
77.8k
}
2226
2227
size_t ZSTD_compressBlock_lazy2_extDict_row(
2228
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2229
        void const* src, size_t srcSize)
2230
211k
{
2231
211k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2);
2232
211k
}
2233
#endif
2234
2235
#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR
2236
size_t ZSTD_compressBlock_btlazy2_extDict(
2237
        ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
2238
        void const* src, size_t srcSize)
2239
2240
58.0k
{
2241
58.0k
    return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2);
2242
58.0k
}
2243
#endif