]> git.sesse.net Git - ffmpeg/blob - tests/checkasm/checkasm.c
Merge commit 'a9a2f3613040c4f90bf15cbd76f8671252ecc043'
[ffmpeg] / tests / checkasm / checkasm.c
1 /*
2  * Assembly testing and benchmarking tool
3  * Copyright (c) 2015 Henrik Gramner
4  * Copyright (c) 2008 Loren Merritt
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include "checkasm.h"
28 #include "libavutil/common.h"
29 #include "libavutil/cpu.h"
30 #include "libavutil/random_seed.h"
31
32 #if ARCH_X86
33 #include "libavutil/x86/cpu.h"
34 #endif
35
36 #if HAVE_SETCONSOLETEXTATTRIBUTE
37 #include <windows.h>
38 #define COLOR_RED    FOREGROUND_RED
39 #define COLOR_GREEN  FOREGROUND_GREEN
40 #define COLOR_YELLOW (FOREGROUND_RED|FOREGROUND_GREEN)
41 #else
42 #define COLOR_RED    1
43 #define COLOR_GREEN  2
44 #define COLOR_YELLOW 3
45 #endif
46
47 #if HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 #if !HAVE_ISATTY
52 #define isatty(fd) 1
53 #endif
54
55 /* List of tests to invoke */
56 static void (* const tests[])(void) = {
57 #if CONFIG_H264PRED
58     checkasm_check_h264pred,
59 #endif
60     NULL
61 };
62
63 /* List of cpu flags to check */
64 static const struct {
65     const char *name;
66     const char *suffix;
67     int flag;
68 } cpus[] = {
69 #if ARCH_X86
70     { "MMX",      "mmx",      AV_CPU_FLAG_MMX|AV_CPU_FLAG_CMOV },
71     { "MMXEXT",   "mmxext",   AV_CPU_FLAG_MMXEXT },
72     { "3DNOW",    "3dnow",    AV_CPU_FLAG_3DNOW },
73     { "3DNOWEXT", "3dnowext", AV_CPU_FLAG_3DNOWEXT },
74     { "SSE",      "sse",      AV_CPU_FLAG_SSE },
75     { "SSE2",     "sse2",     AV_CPU_FLAG_SSE2|AV_CPU_FLAG_SSE2SLOW },
76     { "SSE3",     "sse3",     AV_CPU_FLAG_SSE3|AV_CPU_FLAG_SSE3SLOW },
77     { "SSSE3",    "ssse3",    AV_CPU_FLAG_SSSE3|AV_CPU_FLAG_ATOM },
78     { "SSE4.1",   "sse4",     AV_CPU_FLAG_SSE4 },
79     { "SSE4.2",   "sse42",    AV_CPU_FLAG_SSE42 },
80     { "AVX",      "avx",      AV_CPU_FLAG_AVX },
81     { "XOP",      "xop",      AV_CPU_FLAG_XOP },
82     { "FMA3",     "fma3",     AV_CPU_FLAG_FMA3 },
83     { "FMA4",     "fma4",     AV_CPU_FLAG_FMA4 },
84     { "AVX2",     "avx2",     AV_CPU_FLAG_AVX2 },
85 #endif
86     { NULL }
87 };
88
89 typedef struct CheckasmFuncVersion {
90     struct CheckasmFuncVersion *next;
91     intptr_t (*func)();
92     int ok;
93     int cpu;
94     int iterations;
95     uint64_t cycles;
96 } CheckasmFuncVersion;
97
98 /* Binary search tree node */
99 typedef struct CheckasmFunc {
100     struct CheckasmFunc *child[2];
101     CheckasmFuncVersion versions;
102     char name[1];
103 } CheckasmFunc;
104
105 /* Internal state */
106 static struct {
107     CheckasmFunc *funcs;
108     CheckasmFunc *current_func;
109     CheckasmFuncVersion *current_func_ver;
110     const char *bench_pattern;
111     int bench_pattern_len;
112     int num_checked;
113     int num_failed;
114     int nop_time;
115     int cpu_flag;
116     const char *cpu_flag_name;
117 } state;
118
119 /* PRNG state */
120 AVLFG checkasm_lfg;
121
122 /* Print colored text to stderr if the terminal supports it */
123 static void color_printf(int color, const char *fmt, ...)
124 {
125     static int use_color = -1;
126     va_list arg;
127
128 #if HAVE_SETCONSOLETEXTATTRIBUTE
129     static HANDLE con;
130     static WORD org_attributes;
131
132     if (use_color < 0) {
133         CONSOLE_SCREEN_BUFFER_INFO con_info;
134         con = GetStdHandle(STD_ERROR_HANDLE);
135         if (con && con != INVALID_HANDLE_VALUE && GetConsoleScreenBufferInfo(con, &con_info)) {
136             org_attributes = con_info.wAttributes;
137             use_color = 1;
138         } else
139             use_color = 0;
140     }
141     if (use_color)
142         SetConsoleTextAttribute(con, (org_attributes & 0xfff0) | (color & 0x0f));
143 #else
144     if (use_color < 0) {
145         const char *term = getenv("TERM");
146         use_color = term && strcmp(term, "dumb") && isatty(2);
147     }
148     if (use_color)
149         fprintf(stderr, "\x1b[%d;3%dm", (color & 0x08) >> 3, color & 0x07);
150 #endif
151
152     va_start(arg, fmt);
153     vfprintf(stderr, fmt, arg);
154     va_end(arg);
155
156     if (use_color) {
157 #if HAVE_SETCONSOLETEXTATTRIBUTE
158         SetConsoleTextAttribute(con, org_attributes);
159 #else
160         fprintf(stderr, "\x1b[0m");
161 #endif
162     }
163 }
164
165 /* Deallocate a tree */
166 static void destroy_func_tree(CheckasmFunc *f)
167 {
168     if (f) {
169         CheckasmFuncVersion *v = f->versions.next;
170         while (v) {
171             CheckasmFuncVersion *next = v->next;
172             free(v);
173             v = next;
174         }
175
176         destroy_func_tree(f->child[0]);
177         destroy_func_tree(f->child[1]);
178         free(f);
179     }
180 }
181
182 /* Allocate a zero-initialized block, clean up and exit on failure */
183 static void *checkasm_malloc(size_t size)
184 {
185     void *ptr = calloc(1, size);
186     if (!ptr) {
187         fprintf(stderr, "checkasm: malloc failed\n");
188         destroy_func_tree(state.funcs);
189         exit(1);
190     }
191     return ptr;
192 }
193
194 /* Get the suffix of the specified cpu flag */
195 static const char *cpu_suffix(int cpu)
196 {
197     int i = FF_ARRAY_ELEMS(cpus);
198
199     while (--i >= 0)
200         if (cpu & cpus[i].flag)
201             return cpus[i].suffix;
202
203     return "c";
204 }
205
206 #ifdef AV_READ_TIME
207 static int cmp_nop(const void *a, const void *b)
208 {
209     return *(const uint16_t*)a - *(const uint16_t*)b;
210 }
211
212 /* Measure the overhead of the timing code (in decicycles) */
213 static int measure_nop_time(void)
214 {
215     uint16_t nops[10000];
216     int i, nop_sum = 0;
217
218     for (i = 0; i < 10000; i++) {
219         uint64_t t = AV_READ_TIME();
220         nops[i] = AV_READ_TIME() - t;
221     }
222
223     qsort(nops, 10000, sizeof(uint16_t), cmp_nop);
224     for (i = 2500; i < 7500; i++)
225         nop_sum += nops[i];
226
227     return nop_sum / 500;
228 }
229
230 /* Print benchmark results */
231 static void print_benchs(CheckasmFunc *f)
232 {
233     if (f) {
234         print_benchs(f->child[0]);
235
236         /* Only print functions with at least one assembly version */
237         if (f->versions.cpu || f->versions.next) {
238             CheckasmFuncVersion *v = &f->versions;
239             do {
240                 if (v->iterations) {
241                     int decicycles = (10*v->cycles/v->iterations - state.nop_time) / 4;
242                     printf("%s_%s: %d.%d\n", f->name, cpu_suffix(v->cpu), decicycles/10, decicycles%10);
243                 }
244             } while ((v = v->next));
245         }
246
247         print_benchs(f->child[1]);
248     }
249 }
250 #endif
251
252 /* ASCIIbetical sort except preserving natural order for numbers */
253 static int cmp_func_names(const char *a, const char *b)
254 {
255     int ascii_diff, digit_diff;
256
257     for (; !(ascii_diff = *a - *b) && *a; a++, b++);
258     for (; av_isdigit(*a) && av_isdigit(*b); a++, b++);
259
260     return (digit_diff = av_isdigit(*a) - av_isdigit(*b)) ? digit_diff : ascii_diff;
261 }
262
263 /* Get a node with the specified name, creating it if it doesn't exist */
264 static CheckasmFunc *get_func(const char *name, int length)
265 {
266     CheckasmFunc *f, **f_ptr = &state.funcs;
267
268     /* Search the tree for a matching node */
269     while ((f = *f_ptr)) {
270         int cmp = cmp_func_names(name, f->name);
271         if (!cmp)
272             return f;
273
274         f_ptr = &f->child[(cmp > 0)];
275     }
276
277     /* Allocate and insert a new node into the tree */
278     f = *f_ptr = checkasm_malloc(sizeof(CheckasmFunc) + length);
279     memcpy(f->name, name, length+1);
280
281     return f;
282 }
283
284 /* Perform tests and benchmarks for the specified cpu flag if supported by the host */
285 static void check_cpu_flag(const char *name, int flag)
286 {
287     int old_cpu_flag = state.cpu_flag;
288
289     flag |= old_cpu_flag;
290     av_set_cpu_flags_mask(flag);
291     state.cpu_flag = av_get_cpu_flags();
292
293     if (!flag || state.cpu_flag != old_cpu_flag) {
294         int i;
295
296         state.cpu_flag_name = name;
297         for (i = 0; tests[i]; i++)
298             tests[i]();
299     }
300 }
301
302 /* Print the name of the current CPU flag, but only do it once */
303 static void print_cpu_name(void)
304 {
305     if (state.cpu_flag_name) {
306         color_printf(COLOR_YELLOW, "%s:\n", state.cpu_flag_name);
307         state.cpu_flag_name = NULL;
308     }
309 }
310
311 int main(int argc, char *argv[])
312 {
313     int i, seed, ret = 0;
314
315     if (!tests[0] || !cpus[0].flag) {
316         fprintf(stderr, "checkasm: no tests to perform\n");
317         return 1;
318     }
319
320     if (argc > 1 && !strncmp(argv[1], "--bench", 7)) {
321 #ifndef AV_READ_TIME
322         fprintf(stderr, "checkasm: --bench is not supported on your system\n");
323         return 1;
324 #endif
325         if (argv[1][7] == '=') {
326             state.bench_pattern = argv[1] + 8;
327             state.bench_pattern_len = strlen(state.bench_pattern);
328         } else
329             state.bench_pattern = "";
330
331         argc--;
332         argv++;
333     }
334
335     seed = (argc > 1) ? atoi(argv[1]) : av_get_random_seed();
336     fprintf(stderr, "checkasm: using random seed %u\n", seed);
337     av_lfg_init(&checkasm_lfg, seed);
338
339     check_cpu_flag(NULL, 0);
340     for (i = 0; cpus[i].flag; i++)
341         check_cpu_flag(cpus[i].name, cpus[i].flag);
342
343     if (state.num_failed) {
344         fprintf(stderr, "checkasm: %d of %d tests have failed\n", state.num_failed, state.num_checked);
345         ret = 1;
346     } else {
347         fprintf(stderr, "checkasm: all %d tests passed\n", state.num_checked);
348 #ifdef AV_READ_TIME
349         if (state.bench_pattern) {
350             state.nop_time = measure_nop_time();
351             printf("nop: %d.%d\n", state.nop_time/10, state.nop_time%10);
352             print_benchs(state.funcs);
353         }
354 #endif
355     }
356
357     destroy_func_tree(state.funcs);
358     return ret;
359 }
360
361 /* Decide whether or not the specified function needs to be tested and
362  * allocate/initialize data structures if needed. Returns a pointer to a
363  * reference function if the function should be tested, otherwise NULL */
364 intptr_t (*checkasm_check_func(intptr_t (*func)(), const char *name, ...))()
365 {
366     char name_buf[256];
367     intptr_t (*ref)() = func;
368     CheckasmFuncVersion *v;
369     int name_length;
370     va_list arg;
371
372     va_start(arg, name);
373     name_length = vsnprintf(name_buf, sizeof(name_buf), name, arg);
374     va_end(arg);
375
376     if (!func || name_length <= 0 || name_length >= sizeof(name_buf))
377         return NULL;
378
379     state.current_func = get_func(name_buf, name_length);
380     v = &state.current_func->versions;
381
382     if (v->func) {
383         CheckasmFuncVersion *prev;
384         do {
385             /* Only test functions that haven't already been tested */
386             if (v->func == func)
387                 return NULL;
388
389             if (v->ok)
390                 ref = v->func;
391
392             prev = v;
393         } while ((v = v->next));
394
395         v = prev->next = checkasm_malloc(sizeof(CheckasmFuncVersion));
396     }
397
398     v->func = func;
399     v->ok = 1;
400     v->cpu = state.cpu_flag;
401     state.current_func_ver = v;
402
403     if (state.cpu_flag)
404         state.num_checked++;
405
406     return ref;
407 }
408
409 /* Decide whether or not the current function needs to be benchmarked */
410 int checkasm_bench_func(void)
411 {
412     return !state.num_failed && state.bench_pattern &&
413            !strncmp(state.current_func->name, state.bench_pattern, state.bench_pattern_len);
414 }
415
416 /* Indicate that the current test has failed */
417 void checkasm_fail_func(const char *msg, ...)
418 {
419     if (state.current_func_ver->cpu && state.current_func_ver->ok) {
420         va_list arg;
421
422         print_cpu_name();
423         fprintf(stderr, "   %s_%s (", state.current_func->name, cpu_suffix(state.current_func_ver->cpu));
424         va_start(arg, msg);
425         vfprintf(stderr, msg, arg);
426         va_end(arg);
427         fprintf(stderr, ")\n");
428
429         state.current_func_ver->ok = 0;
430         state.num_failed++;
431     }
432 }
433
434 /* Update benchmark results of the current function */
435 void checkasm_update_bench(int iterations, uint64_t cycles)
436 {
437     state.current_func_ver->iterations += iterations;
438     state.current_func_ver->cycles += cycles;
439 }
440
441 /* Print the outcome of all tests performed since the last time this function was called */
442 void checkasm_report(const char *name, ...)
443 {
444     static int prev_checked, prev_failed, max_length;
445
446     if (state.num_checked > prev_checked) {
447         print_cpu_name();
448
449         if (*name) {
450             int pad_length = max_length;
451             va_list arg;
452
453             fprintf(stderr, " - ");
454             va_start(arg, name);
455             pad_length -= vfprintf(stderr, name, arg);
456             va_end(arg);
457             fprintf(stderr, "%*c", FFMAX(pad_length, 0) + 2, '[');
458         } else
459             fprintf(stderr, " - %-*s [", max_length, state.current_func->name);
460
461         if (state.num_failed == prev_failed)
462             color_printf(COLOR_GREEN, "OK");
463         else
464             color_printf(COLOR_RED, "FAILED");
465         fprintf(stderr, "]\n");
466
467         prev_checked = state.num_checked;
468         prev_failed  = state.num_failed;
469     } else if (!state.cpu_flag) {
470         int length;
471
472         /* Calculate the amount of padding required to make the output vertically aligned */
473         if (*name) {
474             va_list arg;
475             va_start(arg, name);
476             length = vsnprintf(NULL, 0, name, arg);
477             va_end(arg);
478         } else
479             length = strlen(state.current_func->name);
480
481         if (length > max_length)
482             max_length = length;
483     }
484 }