1 /** Optimised asm arbitrary precision arithmetic ('bignum')
2 * routines for X86 processors.
4 * All functions operate on arrays of uints, stored LSB first.
5 * If there is a destination array, it will be the first parameter.
6 * Currently, all of these functions are subject to change, and are
7 * intended for internal use only.
8 * The symbol [#] indicates an array of machine words which is to be
9 * interpreted as a multi-byte number.
12 /* Copyright Don Clugston 2008 - 2010.
13 * Distributed under the Boost Software License, Version 1.0.
14 * (See accompanying file LICENSE_1_0.txt or copy at
15 * http://www.boost.org/LICENSE_1_0.txt)
18 * In simple terms, there are 3 modern x86 microarchitectures:
19 * (a) the P6 family (Pentium Pro, PII, PIII, PM, Core), produced by Intel;
20 * (b) the K6, Athlon, and AMD64 families, produced by AMD; and
21 * (c) the Pentium 4, produced by Marketing.
23 * This code has been optimised for the Intel P6 family.
24 * Generally the code remains near-optimal for Intel Core2/Corei7, after
25 * translating EAX-> RAX, etc, since all these CPUs use essentially the same
26 * pipeline, and are typically limited by memory access.
27 * The code uses techniques described in Agner Fog's superb Pentium manuals
28 * available at www.agner.org.
29 * Not optimised for AMD, which can do two memory loads per cycle (Intel
30 * CPUs can only do one). Despite this, performance is superior on AMD.
31 * Performance is dreadful on P4.
33 * Timing results (cycles per int)
34 * --Intel Pentium-- --AMD--
36 * +,- 2.25 15.6 2.25 1.5
37 * <<,>> 2.0 6.6 2.0 5.0
38 * (<< MMX) 1.7 5.3 1.5 1.2
40 * mulAdd 5.7 19.0 4.9 4.0
41 * div 30.0 32.0 32.0 22.4
42 * mulAcc(32) 6.5 20.0 5.4 4.9
44 * mulAcc(32) is multiplyAccumulate() for a 32*32 multiply. Thus it includes
45 * function call overhead.
46 * The timing for Div is quite unpredictable, but it's probably too slow
47 * to be useful. On 64-bit processors, these times should
48 * halve if run in 64-bit mode, except for the MMX functions.
51 module std.internal.math.biguintx86;
58 Naked asm is used throughout, because:
59 (a) it frees up the EBP register
60 (b) compiler bugs prevent the use of .ptr when a frame pointer is used.
63 version (D_InlineAsm_X86)
68 /* Duplicate string s, with n times, substituting index for '@'.
70 * Each instance of '@' in s is replaced by 0,1,...n-1. This is a helper
71 * function for some of the asm routines.
73 string indexedLoopUnroll(int n, string s) pure @safe
76 for (int i = 0; i<n; ++i)
78 string nstr= (i>9 ? ""~ cast(char)('0'+i/10) : "") ~ cast(char)('0' + i%10);
81 for (int j = 0; j<s.length; ++j)
85 u ~= s[last .. j] ~ nstr;
89 if (last<s.length) u = u ~ s[last..$];
96 assert(indexedLoopUnroll(3, "@*23;")=="0*23;1*23;2*23;");
101 alias BigDigit = uint; // A Bignum is an array of BigDigits. Usually the machine word size.
103 // Limits for when to switch between multiplication algorithms.
104 enum : int { KARATSUBALIMIT = 18 }; // Minimum value for which Karatsuba is worthwhile.
105 enum : int { KARATSUBASQUARELIMIT=26 }; // Minimum value for which square Karatsuba is worthwhile
107 /** Multi-byte addition or subtraction
108 * dest[#] = src1[#] + src2[#] + carry (0 or 1).
109 * or dest[#] = src1[#] - src2[#] - carry (0 or 1).
110 * Returns carry or borrow (0 or 1).
111 * Set op == '+' for addition, '-' for subtraction.
113 uint multibyteAddSub(char op)(uint[] dest, const uint [] src1, const uint []
114 src2, uint carry) pure
117 // Pentium M: 2.25/int
118 // P6 family, Core2 have a partial flags stall when reading the carry flag in
119 // an ADC, SBB operation after an operation such as INC or DEC which
120 // modifies some, but not all, flags. We avoid this by storing carry into
121 // a resister (AL), and restoring it after the branch.
123 enum { LASTPARAM = 4*4 } // 3* pushes + return address.
129 mov ECX, [ESP + LASTPARAM + 4*4]; // dest.length;
130 mov EDX, [ESP + LASTPARAM + 3*4]; // src1.ptr
131 mov ESI, [ESP + LASTPARAM + 1*4]; // src2.ptr
132 mov EDI, [ESP + LASTPARAM + 5*4]; // dest.ptr
134 // Count UP to zero (from -len) to minimize loop overhead.
135 lea EDX, [EDX + 4*ECX]; // EDX = end of src1.
136 lea ESI, [ESI + 4*ECX]; // EBP = end of src2.
137 lea EDI, [EDI + 4*ECX]; // EDI = end of dest.
141 jb L2; // if length < 8 , bypass the unrolled loop.
143 shr AL, 1; // get carry from EAX
145 mixin(" asm pure nothrow {"
146 ~ indexedLoopUnroll( 8,
147 "mov EAX, [@*4-8*4+EDX+ECX*4];"
148 ~ ( op == '+' ? "adc" : "sbb" ) ~ " EAX, [@*4-8*4+ESI+ECX*4];"
149 ~ "mov [@*4-8*4+EDI+ECX*4], EAX;")
152 setc AL; // save carry
155 L2: // Do the residual 1 .. 7 ints.
160 shr AL, 1; // get carry from EAX
162 mixin(" asm pure nothrow {"
163 ~ indexedLoopUnroll( 1,
164 "mov EAX, [@*4+EDX+ECX*4];"
165 ~ ( op == '+' ? "adc" : "sbb" ) ~ " EAX, [@*4+ESI+ECX*4];"
166 ~ "mov [@*4+EDI+ECX*4], EAX;") ~ "}");
168 setc AL; // save carry
172 and EAX, 1; // make it O or 1.
182 uint [] a = new uint[40];
183 uint [] b = new uint[40];
184 uint [] c = new uint[40];
185 for (int i=0; i<a.length; ++i)
187 if (i&1) a[i]=0x8000_0000 + i;
192 uint carry = multibyteAddSub!('+')(c[0 .. 18], a[0 .. 18], b[0 .. 18], 0);
194 assert(c[0]==0x8000_0003);
196 assert(c[19]==0x3333_3333); // check for overrun
197 for (int i=0; i<a.length; ++i)
206 carry = multibyteAddSub!('-')(a[0 .. 12], a[0 .. 12], b[0 .. 12], 0);
208 for (int i=0; i<10; ++i) if (i != 5) assert(a[i]==0);
210 for (int q=3; q<36;++q)
212 for (int i=0; i<a.length; ++i)
218 carry = multibyteAddSub!('-')(a[0 .. q], a[0 .. q], b[0 .. q], 0);
223 /** dest[#] += carry, or dest[#] -= carry.
224 * op must be '+' or '-'
225 * Returns final carry or borrow (0 or 1)
227 uint multibyteIncrementAssign(char op)(uint[] dest, uint carry) pure
229 enum { LASTPARAM = 1*4 } // 0* pushes + return address.
232 mov ECX, [ESP + LASTPARAM + 0*4]; // dest.length;
233 mov EDX, [ESP + LASTPARAM + 1*4]; // dest.ptr
238 asm pure nothrow { add [EDX], EAX; }
240 asm pure nothrow { sub [EDX], EAX; }
253 /** dest[#] = src[#] << numbits
254 * numbits must be in the range 1 .. 31
255 * Returns the overflow
257 uint multibyteShlNoMMX(uint [] dest, const uint [] src, uint numbits) pure
259 // Timing: Optimal for P6 family.
260 // 2.0 cycles/int on PPro .. PM (limited by execution port p0)
261 // 5.0 cycles/int on Athlon, which has 7 cycles for SHLD!!
262 enum { LASTPARAM = 4*4 } // 3* pushes + return address.
268 mov EDI, [ESP + LASTPARAM + 4*3]; //dest.ptr;
269 mov EBX, [ESP + LASTPARAM + 4*2]; //dest.length;
270 mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr;
271 mov ECX, EAX; // numbits;
273 mov EAX, [-4+ESI + 4*EBX];
276 push EDX; // Save return value
279 mov EDX, [-4+ESI + 4*EBX];
284 mov EDX, [-4+ ESI + 4*EBX];
286 mov [EDI+4*EBX], EAX;
288 mov EAX, [-8+ESI + 4*EBX];
290 mov [-4+EDI + 4*EBX], EDX;
296 pop EAX; // pop return value
304 /** dest[#] = src[#] >> numbits
305 * numbits must be in the range 1 .. 31
306 * This version uses MMX.
308 uint multibyteShl(uint [] dest, const uint [] src, uint numbits) pure
311 // K7 1.2/int. PM 1.7/int P4 5.3/int
312 enum { LASTPARAM = 4*4 } // 3* pushes + return address.
318 mov EDI, [ESP + LASTPARAM + 4*3]; //dest.ptr;
319 mov EBX, [ESP + LASTPARAM + 4*2]; //dest.length;
320 mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr;
322 movd MM3, EAX; // numbits = bits to shift left
326 movd MM4, EAX ; // 64-numbits = bits to shift right
328 // Get the return value into EAX
329 and EAX, 31; // EAX = 32-numbits
330 movd MM2, EAX; // 32-numbits
331 movd MM1, [ESI+4*EBX-4];
333 movd EAX, MM1; // EAX = return value
340 // deal with odd lengths
341 movq MM1, [ESI+4*EBX-8];
343 movd [EDI +4*EBX-4], MM1;
345 L_even: // It's either singly or doubly even
346 movq MM2, [ESI + 4*EBX - 8];
356 // MAIN LOOP -- 128 bytes per iteration
357 L_twiceeven: // here MM2 is the carry
358 movq MM0, [ESI + 4*EBX-8];
360 movq MM1, [ESI + 4*EBX-8];
363 movq [EDI +4*EBX], MM2;
364 L_onceeven: // here MM1 is the carry
365 movq MM0, [ESI + 4*EBX-16];
367 movq MM2, [ESI + 4*EBX-16];
369 movq [EDI +4*EBX-8], MM1;
374 movq [EDI +4*EBX], MM2;
376 emms; // NOTE: costs 6 cycles on Intel CPUs
383 // length 1 is a special case
391 void multibyteShr(uint [] dest, const uint [] src, uint numbits) pure
393 enum { LASTPARAM = 4*4 } // 3* pushes + return address.
399 mov EDI, [ESP + LASTPARAM + 4*3]; //dest.ptr;
400 mov EBX, [ESP + LASTPARAM + 4*2]; //dest.length;
402 mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr;
403 lea EDI, [EDI + 4*EBX]; // EDI = end of dest
404 lea ESI, [ESI + 4*EBX]; // ESI = end of src
405 neg EBX; // count UP to zero.
407 movd MM3, EAX; // numbits = bits to shift right
410 movd MM4, EAX ; // 64-numbits = bits to shift left
415 // deal with odd lengths
416 and EAX, 31; // EAX = 32-numbits
417 movd MM2, EAX; // 32-numbits
421 movq MM0, [ESI+4*EBX];
423 movd [EDI +4*EBX], MM0;
426 movq MM2, [ESI + 4*EBX];
433 // It's either singly or doubly even
439 // MAIN LOOP -- 128 bytes per iteration
440 L_twiceeven: // here MM2 is the carry
441 movq MM0, [ESI + 4*EBX-8];
443 movq MM1, [ESI + 4*EBX-8];
446 movq [EDI +4*EBX-16], MM2;
447 L_onceeven: // here MM1 is the carry
448 movq MM0, [ESI + 4*EBX];
450 movq MM2, [ESI + 4*EBX];
452 movq [EDI +4*EBX-8], MM1;
457 movq [EDI +4*EBX-16], MM2;
459 emms; // NOTE: costs 6 cycles on Intel CPUs
466 // length 1 is a special case
467 movd MM1, [ESI+4*EBX];
469 movd [EDI +4*EBX], MM1;
475 /** dest[#] = src[#] >> numbits
476 * numbits must be in the range 1 .. 31
478 void multibyteShrNoMMX(uint [] dest, const uint [] src, uint numbits) pure
480 // Timing: Optimal for P6 family.
481 // 2.0 cycles/int on PPro .. PM (limited by execution port p0)
482 // Terrible performance on AMD64, which has 7 cycles for SHRD!!
483 enum { LASTPARAM = 4*4 } // 3* pushes + return address.
489 mov EDI, [ESP + LASTPARAM + 4*3]; //dest.ptr;
490 mov EBX, [ESP + LASTPARAM + 4*2]; //dest.length;
491 mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr;
492 mov ECX, EAX; // numbits;
494 lea EDI, [EDI + 4*EBX]; // EDI = end of dest
495 lea ESI, [ESI + 4*EBX]; // ESI = end of src
496 neg EBX; // count UP to zero.
497 mov EAX, [ESI + 4*EBX];
500 mov EDX, [ESI + 4*EBX];
505 mov EDX, [ ESI + 4*EBX];
507 mov [-4 + EDI+4*EBX], EAX;
509 mov EAX, [4 + ESI + 4*EBX];
511 mov [EDI + 4*EBX], EDX;
528 uint [] aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
529 multibyteShr(aa[0..$-1], aa, 4);
530 assert(aa[0] == 0x6122_2222 && aa[1]==0xA455_5555
531 && aa[2]==0xD899_9999 && aa[3]==0x0BCC_CCCC);
533 aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
534 multibyteShr(aa[2..$-1], aa[2..$-1], 4);
535 assert(aa[0] == 0x1222_2223 && aa[1]==0x4555_5556
536 && aa[2]==0xD899_9999 && aa[3]==0x0BCC_CCCC);
538 aa = [0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
539 multibyteShr(aa[0..$-2], aa, 4);
540 assert(aa[1]==0xA455_5555 && aa[2]==0x0899_9999);
541 assert(aa[0]==0x6122_2222);
542 assert(aa[3]==0xBCCC_CCCD);
545 aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
546 uint r = multibyteShl(aa[2 .. 4], aa[2 .. 4], 4);
547 assert(aa[0] == 0xF0FF_FFFF && aa[1]==0x1222_2223
548 && aa[2]==0x5555_5560 && aa[3]==0x9999_99A4 && aa[4]==0xBCCC_CCCD);
551 aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
552 r = multibyteShl(aa[1 .. 4], aa[1 .. 4], 4);
553 assert(aa[0] == 0xF0FF_FFFF
554 && aa[2]==0x5555_5561);
555 assert(aa[3]==0x9999_99A4 && aa[4]==0xBCCC_CCCD);
557 assert(aa[1]==0x2222_2230);
559 aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
560 r = multibyteShl(aa[0 .. 4], aa[1 .. 5], 31);
563 /** dest[#] = src[#] * multiplier + carry.
566 uint multibyteMul(uint[] dest, const uint[] src, uint multiplier, uint carry)
569 // Timing: definitely not optimal.
570 // Pentium M: 5.0 cycles/operation, has 3 resource stalls/iteration
571 // Fastest implementation found was 4.6 cycles/op, but not worth the complexity.
573 enum { LASTPARAM = 4*4 } // 4* pushes + return address.
574 // We'll use p2 (load unit) instead of the overworked p0 or p1 (ALU units)
575 // when initializing variables to zero.
582 __gshared int zero = 0;
590 mov EDI, [ESP + LASTPARAM + 4*4]; // dest.ptr
591 mov EBX, [ESP + LASTPARAM + 4*3]; // dest.length
592 mov ESI, [ESP + LASTPARAM + 4*2]; // src.ptr
594 lea EDI, [EDI + 4*EBX]; // EDI = end of dest
595 lea ESI, [ESI + 4*EBX]; // ESI = end of src
596 mov ECX, EAX; // [carry]; -- last param is in EAX.
597 neg EBX; // count UP to zero.
602 mov EAX, [-4 + ESI + 4*EBX];
603 mul int ptr [ESP+LASTPARAM]; //[multiplier];
606 mov [-4+EDI + 4*EBX], EAX;
609 mov EAX, [ESI + 4*EBX]; // p2
610 mul int ptr [ESP+LASTPARAM]; //[multiplier]; // p0*3,
614 mov [EDI + 4*EBX], EAX;
618 mov EAX, ECX; // get final carry
629 uint [] aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
630 multibyteMul(aa[1 .. 4], aa[1 .. 4], 16, 0);
631 assert(aa[0] == 0xF0FF_FFFF && aa[1] == 0x2222_2230 &&
632 aa[2]==0x5555_5561 && aa[3]==0x9999_99A4 && aa[4]==0x0BCCC_CCCD);
635 // The inner multiply-and-add loop, together with the Even entry point.
636 // Multiples by M_ADDRESS which should be "ESP+LASTPARAM" or "ESP". OP must be "add" or "sub"
637 // This is the most time-critical code in the BigInt library.
638 // It is used by both MulAdd, multiplyAccumulate, and triangleAccumulate
639 string asmMulAdd_innerloop(string OP, string M_ADDRESS) pure {
640 // The bottlenecks in this code are extremely complicated. The MUL, ADD, and ADC
641 // need 4 cycles on each of the ALUs units p0 and p1. So we use memory load
642 // (unit p2) for initializing registers to zero.
643 // There are also dependencies between the instructions, and we run up against the
644 // ROB-read limit (can only read 2 registers per cycle).
645 // We also need the number of uops in the loop to be a multiple of 3.
646 // The only available execution unit for this is p3 (memory write). Unfortunately we can't do that
647 // if Position-Independent Code is required.
652 // EBX = index. Counts up to zero (in steps of 2).
653 // EDX:EAX = scratch, used in multiply.
656 // ESP = points to the multiplier.
658 // The first member of 'dest' which will be modified is [EDI+4*EBX].
659 // EAX must already contain the first member of 'src', [ESI+4*EBX].
661 version (D_PIC) { bool using_PIC = true; } else { bool using_PIC = false; }
663 // Entry point for even length
665 mov EBP, ECX; // carry
667 mul int ptr [" ~ M_ADDRESS ~ "]; // M
671 mov EAX, [ESI+4*EBX];
674 mul int ptr [" ~ M_ADDRESS ~ "]; // M
675 " ~ OP ~ " [-4+EDI+4*EBX], EBP;
679 mov EAX, [4+ESI+4*EBX];
685 mul int ptr [" ~ M_ADDRESS ~ "];
686 " ~ OP ~ " [-8+EDI+4*EBX], ECX;
689 mov EAX, [ESI+4*EBX];
692 (using_PIC ? "" : " mov storagenop, EDX; ") // make #uops in loop a multiple of 3, can't do this in PIC mode.
694 mul int ptr [" ~ M_ADDRESS ~ "];
695 " ~ OP ~ " [-4+EDI+4*EBX], EBP;
699 mov EAX, [4+ESI+4*EBX];
704 L_done: " ~ OP ~ " [-8+EDI+4*EBX], ECX;
707 // final carry is now in EBP
710 string asmMulAdd_enter_odd(string OP, string M_ADDRESS) pure
713 mul int ptr [" ~M_ADDRESS ~"];
716 mov EAX, [4+ESI+4*EBX];
728 * dest[#] += src[#] * multiplier OP carry(0 .. FFFF_FFFF).
729 * where op == '+' or '-'
730 * Returns carry out of MSB (0 .. FFFF_FFFF).
732 uint multibyteMulAdd(char op)(uint [] dest, const uint [] src, uint
733 multiplier, uint carry) pure {
734 // Timing: This is the most time-critical bignum function.
735 // Pentium M: 5.4 cycles/operation, still has 2 resource stalls + 1load block/iteration
737 // The main loop is pipelined and unrolled by 2,
738 // so entry to the loop is also complicated.
741 // EDX:EAX = multiply
748 enum string OP = (op=='+')? "add" : "sub";
755 // use p2 (load unit) instead of the overworked p0 or p1 (ALU units)
756 // when initializing registers to zero.
757 __gshared int zero = 0;
759 __gshared int storagenop; // write-only
762 enum { LASTPARAM = 5*4 } // 4* pushes + return address.
770 mov EDI, [ESP + LASTPARAM + 4*4]; // dest.ptr
771 mov EBX, [ESP + LASTPARAM + 4*3]; // dest.length
774 mov ESI, [ESP + LASTPARAM + 4*2]; // src.ptr
775 lea EDI, [EDI + 4*EBX]; // EDI = end of dest
776 lea ESI, [ESI + 4*EBX]; // ESI = end of src
778 mov ECX, EAX; // ECX = input carry.
779 neg EBX; // count UP to zero.
780 mov EAX, [ESI+4*EBX];
784 // Main loop, with entry point for even length
785 mixin("asm pure nothrow {" ~ asmMulAdd_innerloop(OP, "ESP+LASTPARAM") ~ "}");
787 mov EAX, EBP; // get final carry
795 mixin("asm pure nothrow {" ~ asmMulAdd_enter_odd(OP, "ESP+LASTPARAM") ~ "}");
801 uint [] aa = [0xF0FF_FFFF, 0x1222_2223, 0x4555_5556, 0x8999_999A, 0xBCCC_CCCD, 0xEEEE_EEEE];
802 uint [] bb = [0x1234_1234, 0xF0F0_F0F0, 0x00C0_C0C0, 0xF0F0_F0F0, 0xC0C0_C0C0];
803 multibyteMulAdd!('+')(bb[1..$-1], aa[1..$-2], 16, 5);
804 assert(bb[0] == 0x1234_1234 && bb[4] == 0xC0C0_C0C0);
805 assert(bb[1] == 0x2222_2230 + 0xF0F0_F0F0+5 && bb[2] == 0x5555_5561+0x00C0_C0C0+1
806 && bb[3] == 0x9999_99A4+0xF0F0_F0F0 );
810 Sets result[#] = result[0 .. left.length] + left[#] * right[#]
812 It is defined in this way to allow cache-efficient multiplication.
813 This function is equivalent to:
815 for (int i = 0; i< right.length; ++i)
817 dest[left.length + i] = multibyteMulAdd(dest[i .. left.length+i],
822 void multibyteMultiplyAccumulate(uint [] dest, const uint[] left,
823 const uint [] right) pure {
825 // EDX:EAX = used in multiply
829 // EDI = end of dest for this pass through the loop. Index for outer loop.
830 // ESI = end of left. never changes
831 // [ESP] = M = right[i] = multiplier for this pass through the loop.
832 // right.length is changed into dest.ptr+dest.length
839 // use p2 (load unit) instead of the overworked p0 or p1 (ALU units)
840 // when initializing registers to zero.
841 __gshared int zero = 0;
843 __gshared int storagenop; // write-only
846 enum { LASTPARAM = 6*4 } // 4* pushes + local + return address.
855 push EAX; // local variable M
856 mov EDI, [ESP + LASTPARAM + 4*5]; // dest.ptr
857 mov EBX, [ESP + LASTPARAM + 4*2]; // left.length
858 mov ESI, [ESP + LASTPARAM + 4*3]; // left.ptr
859 lea EDI, [EDI + 4*EBX]; // EDI = end of dest for first pass
861 mov EAX, [ESP + LASTPARAM + 4*0]; // right.length
862 lea EAX, [EDI + 4*EAX];
863 mov [ESP + LASTPARAM + 4*0], EAX; // last value for EDI
865 lea ESI, [ESI + 4*EBX]; // ESI = end of left
866 mov EAX, [ESP + LASTPARAM + 4*1]; // right.ptr
871 mov ECX, 0; // ECX = input carry.
872 neg EBX; // count UP to zero.
873 mov EAX, [ESI+4*EBX];
877 // -- Inner loop, with even entry point
878 mixin("asm pure nothrow { " ~ asmMulAdd_innerloop("add", "ESP") ~ "}");
880 mov [-4+EDI+4*EBX], EBP;
882 cmp EDI, [ESP + LASTPARAM + 4*0]; // is EDI = &dest[$]?
884 mov EAX, [ESP + LASTPARAM + 4*1]; // right.ptr
885 mov EAX, [EAX+4]; // get new M
886 mov [ESP], EAX; // save new M
887 add int ptr [ESP + LASTPARAM + 4*1], 4; // right.ptr
888 mov EBX, [ESP + LASTPARAM + 4*2]; // left.length
899 mixin("asm pure nothrow {" ~ asmMulAdd_enter_odd("add", "ESP") ~ "}");
902 /** dest[#] /= divisor.
903 * overflow is the initial remainder, and must be in the range 0 .. divisor-1.
904 * divisor must not be a power of 2 (use right shift for that case;
905 * A division by zero will occur if divisor is a power of 2).
906 * Returns the final remainder
908 * Based on public domain code by Eric Bainville.
909 * (http://www.bealto.com/) Used with permission.
911 uint multibyteDivAssign(uint [] dest, uint divisor, uint overflow) pure
913 // Timing: limited by a horrible dependency chain.
914 // Pentium M: 18 cycles/op, 8 resource stalls/op.
915 // EAX, EDX = scratch, used by MUL
922 // [ESP] = kinv (2^64 /divisor)
923 enum { LASTPARAM = 5*4 } // 4* pushes + return address.
924 enum { LOCALS = 2*4} // MASK, KINV
933 mov EDI, [ESP + LASTPARAM + 4*2]; // dest.ptr
934 mov EBX, [ESP + LASTPARAM + 4*1]; // dest.length
936 // Loop from msb to lsb
937 lea EDI, [EDI + 4*EBX];
938 mov EBP, EAX; // rem is the input remainder, in 0 .. divisor-1
939 // Build the pseudo-inverse of divisor k: 2^64/k
940 // First determine the shift in ecx to get the max number of bits in kinv
942 mov EAX, [ESP + LASTPARAM]; //divisor;
950 // Here, ecx is a left shift moving the msb of k to bit 32
955 ror EAX, CL ; //ecx bits at msb
958 // Then divide 2^(32+cx) by divisor (edx already ok)
960 div int ptr [ESP + LASTPARAM + LOCALS-4*1]; //divisor;
964 // Get 32 bits of quotient approx, multiplying
965 // most significant word of (rem*2^32+input)
966 mov EAX, [ESP+4]; //MASK;
972 mul int ptr [ESP]; //KINV;
977 // Multiply by k and subtract to get remainder
978 // Subtraction must be done on two words
980 mov ESI, EDX; // quot = high word
981 mul int ptr [ESP + LASTPARAM+LOCALS]; //divisor;
984 jz Lb; // high word is 0, goto adjust on single word
986 // Adjust quotient and remainder on two words
988 sub EBP, [ESP + LASTPARAM+LOCALS]; //divisor;
992 // Adjust quotient and remainder on single word
993 Lb: cmp EBP, [ESP + LASTPARAM+LOCALS]; //divisor;
994 jc Lc; // rem in 0 .. divisor-1, OK
995 sub EBP, [ESP + LASTPARAM+LOCALS]; //divisor;
1003 dec int ptr [ESP + LASTPARAM + 4*1+LOCALS]; // len
1006 pop EAX; // discard kinv
1007 pop EAX; // discard mask
1009 mov EAX, EBP; // return final remainder
1020 uint [] aa = new uint[101];
1021 for (int i=0; i<aa.length; ++i) aa[i] = 0x8765_4321 * (i+3);
1022 uint overflow = multibyteMul(aa, aa, 0x8EFD_FCFB, 0x33FF_7461);
1023 uint r = multibyteDivAssign(aa, 0x8EFD_FCFB, overflow);
1024 for (int i=0; i<aa.length-1; ++i) assert(aa[i] == 0x8765_4321 * (i+3));
1025 assert(r == 0x33FF_7461);
1028 // Set dest[2*i .. 2*i+1]+=src[i]*src[i]
1029 void multibyteAddDiagonalSquares(uint [] dest, const uint [] src) pure
1031 /* Unlike mulAdd, the carry is only 1 bit,
1032 since FFFF*FFFF+FFFF_FFFF = 1_0000_0000.
1033 Note also that on the last iteration, no carry can occur.
1034 As for multibyteAdd, we save & restore carry flag through the loop.
1036 The timing is entirely dictated by the dependency chain. We could
1037 improve it by moving the mov EAX after the adc [EDI], EAX. Probably not worthwhile.
1039 enum { LASTPARAM = 4*5 } // 4* pushes + return address.
1046 mov EDI, [ESP + LASTPARAM + 4*3]; //dest.ptr;
1047 mov EBX, [ESP + LASTPARAM + 4*0]; //src.length;
1048 mov ESI, [ESP + LASTPARAM + 4*1]; //src.ptr;
1049 lea EDI, [EDI + 8*EBX]; // EDI = end of dest
1050 lea ESI, [ESI + 4*EBX]; // ESI = end of src
1051 neg EBX; // count UP to zero.
1052 xor ECX, ECX; // initial carry = 0.
1054 mov EAX, [ESI + 4*EBX];
1056 shr CL, 1; // get carry
1057 adc [EDI + 8*EBX], EAX;
1058 adc [EDI + 8*EBX + 4], EDX;
1059 setc CL; // save carry
1073 uint [] aa = new uint[13];
1074 uint [] bb = new uint[6];
1075 for (int i=0; i<aa.length; ++i) aa[i] = 0x8000_0000;
1076 for (int i=0; i<bb.length; ++i) bb[i] = i;
1078 multibyteAddDiagonalSquares(aa[0..$-1], bb);
1080 for (int i=0; i<bb.length; ++i) { assert(aa[2*i]==0x8000_0000+i*i); assert(aa[2*i+1]==0x8000_0000); }
1083 void multibyteTriangleAccumulateD(uint[] dest, uint[] x) pure
1085 for (int i = 0; i < x.length-3; ++i)
1087 dest[i+x.length] = multibyteMulAdd!('+')(
1088 dest[i+i+1 .. i+x.length], x[i+1..$], x[i], 0);
1090 ulong c = cast(ulong)(x[$-3]) * x[$-2] + dest[$-5];
1091 dest[$-5] = cast(uint) c;
1093 c += cast(ulong)(x[$-3]) * x[$-1] + dest[$-4];
1094 dest[$-4] = cast(uint) c;
1097 c += cast(ulong)(x[$-2]) * x[$-1];
1098 dest[$-3] = cast(uint) c;
1100 dest[$-2] = cast(uint) c;
1103 //dest += src[0]*src[1...$] + src[1]*src[2..$] + ... + src[$-3]*src[$-2..$]+ src[$-2]*src[$-1]
1104 // assert(dest.length = src.length*2);
1105 // assert(src.length >= 3);
1106 void multibyteTriangleAccumulateAsm(uint[] dest, const uint[] src) pure
1109 // EDX:EAX = used in multiply
1113 // EDI = end of dest for this pass through the loop. Index for outer loop.
1114 // ESI = end of src. never changes
1115 // [ESP] = M = src[i] = multiplier for this pass through the loop.
1116 // dest.length is changed into dest.ptr+dest.length
1123 // use p2 (load unit) instead of the overworked p0 or p1 (ALU units)
1124 // when initializing registers to zero.
1125 __gshared int zero = 0;
1127 __gshared int storagenop; // write-only
1130 enum { LASTPARAM = 6*4 } // 4* pushes + local + return address.
1139 push EAX; // local variable M= src[i]
1140 mov EDI, [ESP + LASTPARAM + 4*3]; // dest.ptr
1141 mov EBX, [ESP + LASTPARAM + 4*0]; // src.length
1142 mov ESI, [ESP + LASTPARAM + 4*1]; // src.ptr
1144 lea ESI, [ESI + 4*EBX]; // ESI = end of left
1145 add int ptr [ESP + LASTPARAM + 4*1], 4; // src.ptr, used for getting M
1147 // local variable [ESP + LASTPARAM + 4*2] = last value for EDI
1148 lea EDI, [EDI + 4*EBX]; // EDI = end of dest for first pass
1150 lea EAX, [EDI + 4*EBX-3*4]; // up to src.length - 3
1151 mov [ESP + LASTPARAM + 4*2], EAX; // last value for EDI = &dest[src.length*2 -3]
1156 // We start at src[1], not src[0].
1158 mov [ESP + LASTPARAM + 4*0], EBX;
1161 mov EBX, [ESP + LASTPARAM + 4*0]; // src.length
1163 mov ECX, 0; // ECX = input carry.
1164 dec [ESP + LASTPARAM + 4*0]; // Next time, the length will be shorter by 1.
1165 neg EBX; // count UP to zero.
1167 mov EAX, [ESI + 4*EBX - 4*1]; // get new M
1168 mov [ESP], EAX; // save new M
1170 mov EAX, [ESI+4*EBX];
1174 // -- Inner loop, with even entry point
1175 mixin("asm pure nothrow { " ~ asmMulAdd_innerloop("add", "ESP") ~ "}");
1177 mov [-4+EDI+4*EBX], EBP;
1179 cmp EDI, [ESP + LASTPARAM + 4*2]; // is EDI = &dest[$-3]?
1182 mov EAX, [ESI - 4*3];
1183 mul EAX, [ESI - 4*2];
1185 add [EDI-2*4], EAX; // ECX:dest[$-5] += x[$-3] * x[$-2]
1188 mov EAX, [ESI - 4*3];
1189 mul EAX, [ESI - 4*1]; // x[$-3] * x[$-1]
1193 // now EDX: EAX = c + x[$-3] * x[$-1]
1194 add [EDI-1*4], EAX; // ECX:dest[$-4] += (EDX:EAX)
1195 adc ECX, EDX; // ECX holds dest[$-3], it acts as carry for the last row
1197 mov EAX, [ESI - 4*2];
1198 mul EAX, [ESI - 4*1];
1201 mov [EDI - 0*4], ECX; // dest[$-2:$-3] = c + x[$-2] * x[$-1];
1202 mov [EDI + 1*4], EDX;
1212 mixin("asm pure nothrow {" ~ asmMulAdd_enter_odd("add", "ESP") ~ "}");
1217 uint [] aa = new uint[200];
1218 uint [] a = aa[0 .. 100];
1219 uint [] b = new uint [100];
1227 multibyteTriangleAccumulateAsm(a, b[0 .. 50]);
1228 uint [] c = new uint[100];
1242 multibyteTriangleAccumulateAsm(a[0 .. 8], b[0 .. 4]);
1243 assert(a[1]==0x3a600964);
1244 assert(a[2]==0x339974f6);
1245 assert(a[3]==0x46736fce);
1246 assert(a[4]==0x5e24a2b4);
1251 multibyteTriangleAccumulateAsm(a[0 .. 14], b[0 .. 7]);
1252 assert(a[3]==0x79fff5c2);
1253 assert(a[4]==0xcf384241);
1254 assert(a[5]== 0x4a17fc8);
1255 assert(a[6]==0x4d549025);
1259 void multibyteSquare(BigDigit[] result, const BigDigit [] x) pure
1263 // Special cases, not worth doing triangular.
1264 result[x.length] = multibyteMul(result[0 .. x.length], x, x[0], 0);
1265 multibyteMultiplyAccumulate(result[1..$], x, x[1..$]);
1268 // Do half a square multiply.
1269 // dest += src[0]*src[1...$] + src[1]*src[2..$] + ... + src[$-3]*src[$-2..$]+ src[$-2]*src[$-1]
1270 result[x.length] = multibyteMul(result[1 .. x.length], x[1..$], x[0], 0);
1271 multibyteTriangleAccumulateAsm(result[2..$], x[1..$]);
1273 result[$-1] = multibyteShlNoMMX(result[1..$-1], result[1..$-1], 1);
1274 // And add the diagonal elements
1276 multibyteAddDiagonalSquares(result, x);
1279 version (BignumPerformanceTest)
1281 import core.stdc.stdio;
1282 int clock() { asm { push EBX; xor EAX, EAX; cpuid; pop EBX; rdtsc; } }
1284 __gshared uint [2200] X1;
1285 __gshared uint [2200] Y1;
1286 __gshared uint [4000] Z1;
1288 void testPerformance() pure
1290 // The performance results at the top of this file were obtained using
1291 // a Windows device driver to access the CPU performance counters.
1292 // The code below is less accurate but more widely usable.
1293 // The value for division is quite inconsistent.
1294 for (int i=0; i<X1.length; ++i) { X1[i]=i; Y1[i]=i; Z1[i]=i; }
1296 multibyteShl(Z1[0 .. 2000], X1[0 .. 2000], 7);
1298 multibyteShl(Z1[0 .. 1000], X1[0 .. 1000], 7);
1300 multibyteShl(Z1[0 .. 2000], X1[0 .. 2000], 7);
1301 auto shltime = (clock() - t) - (t - t0);
1303 multibyteShr(Z1[2 .. 1002], X1[4 .. 1004], 13);
1305 multibyteShr(Z1[2 .. 2002], X1[4 .. 2004], 13);
1306 auto shrtime = (clock() - t) - (t - t0);
1308 multibyteAddSub!('+')(Z1[0 .. 1000], X1[0 .. 1000], Y1[0 .. 1000], 0);
1310 multibyteAddSub!('+')(Z1[0 .. 2000], X1[0 .. 2000], Y1[0 .. 2000], 0);
1311 auto addtime = (clock() - t) - (t-t0);
1313 multibyteMul(Z1[0 .. 1000], X1[0 .. 1000], 7, 0);
1315 multibyteMul(Z1[0 .. 2000], X1[0 .. 2000], 7, 0);
1316 auto multime = (clock() - t) - (t - t0);
1317 multibyteMulAdd!('+')(Z1[0 .. 2000], X1[0 .. 2000], 217, 0);
1319 multibyteMulAdd!('+')(Z1[0 .. 1000], X1[0 .. 1000], 217, 0);
1321 multibyteMulAdd!('+')(Z1[0 .. 2000], X1[0 .. 2000], 217, 0);
1322 auto muladdtime = (clock() - t) - (t - t0);
1323 multibyteMultiplyAccumulate(Z1[0 .. 64], X1[0 .. 32], Y1[0 .. 32]);
1325 multibyteMultiplyAccumulate(Z1[0 .. 64], X1[0 .. 32], Y1[0 .. 32]);
1326 auto accumtime = clock() - t;
1328 multibyteDivAssign(Z1[0 .. 2000], 217, 0);
1330 multibyteDivAssign(Z1[0 .. 1000], 37, 0);
1331 auto divtime = (t - t0) - (clock() - t);
1333 multibyteSquare(Z1[0 .. 64], X1[0 .. 32]);
1334 auto squaretime = clock() - t;
1336 printf("-- BigInt asm performance (cycles/int) --\n");
1337 printf("Add: %.2f\n", addtime/1000.0);
1338 printf("Shl: %.2f\n", shltime/1000.0);
1339 printf("Shr: %.2f\n", shrtime/1000.0);
1340 printf("Mul: %.2f\n", multime/1000.0);
1341 printf("MulAdd: %.2f\n", muladdtime/1000.0);
1342 printf("Div: %.2f\n", divtime/1000.0);
1343 printf("MulAccum32: %.2f*n*n (total %d)\n", accumtime/(32.0*32.0), accumtime);
1344 printf("Square32: %.2f*n*n (total %d)\n\n", squaretime/(32.0*32.0), squaretime);
1353 } // version (D_InlineAsm_X86)