chiark / gitweb /
Implement efficient reduction for pleasant-looking primes.
[catacomb] / mpreduce.c
CommitLineData
f46efa79 1/* -*-c-*-
2 *
3 * $Id: mpreduce.c,v 1.1 2004/03/27 00:04:46 mdw Exp $
4 *
5 * Efficient reduction modulo nice primes
6 *
7 * (c) 2004 Straylight/Edgeware
8 */
9
10/*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Catacomb.
13 *
14 * Catacomb is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
18 *
19 * Catacomb is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
23 *
24 * You should have received a copy of the GNU Library General Public
25 * License along with Catacomb; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27 * MA 02111-1307, USA.
28 */
29
30/*----- Revision history --------------------------------------------------*
31 *
32 * $Log: mpreduce.c,v $
33 * Revision 1.1 2004/03/27 00:04:46 mdw
34 * Implement efficient reduction for pleasant-looking primes.
35 *
36 */
37
38/*----- Header files ------------------------------------------------------*/
39
40#include <mLib/darray.h>
41#include <mLib/macros.h>
42
43#include "mp.h"
44#include "mpreduce.h"
45#include "mpreduce-exp.h"
46
47/*----- Data structures ---------------------------------------------------*/
48
49DA_DECL(instr_v, mpreduce_instr);
50
51/*----- Main code ---------------------------------------------------------*/
52
53/* --- @mpreduce_create@ --- *
54 *
55 * Arguments: @gfreduce *r@ = structure to fill in
56 * @mp *x@ = an integer
57 *
58 * Returns: ---
59 *
60 * Use: Initializes a context structure for reduction.
61 */
62
63void mpreduce_create(mpreduce *r, mp *p)
64{
65 mpscan sc;
66 enum { Z = 0, Z1 = 2, X = 4, X0 = 6 };
67 unsigned st = Z;
68 instr_v iv = DA_INIT;
69 unsigned long d, i;
70 unsigned op;
71 size_t w, b;
72
73 /* --- Fill in the easy stuff --- */
74
75 assert(MP_ISPOS(p));
76 d = mp_bits(p);
77 r->lim = d/MPW_BITS;
78 r->s = d%MPW_BITS;
79 if (r->s)
80 r->lim++;
81 r->p = mp_copy(p);
82
83 /* --- Stash a new instruction --- */
84
85#define INSTR(op_, argx_, argy_) do { \
86 DA_ENSURE(&iv, 1); \
87 DA(&iv)[DA_LEN(&iv)].op = (op_); \
88 DA(&iv)[DA_LEN(&iv)].argx = (argx_); \
89 DA(&iv)[DA_LEN(&iv)].argy = (argy_); \
90 DA_EXTEND(&iv, 1); \
91} while (0)
92
93 /* --- Main loop --- *
94 *
95 * A simple state machine decomposes @p@ conveniently into positive and
96 * negative powers of 2. The pure form of the state machine is left below
97 * for reference (and in case I need inspiration for a NAF exponentiator).
98 */
99
100#ifdef DEBUG
101 for (i = 0, mp_scan(&sc, p); mp_step(&sc); i++) {
102 switch (st | mp_bit(&sc)) {
103 case Z | 1: st = Z1; break;
104 case Z1 | 0: st = Z; printf("+ %lu\n", i - 1); break;
105 case Z1 | 1: st = X; printf("- %lu\n", i - 1); break;
106 case X | 0: st = X0; break;
107 case X0 | 1: st = X; printf("- %lu\n", i - 1); break;
108 case X0 | 0: st = Z; printf("+ %lu\n", i - 1); break;
109 }
110 }
111 if (st >= X) printf("+ %lu\n", i);
112#endif
113
114 for (i = 0, mp_scan(&sc, p); i < d - 1 && mp_step(&sc); i++) {
115 switch (st | mp_bit(&sc)) {
116 case Z | 1: st = Z1; break;
117 case Z1 | 0: st = Z; op = MPRI_SUB; goto instr;
118 case Z1 | 1: st = X; op = MPRI_ADD; goto instr;
119 case X | 0: st = X0; break;
120 case X0 | 1: st = X; op = MPRI_ADD; goto instr;
121 case X0 | 0: st = Z; op = MPRI_SUB; goto instr;
122 instr:
123 w = (d - i)/MPW_BITS + 1;
124 b = (MPW_BITS + i - d - 1)%MPW_BITS;
125 INSTR(op | !!b, w, b);
126 }
127 }
128 if ((DA(&iv)[DA_LEN(&iv) - 1].op & ~1u) == MPRI_SUB) {
129 fprintf(stderr,
130 "mpreduce can't handle moduli of the form 2^m + x\n");
131 abort();
132 }
133
134#undef INSTR
135
136 /* --- Wrap up --- */
137
138 r->in = DA_LEN(&iv);
139 if (!r->s) {
140 r->iv = xmalloc(r->in * sizeof(mpreduce_instr));
141 memcpy(r->iv, DA(&iv), r->in * sizeof(mpreduce_instr));
142 } else {
143 r->iv = xmalloc(r->in * 2 * sizeof(mpreduce_instr));
144 for (i = 0; i < r->in; i++) {
145 r->iv[i] = DA(&iv)[i];
146 op = r->iv[i].op & ~1u;
147 w = r->iv[i].argx;
148 b = r->iv[i].argy;
149 b += r->s;
150 if (b >= MPW_BITS) {
151 b -= MPW_BITS;
152 w--;
153 }
154 if (b) op |= 1;
155 r->iv[i + r->in].op = op;
156 r->iv[i + r->in].argx = w;
157 r->iv[i + r->in].argy = b;
158 }
159 }
160 DA_DESTROY(&iv);
161}
162
163/* --- @mpreduce_destroy@ --- *
164 *
165 * Arguments: @mpreduce *r@ = structure to free
166 *
167 * Returns: ---
168 *
169 * Use: Reclaims the resources from a reduction context.
170 */
171
172void mpreduce_destroy(mpreduce *r)
173{
174 mp_drop(r->p);
175 xfree(r->iv);
176}
177
178/* --- @mpreduce_dump@ --- *
179 *
180 * Arguments: @mpreduce *r@ = structure to dump
181 * @FILE *fp@ = file to dump on
182 *
183 * Returns: ---
184 *
185 * Use: Dumps a reduction context.
186 */
187
188void mpreduce_dump(mpreduce *r, FILE *fp)
189{
190 size_t i;
191 static const char *opname[] = { "add", "addshift", "sub", "subshift" };
192
193 fprintf(fp, "mod = "); mp_writefile(r->p, fp, 16);
194 fprintf(fp, "\n lim = %lu; s = %d\n", (unsigned long)r->lim, r->s);
195 for (i = 0; i < r->in; i++) {
196 assert(r->iv[i].op < N(opname));
197 fprintf(fp, " %s %lu %lu\n",
198 opname[r->iv[i].op],
199 (unsigned long)r->iv[i].argx,
200 (unsigned long)r->iv[i].argy);
201 }
202 if (r->s) {
203 fprintf(fp, "tail end charlie\n");
204 for (i = r->in; i < 2 * r->in; i++) {
205 assert(r->iv[i].op < N(opname));
206 fprintf(fp, " %s %lu %lu\n",
207 opname[r->iv[i].op],
208 (unsigned long)r->iv[i].argx,
209 (unsigned long)r->iv[i].argy);
210 }
211 }
212}
213
214/* --- @mpreduce_do@ --- *
215 *
216 * Arguments: @mpreduce *r@ = reduction context
217 * @mp *d@ = destination
218 * @mp *x@ = source
219 *
220 * Returns: Destination, @x@ reduced modulo the reduction poly.
221 */
222
223static void run(const mpreduce_instr *i, const mpreduce_instr *il,
224 mpw *v, mpw z)
225{
226 for (; i < il; i++) {
227#ifdef DEBUG
228 mp vv;
229 mp_build(&vv, v - i->argx, v + 1);
230 printf(" 0x"); mp_writefile(&vv, stdout, 16);
231 printf(" %c (0x%lx << %u) == 0x",
232 (i->op & ~1u) == MPRI_ADD ? '+' : '-',
233 (unsigned long)z,
234 i->argy);
235#endif
236 switch (i->op) {
237 case MPRI_ADD: MPX_UADDN(v - i->argx, v + 1, z); break;
238 case MPRI_ADDLSL: mpx_uaddnlsl(v - i->argx, v + 1, z, i->argy); break;
239 case MPRI_SUB: MPX_USUBN(v - i->argx, v + 1, z); break;
240 case MPRI_SUBLSL: mpx_usubnlsl(v - i->argx, v + 1, z, i->argy); break;
241 default:
242 abort();
243 }
244#ifdef DEBUG
245 mp_build(&vv, v - i->argx, v + 1);
246 mp_writefile(&vv, stdout, 16);
247 printf("\n");
248#endif
249 }
250}
251
252mp *mpreduce_do(mpreduce *r, mp *d, mp *x)
253{
254 mpw *v, *vl;
255 const mpreduce_instr *il;
256 mpw z;
257
258#ifdef DEBUG
259 mp *_r = 0, *_rr = 0;
260#endif
261
262 /* --- If source is negative, divide --- */
263
264 if (MP_ISNEG(x)) {
265 mp_div(0, &d, x, r->p);
266 return (d);
267 }
268
269 /* --- Try to reuse the source's space --- */
270
271 MP_COPY(x);
272 if (d) MP_DROP(d);
273 MP_DEST(x, MP_LEN(x), x->f);
274
275 /* --- Do the reduction --- */
276
277#ifdef DEBUG
278 _r = MP_NEW;
279 mp_div(0, &_r, x, r->p);
280 MP_PRINTX("x", x);
281 _rr = 0;
282#endif
283
284 il = r->iv + r->in;
285 if (MP_LEN(x) >= r->lim) {
286 v = x->v + r->lim;
287 vl = x->vl;
288 while (vl-- > v) {
289 while (*vl) {
290 z = *vl;
291 *vl = 0;
292 run(r->iv, il, vl, z);
293#ifdef DEBUG
294 MP_PRINTX("x", x);
295 mp_div(0, &_rr, x, r->p);
296 assert(MP_EQ(_r, _rr));
297#endif
298 }
299 }
300 if (r->s) {
301 while (*vl >> r->s) {
302 z = *vl >> r->s;
303 *vl &= ((1 << r->s) - 1);
304 run(r->iv + r->in, il + r->in, vl, z);
305#ifdef DEBUG
306 MP_PRINTX("x", x);
307 mp_div(0, &_rr, x, r->p);
308 assert(MP_EQ(_r, _rr));
309#endif
310 }
311 }
312 }
313
314 /* --- Finishing touches --- */
315
316 MP_SHRINK(x);
317 if (MP_CMP(x, >=, r->p))
318 x = mp_sub(x, x, r->p);
319
320 /* --- Done --- */
321
322#ifdef DEBUG
323 assert(MP_EQ(_r, x));
324 mp_drop(_r);
325 mp_drop(_rr);
326#endif
327 return (x);
328}
329
330/* --- @mpreduce_exp@ --- *
331 *
332 * Arguments: @mpreduce *mr@ = pointer to reduction context
333 * @mp *d@ = fake destination
334 * @mp *a@ = base
335 * @mp *e@ = exponent
336 *
337 * Returns: Result, %$a^e \bmod m$%.
338 */
339
340mp *mpreduce_exp(mpreduce *mr, mp *d, mp *a, mp *e)
341{
342 mp *x = MP_ONE;
343 mp *spare = (e->f & MP_BURN) ? MP_NEWSEC : MP_NEW;
344
345 MP_SHRINK(e);
346 if (!MP_LEN(e))
347 ;
348 else if (MP_LEN(e) < EXP_THRESH)
349 EXP_SIMPLE(x, a, e);
350 else
351 EXP_WINDOW(x, a, e);
352 mp_drop(d);
353 mp_drop(spare);
354 return (x);
355}
356
357/*----- Test rig ----------------------------------------------------------*/
358
359
360#ifdef TEST_RIG
361
362#define MP(x) mp_readstring(MP_NEW, #x, 0, 0)
363
364static int vreduce(dstr *v)
365{
366 mp *d = *(mp **)v[0].buf;
367 mp *n = *(mp **)v[1].buf;
368 mp *r = *(mp **)v[2].buf;
369 mp *c;
370 int ok = 1;
371 mpreduce rr;
372
373 mpreduce_create(&rr, d);
374 c = mpreduce_do(&rr, MP_NEW, n);
375 if (!MP_EQ(c, r)) {
376 fprintf(stderr, "\n*** reduction failed\n*** ");
377 mpreduce_dump(&rr, stderr);
378 fprintf(stderr, "\n*** n = "); mp_writefile(n, stderr, 10);
379 fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
380 fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
381 fprintf(stderr, "\n");
382 ok = 0;
383 }
384 mpreduce_destroy(&rr);
385 mp_drop(n); mp_drop(d); mp_drop(r); mp_drop(c);
386 assert(mparena_count(MPARENA_GLOBAL) == 0);
387 return (ok);
388}
389
390static int vmodexp(dstr *v)
391{
392 mp *p = *(mp **)v[0].buf;
393 mp *g = *(mp **)v[1].buf;
394 mp *x = *(mp **)v[2].buf;
395 mp *r = *(mp **)v[3].buf;
396 mp *c;
397 int ok = 1;
398 mpreduce rr;
399
400 mpreduce_create(&rr, p);
401 c = mpreduce_exp(&rr, MP_NEW, g, x);
402 if (!MP_EQ(c, r)) {
403 fprintf(stderr, "\n*** modexp failed\n*** ");
404 fprintf(stderr, "\n*** p = "); mp_writefile(p, stderr, 10);
405 fprintf(stderr, "\n*** g = "); mp_writefile(g, stderr, 10);
406 fprintf(stderr, "\n*** x = "); mp_writefile(x, stderr, 10);
407 fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
408 fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
409 fprintf(stderr, "\n");
410 ok = 0;
411 }
412 mpreduce_destroy(&rr);
413 mp_drop(p); mp_drop(g); mp_drop(r); mp_drop(x); mp_drop(c);
414 assert(mparena_count(MPARENA_GLOBAL) == 0);
415 return (ok);
416}
417
418static test_chunk defs[] = {
419 { "reduce", vreduce, { &type_mp, &type_mp, &type_mp, 0 } },
420 { "modexp", vmodexp, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
421 { 0, 0, { 0 } }
422};
423
424int main(int argc, char *argv[])
425{
426 test_run(argc, argv, defs, SRCDIR"/tests/mpreduce");
427 return (0);
428}
429
430#endif
431
432/*----- That's all, folks -------------------------------------------------*/