raz / test / mac / NarrowArgs.c

69 lines · 2.9 KiB · raw · history · last change b6a29ae3

1/* NarrowArgs's C side (test/mac.sh): built by cc into a library, which
2 the raz program links; with -DMAIN, built as a program that prints
3 what NarrowArgs.expect holds, so that C itself says what is right. */
4#include <stdarg.h>
5#include <stdint.h>
6#include <stdio.h>
7
8/* A running hash: each value changes every digit after it */
9static int64_t mix(int64_t h, int64_t v) { return (int64_t)((uint64_t)h * 1000003u + (uint64_t)v); }
10
11/* Eight integers in x0 to x7; then, on the stack, packed by size as
12 Apple's convention has it, i at 0, j at 1, k at 2, l at 4, m at 8, n
13 at 16, y at 24, z at 32 and last at 40; the reals p to w in v0 to v7 */
14int64_t narrow(int8_t a, uint8_t b, int16_t c, int32_t d, int64_t e, uint8_t f, int16_t g, int32_t h,
15 int8_t i, uint8_t j, int16_t k, int32_t l, int8_t m, int64_t n,
16 float p, double q, float r, double s, float t, double u, float v, double w,
17 float y, double z, int8_t last) {
18 int64_t x = 7;
19 x = mix(x, a); x = mix(x, b); x = mix(x, c); x = mix(x, d);
20 x = mix(x, e); x = mix(x, f); x = mix(x, g); x = mix(x, h);
21 x = mix(x, i); x = mix(x, j); x = mix(x, k); x = mix(x, l);
22 x = mix(x, m); x = mix(x, n);
23 x = mix(x, (int64_t)(p * 4)); x = mix(x, (int64_t)(q * 4));
24 x = mix(x, (int64_t)(r * 4)); x = mix(x, (int64_t)(s * 4));
25 x = mix(x, (int64_t)(t * 4)); x = mix(x, (int64_t)(u * 4));
26 x = mix(x, (int64_t)(v * 4)); x = mix(x, (int64_t)(w * 4));
27 x = mix(x, (int64_t)(y * 4)); x = mix(x, (int64_t)(z * 4));
28 x = mix(x, last);
29 return x;
30}
31
32/* A variadic procedure: its arguments past n all go on the stack, each 8 bytes */
33int64_t varsum(int n, ...) {
34 va_list ap;
35 int64_t x = 7;
36 int k;
37 va_start(ap, n);
38 for (k = 0; k < n; k++) {
39 if (k % 2 == 0) x = mix(x, va_arg(ap, int)); else x = mix(x, (int64_t)(va_arg(ap, double) * 4));
40 }
41 va_end(ap);
42 return x;
43}
44
45/* C calls back a procedure of ten integers, the last two on the stack */
46int64_t callback(int64_t (*cb)(int64_t, int64_t, int64_t, int64_t, int64_t,
47 int64_t, int64_t, int64_t, int64_t, int64_t)) {
48 return cb(1, -2, 3, -4, 5, -6, 7, -8, 9, -10);
49}
50
51#ifdef MAIN
52static int64_t mine(int64_t a, int64_t b, int64_t c, int64_t d, int64_t e,
53 int64_t f, int64_t g, int64_t h, int64_t i, int64_t j) {
54 int64_t x = 7;
55 x = mix(x, a); x = mix(x, b); x = mix(x, c); x = mix(x, d); x = mix(x, e);
56 x = mix(x, f); x = mix(x, g); x = mix(x, h); x = mix(x, i); x = mix(x, j);
57 return x;
58}
59
60int main(void) {
61 printf("%lld\n", (long long)narrow(-1, 200, -300, -70000, -5000000000LL, 255, -32768, 2147483647,
62 -128, 129, -2, -100000, 127, 9000000000LL,
63 1.5f, -2.25, 3.5f, 4.75, -5.5f, 6.25, 7.5f, -8.75,
64 9.5f, 10.25, -100));
65 printf("%lld\n", (long long)varsum(5, 1, 1.5, -3, -2.25, 5));
66 printf("%lld\n", (long long)callback(mine));
67 return 0;
68}
69#endif