math/mpreduce.[ch]: Extend the domain to all positive integers.
[u/mdw/catacomb] / math / mpreduce.c
CommitLineData
f46efa79 1/* -*-c-*-
2 *
f46efa79 3 * Efficient reduction modulo nice primes
4 *
5 * (c) 2004 Straylight/Edgeware
6 */
7
45c0fd36 8/*----- Licensing notice --------------------------------------------------*
f46efa79 9 *
10 * This file is part of Catacomb.
11 *
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
45c0fd36 16 *
f46efa79 17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
45c0fd36 21 *
f46efa79 22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25 * MA 02111-1307, USA.
26 */
27
f46efa79 28/*----- Header files ------------------------------------------------------*/
29
30#include <mLib/darray.h>
31#include <mLib/macros.h>
32
33#include "mp.h"
34#include "mpreduce.h"
35#include "mpreduce-exp.h"
36
37/*----- Data structures ---------------------------------------------------*/
38
39DA_DECL(instr_v, mpreduce_instr);
40
21f82da4
MW
41/*----- Theory ------------------------------------------------------------*
42 *
43 * We're given a modulus %$p = 2^n - d$%, where %$d < 2^n$%, and some %$x$%,
44 * and we want to compute %$x \bmod p$%. We work in base %$2^w$%, for some
45 * appropriate %$w$%. The important observation is that
46 * %$d \equiv 2^n \pmod p$%.
47 *
48 * Suppose %$x = x' + z 2^k$%, where %$k \ge n$%; then
49 * %$x \equiv x' + d z 2^{k-n} \pmod p$%. We can use this to trim the
50 * representation of %$x$%; each time, we reduce %$x$% by a mutliple of
51 * %$2^{k-n} p$%. We can do this in two passes: firstly by taking whole
52 * words off the top, and then (if necessary) by trimming the top word.
53 * Finally, if %$p \le x < 2^n$% then %$0 \le x - p < p$% and we're done.
54 *
55 * A common trick, apparently, is to choose %$d$% such that it has a very
56 * sparse non-adjacent form, and, moreover, that this form is nicely aligned
57 * with common word sizes. (That is, write %$d = \sum_{0\le i<m} d_i 2^i$%,
58 * with %$d_i \in \{ -1, 0, +1 \}$% and most %$d_i = 0$%.) Then adding
59 * %$z d$% is a matter of adding and subtracting appropriately shifted copies
60 * of %$z$%.
61 *
62 * Most libraries come with hardwired code for doing this for a few
63 * well-known values of %$p$%. We take a different approach, for two
64 * reasons.
65 *
66 * * Firstly, it privileges built-in numbers over user-selected ones, even
67 * if the latter have the right (or better) properties.
68 *
69 * * Secondly, writing appropriately optimized reduction functions when we
70 * don't know the exact characteristics of the target machine is rather
71 * difficult.
72 *
73 * Our solution, then, is to `compile' the value %$p$% at runtime, into a
74 * sequence of simple instructions for doing the reduction.
75 */
76
f46efa79 77/*----- Main code ---------------------------------------------------------*/
78
79/* --- @mpreduce_create@ --- *
80 *
81 * Arguments: @gfreduce *r@ = structure to fill in
82 * @mp *x@ = an integer
83 *
30d09778
MW
84 * Returns: Zero if successful; nonzero on failure. The current
85 * algorithm always succeeds when given positive @x@. Earlier
86 * versions used to fail on particular kinds of integers, but
87 * this is guaranteed not to happen any more.
f46efa79 88 *
89 * Use: Initializes a context structure for reduction.
90 */
91
f4535c64 92int mpreduce_create(mpreduce *r, mp *p)
f46efa79 93{
94 mpscan sc;
95 enum { Z = 0, Z1 = 2, X = 4, X0 = 6 };
96 unsigned st = Z;
97 instr_v iv = DA_INIT;
98 unsigned long d, i;
99 unsigned op;
c29970a7 100 size_t w, b, bb;
f46efa79 101
102 /* --- Fill in the easy stuff --- */
103
f4535c64 104 if (!MP_POSP(p))
105 return (-1);
f46efa79 106 d = mp_bits(p);
107 r->lim = d/MPW_BITS;
108 r->s = d%MPW_BITS;
109 if (r->s)
110 r->lim++;
111 r->p = mp_copy(p);
112
113 /* --- Stash a new instruction --- */
114
115#define INSTR(op_, argx_, argy_) do { \
116 DA_ENSURE(&iv, 1); \
117 DA(&iv)[DA_LEN(&iv)].op = (op_); \
118 DA(&iv)[DA_LEN(&iv)].argx = (argx_); \
119 DA(&iv)[DA_LEN(&iv)].argy = (argy_); \
120 DA_EXTEND(&iv, 1); \
121} while (0)
122
123 /* --- Main loop --- *
124 *
125 * A simple state machine decomposes @p@ conveniently into positive and
21f82da4
MW
126 * negative powers of 2.
127 *
128 * Here's the relevant theory. The important observation is that
129 * %$2^i = 2^{i+1} - 2^i$%, and hence
130 *
131 * * %$\sum_{a\le i<b} 2^i = 2^b - 2^a$%, and
132 *
133 * * %$2^c - 2^{b+1} + 2^b - 2^a = 2^c - 2^b - 2^a$%.
134 *
135 * The first of these gives us a way of combining a run of several one
136 * bits, and the second gives us a way of handling a single-bit
137 * interruption in such a run.
138 *
139 * We start with a number %$p = \sum_{0\le i<n} p_i 2^i$%, and scan
140 * right-to-left using a simple state-machine keeping (approximate) track
141 * of the two previous bits. The @Z@ states denote that we're in a string
142 * of zeros; @Z1@ means that we just saw a 1 bit after a sequence of zeros.
143 * Similarly, the @X@ states denote that we're in a string of ones; and
144 * @X0@ means that we just saw a zero bit after a sequence of ones. The
145 * state machine lets us delay decisions about what to do when we've seen a
146 * change to the status quo (a one after a run of zeros, or vice-versa)
147 * until we've seen the next bit, so we can tell whether this is an
148 * isolated bit or the start of a new sequence.
149 *
150 * More formally: we define two functions %$Z^b_i$% and %$X^b_i$% as
151 * follows.
152 *
153 * * %$Z^0_i(S, 0) = S$%
154 * * %$Z^0_i(S, n) = Z^0_{i+1}(S, n)$%
155 * * %$Z^0_i(S, n + 2^i) = Z^1_{i+1}(S, n)$%
156 * * %$Z^1_i(S, n) = Z^0_{i+1}(S \cup \{ 2^{i-1} \}, n)$%
157 * * %$Z^1_i(S, n + 2^i) = X^1_{i+1}(S \cup \{ -2^{i-1} \}, n)$%
158 * * %$X^0_i(S, n) = Z^0_{i+1}(S, \{ 2^{i-1} \})$%
159 * * %$X^0_i(S, n + 2^i) = X^1_{i+1}(S \cup \{ -2^{i-1} \}, n)$%
160 * * %$X^1_i(S, n) = X^0_{i+1}(S, n)$%
161 * * %$X^1_i(S, n + 2^i) = X^1_{i+1}(S, n)$%
162 *
163 * The reader may verify (by induction on %$n$%) that the following
164 * properties hold.
165 *
166 * * %$Z^0_0(\emptyset, n)$% is well-defined for all %$n \ge 0$%
167 * * %$\sum Z^b_i(S, n) = \sum S + n + b 2^{i-1}$%
168 * * %$\sum X^b_i(S, n) = \sum S + n + (b + 1) 2^{i-1}$%
169 *
170 * From these, of course, we can deduce %$\sum Z^0_0(\emptyset, n) = n$%.
171 *
172 * We apply the above recurrence to build a simple instruction sequence for
173 * adding an appropriate multiple of %$d$% to a given number. Suppose that
174 * %$2^{w(N-1)} \le 2^{n-1} \le p < 2^n \le 2^{wN}$%. The machine which
175 * interprets these instructions does so in the context of a
176 * single-precision multiplicand @z@ and a pointer @v@ to the
177 * %%\emph{most}%% significant word of an %$N + 1$%-word integer, and the
178 * instruction sequence should add %$z d$% to this integer.
179 *
180 * The available instructions are named @MPRI_{ADD,SUB}{,LSL}@; they add
181 * (or subtract) %$z$% (shifted left by some amount, in the @LSL@ variants)
182 * to some word earlier than @v@. The relevant quantities are encoded in
183 * the instruction's immediate operands.
f46efa79 184 */
185
c29970a7 186 bb = MPW_BITS - (d + 1)%MPW_BITS;
bccb92dd 187 for (i = 0, mp_scan(&sc, p); i < d && mp_step(&sc); i++) {
f46efa79 188 switch (st | mp_bit(&sc)) {
189 case Z | 1: st = Z1; break;
45c0fd36
MW
190 case Z1 | 0: st = Z; op = MPRI_SUB; goto instr;
191 case Z1 | 1: st = X; op = MPRI_ADD; goto instr;
f46efa79 192 case X | 0: st = X0; break;
45c0fd36
MW
193 case X0 | 1: st = X; op = MPRI_ADD; goto instr;
194 case X0 | 0: st = Z; op = MPRI_SUB; goto instr;
f46efa79 195 instr:
196 w = (d - i)/MPW_BITS + 1;
c29970a7 197 b = (bb + i)%MPW_BITS;
f46efa79 198 INSTR(op | !!b, w, b);
199 }
200 }
21f82da4 201
30d09778
MW
202 /* --- Fix up wrong-sided decompositions --- *
203 *
204 * At this point, we haven't actually finished up the state machine
205 * properly. We stopped scanning just after bit %$n - 1$% -- the most
206 * significant one, which we know in advance must be set (since @x@ is
207 * strictly positive). Therefore we are either in state @X@ or @Z1@. In
208 * the former case, we have nothing to do. In the latter, there are two
209 * subcases to deal with. If there are no other instructions, then @x@ is
210 * a perfect power of two, and %$d = 0$%, so again there is nothing to do.
211 *
212 * In the remaining case, we have decomposed @x@ as %$2^{n-1} + d$%, for
213 * some positive %$d%, which is unfortuante: if we're asked to reduce
214 * %$2^n$%, say, we'll end up with %$-d$% (or would do, if we weren't
215 * sticking to unsigned arithmetic for good performance). So instead, we
216 * rewrite this as %$2^n - 2^{n-1} + d$% and everything will be good.
21f82da4
MW
217 */
218
30d09778
MW
219 if (st == Z1 && DA_LEN(&iv)) {
220 w = 1;
221 b = (bb + d)%MPW_BITS;
222 INSTR(MPRI_ADD | !!b, w, b);
f46efa79 223 }
224
225#undef INSTR
226
21f82da4
MW
227 /* --- Wrap up --- *
228 *
229 * Store the generated instruction sequence in our context structure. If
230 * %$p$%'s bit length %$n$% is a multiple of the word size %$w$% then
231 * there's nothing much else to do here. Otherwise, we have an additional
232 * job.
233 *
234 * The reduction operation has three phases. The first trims entire words
235 * from the argument, and the instruction sequence constructed above does
236 * this well; the second phase reduces an integer which has the same number
237 * of words as %$p$%, but strictly more bits. (The third phase is a single
238 * conditional subtraction of %$p$%, in case the argument is the same bit
239 * length as %$p$% but greater; this doesn't concern us here.) To handle
240 * the second phase, we create another copy of the instruction stream, with
241 * all of the target shifts adjusted upwards by %$s = n \bmod w$%.
242 *
243 * In this case, we are acting on an %$(N - 1)$%-word operand, and so
244 * (given the remarks above) must check that this is still valid, but a
245 * moment's reflection shows that this must be fine: the most distant
246 * target must be the bit %$s$% from the top of the least-significant word;
247 * but since we shift all of the targets up by %$s$%, this now addresses
248 * the bottom bit of the next most significant word, and there is no
249 * underflow.
250 */
f46efa79 251
252 r->in = DA_LEN(&iv);
cd9aae84
MW
253 if (!r->in)
254 r->iv = 0;
255 else if (!r->s) {
f46efa79 256 r->iv = xmalloc(r->in * sizeof(mpreduce_instr));
257 memcpy(r->iv, DA(&iv), r->in * sizeof(mpreduce_instr));
258 } else {
259 r->iv = xmalloc(r->in * 2 * sizeof(mpreduce_instr));
260 for (i = 0; i < r->in; i++) {
261 r->iv[i] = DA(&iv)[i];
262 op = r->iv[i].op & ~1u;
263 w = r->iv[i].argx;
264 b = r->iv[i].argy;
265 b += r->s;
266 if (b >= MPW_BITS) {
267 b -= MPW_BITS;
268 w--;
269 }
270 if (b) op |= 1;
271 r->iv[i + r->in].op = op;
272 r->iv[i + r->in].argx = w;
273 r->iv[i + r->in].argy = b;
274 }
275 }
f4535c64 276 DA_DESTROY(&iv);
c29970a7 277
f4535c64 278 return (0);
f46efa79 279}
280
281/* --- @mpreduce_destroy@ --- *
282 *
283 * Arguments: @mpreduce *r@ = structure to free
284 *
285 * Returns: ---
286 *
287 * Use: Reclaims the resources from a reduction context.
288 */
289
290void mpreduce_destroy(mpreduce *r)
291{
292 mp_drop(r->p);
cd9aae84 293 if (r->iv) xfree(r->iv);
f46efa79 294}
295
296/* --- @mpreduce_dump@ --- *
297 *
298 * Arguments: @mpreduce *r@ = structure to dump
299 * @FILE *fp@ = file to dump on
300 *
301 * Returns: ---
302 *
303 * Use: Dumps a reduction context.
304 */
305
306void mpreduce_dump(mpreduce *r, FILE *fp)
307{
308 size_t i;
309 static const char *opname[] = { "add", "addshift", "sub", "subshift" };
310
311 fprintf(fp, "mod = "); mp_writefile(r->p, fp, 16);
312 fprintf(fp, "\n lim = %lu; s = %d\n", (unsigned long)r->lim, r->s);
313 for (i = 0; i < r->in; i++) {
314 assert(r->iv[i].op < N(opname));
315 fprintf(fp, " %s %lu %lu\n",
316 opname[r->iv[i].op],
317 (unsigned long)r->iv[i].argx,
318 (unsigned long)r->iv[i].argy);
319 }
320 if (r->s) {
321 fprintf(fp, "tail end charlie\n");
322 for (i = r->in; i < 2 * r->in; i++) {
323 assert(r->iv[i].op < N(opname));
324 fprintf(fp, " %s %lu %lu\n",
325 opname[r->iv[i].op],
326 (unsigned long)r->iv[i].argx,
327 (unsigned long)r->iv[i].argy);
328 }
329 }
330}
331
332/* --- @mpreduce_do@ --- *
333 *
334 * Arguments: @mpreduce *r@ = reduction context
335 * @mp *d@ = destination
336 * @mp *x@ = source
337 *
338 * Returns: Destination, @x@ reduced modulo the reduction poly.
339 */
340
341static void run(const mpreduce_instr *i, const mpreduce_instr *il,
342 mpw *v, mpw z)
343{
344 for (; i < il; i++) {
f46efa79 345 switch (i->op) {
346 case MPRI_ADD: MPX_UADDN(v - i->argx, v + 1, z); break;
347 case MPRI_ADDLSL: mpx_uaddnlsl(v - i->argx, v + 1, z, i->argy); break;
348 case MPRI_SUB: MPX_USUBN(v - i->argx, v + 1, z); break;
349 case MPRI_SUBLSL: mpx_usubnlsl(v - i->argx, v + 1, z, i->argy); break;
350 default:
351 abort();
352 }
f46efa79 353 }
354}
355
356mp *mpreduce_do(mpreduce *r, mp *d, mp *x)
357{
358 mpw *v, *vl;
359 const mpreduce_instr *il;
360 mpw z;
361
f46efa79 362 /* --- If source is negative, divide --- */
363
a69a3efd 364 if (MP_NEGP(x)) {
f46efa79 365 mp_div(0, &d, x, r->p);
366 return (d);
367 }
368
369 /* --- Try to reuse the source's space --- */
370
371 MP_COPY(x);
372 if (d) MP_DROP(d);
373 MP_DEST(x, MP_LEN(x), x->f);
374
21f82da4 375 /* --- Stage one: trim excess words from the most significant end --- */
f46efa79 376
f46efa79 377 il = r->iv + r->in;
378 if (MP_LEN(x) >= r->lim) {
379 v = x->v + r->lim;
380 vl = x->vl;
381 while (vl-- > v) {
382 while (*vl) {
383 z = *vl;
384 *vl = 0;
385 run(r->iv, il, vl, z);
f46efa79 386 }
387 }
21f82da4
MW
388
389 /* --- Stage two: trim excess bits from the most significant word --- */
390
f46efa79 391 if (r->s) {
392 while (*vl >> r->s) {
393 z = *vl >> r->s;
394 *vl &= ((1 << r->s) - 1);
395 run(r->iv + r->in, il + r->in, vl, z);
f46efa79 396 }
397 }
398 }
399
21f82da4 400 /* --- Stage three: conditional subtraction --- */
f46efa79 401
402 MP_SHRINK(x);
403 if (MP_CMP(x, >=, r->p))
404 x = mp_sub(x, x, r->p);
405
406 /* --- Done --- */
407
f46efa79 408 return (x);
409}
410
411/* --- @mpreduce_exp@ --- *
412 *
413 * Arguments: @mpreduce *mr@ = pointer to reduction context
45c0fd36
MW
414 * @mp *d@ = fake destination
415 * @mp *a@ = base
416 * @mp *e@ = exponent
f46efa79 417 *
45c0fd36 418 * Returns: Result, %$a^e \bmod m$%.
f46efa79 419 */
420
421mp *mpreduce_exp(mpreduce *mr, mp *d, mp *a, mp *e)
422{
423 mp *x = MP_ONE;
424 mp *spare = (e->f & MP_BURN) ? MP_NEWSEC : MP_NEW;
425
426 MP_SHRINK(e);
a69a3efd 427 MP_COPY(a);
428 if (MP_ZEROP(e))
f46efa79 429 ;
a69a3efd 430 else {
431 if (MP_NEGP(e))
432 a = mp_modinv(a, a, mr->p);
433 if (MP_LEN(e) < EXP_THRESH)
434 EXP_SIMPLE(x, a, e);
435 else
436 EXP_WINDOW(x, a, e);
437 }
438 mp_drop(a);
f46efa79 439 mp_drop(d);
440 mp_drop(spare);
441 return (x);
442}
443
444/*----- Test rig ----------------------------------------------------------*/
445
446
447#ifdef TEST_RIG
448
449#define MP(x) mp_readstring(MP_NEW, #x, 0, 0)
450
451static int vreduce(dstr *v)
452{
453 mp *d = *(mp **)v[0].buf;
454 mp *n = *(mp **)v[1].buf;
455 mp *r = *(mp **)v[2].buf;
456 mp *c;
457 int ok = 1;
458 mpreduce rr;
459
460 mpreduce_create(&rr, d);
461 c = mpreduce_do(&rr, MP_NEW, n);
462 if (!MP_EQ(c, r)) {
463 fprintf(stderr, "\n*** reduction failed\n*** ");
464 mpreduce_dump(&rr, stderr);
465 fprintf(stderr, "\n*** n = "); mp_writefile(n, stderr, 10);
466 fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
467 fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
468 fprintf(stderr, "\n");
469 ok = 0;
470 }
471 mpreduce_destroy(&rr);
472 mp_drop(n); mp_drop(d); mp_drop(r); mp_drop(c);
473 assert(mparena_count(MPARENA_GLOBAL) == 0);
474 return (ok);
475}
476
477static int vmodexp(dstr *v)
478{
479 mp *p = *(mp **)v[0].buf;
480 mp *g = *(mp **)v[1].buf;
481 mp *x = *(mp **)v[2].buf;
482 mp *r = *(mp **)v[3].buf;
483 mp *c;
484 int ok = 1;
485 mpreduce rr;
486
487 mpreduce_create(&rr, p);
488 c = mpreduce_exp(&rr, MP_NEW, g, x);
489 if (!MP_EQ(c, r)) {
490 fprintf(stderr, "\n*** modexp failed\n*** ");
491 fprintf(stderr, "\n*** p = "); mp_writefile(p, stderr, 10);
492 fprintf(stderr, "\n*** g = "); mp_writefile(g, stderr, 10);
493 fprintf(stderr, "\n*** x = "); mp_writefile(x, stderr, 10);
494 fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
495 fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
496 fprintf(stderr, "\n");
497 ok = 0;
498 }
499 mpreduce_destroy(&rr);
500 mp_drop(p); mp_drop(g); mp_drop(r); mp_drop(x); mp_drop(c);
501 assert(mparena_count(MPARENA_GLOBAL) == 0);
502 return (ok);
503}
504
505static test_chunk defs[] = {
506 { "reduce", vreduce, { &type_mp, &type_mp, &type_mp, 0 } },
507 { "modexp", vmodexp, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
508 { 0, 0, { 0 } }
509};
510
511int main(int argc, char *argv[])
512{
0f00dc4c 513 test_run(argc, argv, defs, SRCDIR"/t/mpreduce");
f46efa79 514 return (0);
515}
516
517#endif
518
519/*----- That's all, folks -------------------------------------------------*/