Add an example about summing an array of integers
[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                 /* TODO: try incrementing the pointer by 4 */
37                 "movq (%%rbx,%%rdi,4), %%rdx\n\t" /* tmp = values[i]; 64 bit register */
38                 "addl %%edx, %%eax\n\t" /* sum += tmp[31:0]; */
39                 "incl %%edi\n\t" /* i++ */
40                 "jmp .REPEAT\n\t"
41                 ".DONE:\n\t"
42                 : "=a"(sum)
43                 : "b"(values), "c"(n), "0"(sum)
44                 : "%rdx", "%rdi", "cc"
45                 );
46 #else
47         unsigned int i;
48         for (i = 0; i < n; i++)
49                 sum += values[i];
50 #endif
51         return sum;
52 }
53
54 int main(void)
55 {
56         int *values;
57         int i;
58         int sum;
59         int expected;
60         int n = SIZE;
61
62         srand(time(0));
63
64         values = malloc(n * sizeof(*values));
65
66         expected = 0;
67         for (i = 0; i < n; i++) {
68                 values[i] = rand();
69                 expected += values[i];
70         }
71
72         sum = array_sum(values, n);
73
74         printf("expected = %d; sum = %d; %s\n", expected, sum, sum == expected ? "OK" : "FAILED");
75         return (sum == expected);
76 }