Add an example about summing an array of integers
[experiments/inline-assembly.git] / inline-asm-array-sum.c
diff --git a/inline-asm-array-sum.c b/inline-asm-array-sum.c
new file mode 100644 (file)
index 0000000..7eb7ae8
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * inline-asm-array-sum - an example of inline assembly accessing arrays
+ *
+ * Copyright (C) 2013  Antonio Ospite <ospite@studenti.unina.it>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+
+#define SIZE 10000001
+
+static int array_sum(int *values, unsigned int n)
+{
+       int sum = 0;
+
+#if defined(__x86_64__)
+       __asm__(
+               "movq $0, %%rdi\n\t" /* i = 0 */
+               ".REPEAT:\n\t"
+               "cmpl %%edi, %%ecx\n\t" /* if (i == n) */
+               "je .DONE\n\t"
+               /* TODO: try incrementing the pointer by 4 */
+               "movq (%%rbx,%%rdi,4), %%rdx\n\t" /* tmp = values[i]; 64 bit register */
+               "addl %%edx, %%eax\n\t" /* sum += tmp[31:0]; */
+               "incl %%edi\n\t" /* i++ */
+               "jmp .REPEAT\n\t"
+               ".DONE:\n\t"
+               : "=a"(sum)
+               : "b"(values), "c"(n), "0"(sum)
+               : "%rdx", "%rdi", "cc"
+               );
+#else
+       unsigned int i;
+       for (i = 0; i < n; i++)
+               sum += values[i];
+#endif
+       return sum;
+}
+
+int main(void)
+{
+       int *values;
+       int i;
+       int sum;
+       int expected;
+       int n = SIZE;
+
+       srand(time(0));
+
+       values = malloc(n * sizeof(*values));
+
+       expected = 0;
+       for (i = 0; i < n; i++) {
+               values[i] = rand();
+               expected += values[i];
+       }
+
+       sum = array_sum(values, n);
+
+       printf("expected = %d; sum = %d; %s\n", expected, sum, sum == expected ? "OK" : "FAILED");
+       return (sum == expected);
+}