Created
September 24, 2017 19:03
-
-
Save eush77/c59f6711fbff19c0a63470a087d010b3 to your computer and use it in GitHub Desktop.
Example of a QBE pass
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function w $add(w %a, w %b) { # Define a function add | |
@start | |
%c =w add %a, %b # Adds the 2 arguments | |
ret %c # Return the result | |
} | |
function w $sum(w %n) { | |
@entry | |
%s =w add 0, 0 | |
@header | |
jnz %n, @body, @exit | |
@faux1 | |
jmp @faux2 | |
@body | |
%s =w add %s, %n | |
%n =w sub %n, 1 | |
jmp @header | |
@exit | |
ret %s | |
@faux2 | |
jmp @faux1 | |
} | |
export function w $main() { | |
@start | |
%r =w call $sum(w 3) | |
call $printf(l $fmt, w %r, ...) | |
ret 0 | |
} | |
data $fmt = { b "%d\n", b 0 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <qbe/all.h> | |
#include <stdbool.h> | |
#include <stdio.h> | |
void remove_dead_code (Fn *fn) { | |
if (!fn->nblk) { | |
return; | |
} | |
bool live_blocks[fn->nblk]; | |
memset(live_blocks, false, sizeof live_blocks); | |
live_blocks[0] = true; | |
for (bool changed = true; changed; ) { | |
changed = false; | |
for (Blk *blk = fn->start; blk; blk = blk->link) { | |
if (!live_blocks[blk->id]) { | |
continue; | |
} | |
Blk *succs[] = { blk->s1, blk->s2, NULL }; | |
for (Blk **psucc = succs; *psucc; ++psucc) { | |
Blk *succ = *psucc; | |
changed |= !live_blocks[succ->id]; | |
live_blocks[succ->id] = true; | |
} | |
} | |
} | |
for (Blk **pblk = &fn->start; *pblk; ) { | |
Blk *blk = *pblk; | |
if (live_blocks[blk->id]) { | |
pblk = &blk->link; | |
} | |
else { | |
edgedel(blk, &blk->s1); | |
edgedel(blk, &blk->s2); | |
*pblk = blk->link; | |
} | |
} | |
} | |
void read_fn (Fn *fn) { | |
remove_dead_code(fn); | |
printfn(fn, stdout); | |
} | |
void read_dat (Dat *dat) { | |
static bool s_comma = false; | |
switch (dat->type) { | |
case DStart: | |
break; | |
case DEnd: | |
printf(" }\n"); | |
s_comma = false; | |
break; | |
case DName: | |
printf("data $%s = { ", dat->u.ref.nam); | |
break; | |
case DB: | |
if (s_comma) { | |
printf(", "); | |
} | |
else { | |
s_comma = true; | |
} | |
printf("b "); | |
if (dat->u.num) { | |
printf("\"%s\"", dat->u.str); | |
} | |
else { | |
printf("0"); | |
} | |
break; | |
default: | |
die("Unsupported Dat type"); | |
} | |
} | |
int main () { | |
parse(stdin, "stdin", read_dat, read_fn); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment