aboutsummaryrefslogtreecommitdiff
path: root/src/main.c
blob: d6abb2d1918c8602681dbb69c217debc83e1d802 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

#include <qbt/parser.h>
#include <qbt/opt.h>
#include <qbt/asm.h>
#include <qbt/debug.h>

static char *read_file(const char *file, FILE *f)
{
	fseek(f, 0, SEEK_END);
	/** @todo check how well standardized this actually is */
	long s = ftell(f);
	if (s == LONG_MAX) {
		error("%s might be a directory", file);
		return NULL;
	}

	fseek(f, 0, SEEK_SET);

	char *buf = malloc(s + 1);
	if (!buf)
		return NULL;

	fread(buf, s + 1, 1, f);
	/* remember terminating null */
	buf[s] = 0;
	return buf;
}

static void usage(FILE *f)
{
	fprintf(f, "qbt <file>.qbt\n");
}

int main(int argc, char *argv[])
{
	if (argc != 2) {
		usage(stdout);
		return -1;
	}

	char *fname = argv[1];
	FILE *f = fopen(fname, "rb");
	if (!f) {
		fprintf(stderr, "couldn't open %s\n", fname);
		return -1;
	}

	char *buf = read_file(fname, f);
	fclose(f);

	struct parser *p = create_parser();
	parse(p, fname, buf);

	foreach_fn(i, p->fns) {
		struct fn_map m = fn_at(p->fns, i);
		dump_function(m.fn);
		// also handles things like register mapping etc.
		optimize(m.fn);
		dump_function(m.fn);
		// for now
		output(m.fn, stdout);
	}

	destroy_parser(p);
	free(buf);
}