ref: afc55f2a912d03aab2cfde5de3ba76de6ece8ac3
parent: 42a80b685648b7cb5c417c00b7cc338dcbefc394
author: Roberto E. Vargas Caballero <[email protected]>
date: Thu Feb 12 07:35:24 EST 2015
Add optimize function() to cc2 This function runs all the possible optimizations that can be applied. At this moment only reduction of casting can be used.
--- a/cc2/Makefile
+++ b/cc2/Makefile
@@ -1,5 +1,5 @@
-OBJS = main.o parser.o cgen.o code.o
+OBJS = main.o parser.o cgen.o code.o optm.o
CPPFLAGS = -I../inc
LDFLAGS = -L../lib
--- a/cc2/cc2.h
+++ b/cc2/cc2.h
@@ -117,4 +117,5 @@
extern void apply(Node *list[], Node *(*fun)(Node *));
extern Symbol *parse(void);
extern void code(char op, ...);
+extern Node *optimize(Node *np);
extern void prtree(Node *np);
--- a/cc2/main.c
+++ b/cc2/main.c
@@ -31,6 +31,7 @@
Symbol *fun;
while (!feof(stdin) && (fun = parse())) {
+ apply(fun->u.f.body, optimize);
apply(fun->u.f.body, genaddable);
generate(fun);
}
--- /dev/null
+++ b/cc2/optm.c
@@ -1,0 +1,43 @@
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <cc.h>
+#include "cc2.h"
+
+
+#include <stdio.h>
+
+static Node *
+optcasts(Node *np, Type *tp)
+{
+ if (!np)
+ return NULL;
+
+repeat:
+ switch (np->op) {
+ case OCAST:
+ /* TODO: be careful with the sign */
+ if (np->type->c_int && np->type->size >= tp->size) {
+ np = np->left;
+ goto repeat;
+ }
+ break;
+ case OASSIG:
+ tp = np->type;
+ break;
+ default:
+ np->type = tp;
+ }
+
+ np->left = optcasts(np->left, tp);
+ np->right = optcasts(np->right, tp);
+ return np;
+}
+
+Node *
+optimize(Node *np)
+{
+ np = optcasts(np, np->type);
+ return np;
+}