Add another link for reference
[experiments/inline-assembly.git] / inline-asm-array-sum.c
1 /*
2  * inline-asm-array-sum - an example of inline assembly accessing arrays
3  *
4  * Copyright (C) 2013  Antonio Ospite <ospite@studenti.unina.it>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <time.h>
23
24 #define SIZE 10000001
25
26 static int array_sum(int *values, unsigned int n)
27 {
28         int sum = 0;
29
30 #if defined(__x86_64__)
31         __asm__(
32                 "movq $0, %%rdi\n\t" /* i = 0 */
33                 ".REPEAT:\n\t"
34                 "cmpl %%edi, %%ecx\n\t" /* if (i == n) */
35                 "je .DONE\n\t"
36                 "movq (%%rbx,%%rdi,4), %%rdx\n\t" /* tmp = values[i]; 64 bit register */
37                 "addl %%edx, %%eax\n\t" /* sum += tmp[31:0]; */
38                 "incl %%edi\n\t" /* i++ */
39                 "jmp .REPEAT\n\t"
40                 ".DONE:\n\t"
41                 : "=a"(sum)
42                 : "b"(values), "c"(n), "0"(sum)
43                 : "%rdx", "%rdi", "cc"
44                 );
45 #else
46         unsigned int i;
47         for (i = 0; i < n; i++)
48                 sum += values[i];
49 #endif
50         return sum;
51 }
52
53 int main(void)
54 {
55         int *values;
56         int i;
57         int sum;
58         int expected;
59         int n = SIZE;
60
61         srand(time(0));
62
63         values = malloc(n * sizeof(*values));
64
65         expected = 0;
66         for (i = 0; i < n; i++) {
67                 values[i] = rand();
68                 expected += values[i];
69         }
70
71         sum = array_sum(values, n);
72
73         printf("expected = %d; sum = %d; %s\n", expected, sum, sum == expected ? "OK" : "FAILED");
74         return (sum == expected);
75 }