Skip to content

Wow – This is Why I Want an LLVM Compiler!

March 19, 2015

A while ago I found an LLVM implementation for the Z80.  I downloaded and built it and ran a few examples.  Later, someone asked whether it actually supported C++.  I figured it would but hadn’t tried it so today i did with delightful results.

This example has two different definitions of the function foo(). The first one takes two arguments and returns the sum. The second takes a single argument and returns it as its value. The main procedure calls foo(1,2) so it should invoke the first foo().

short int foo(short int a, short int b) {
    short int result = a + b;   // r0 + r1
    return result;        // r0
}
short int foo(int a) {
    int result = a;   // r0
    return result;        // r0
}

int main(){
  return foo(1,2);
}

I was looking to see that i didn’t get a double definition error and what the mechanism for distinguishing was.

	.file	"exwjr1.cpp"
	.text
	.globl	_Z3fooss
	.type	_Z3fooss,@function
_Z3fooss:
	push	ix
	push	bc
	ld	ix, 0
	add	ix, sp
	ld	sp, ix
	ld	b, h
	ld	c, l
	ld	l, (ix+6)
	ld	h, (ix+7)
	add	hl, bc
	pop	bc
	pop	ix
	ret
.tmp0:
	.size	_Z3fooss, .tmp0-_Z3fooss

	.globl	_Z3fooi
	.type	_Z3fooi,@function
_Z3fooi:
	ret
.tmp1:
	.size	_Z3fooi, .tmp1-_Z3fooi

	.globl	main
	.type	main,@function
main:
	ld	hl, 3
	ret
.tmp2:
	.size	main, .tmp2-main

In fact, I did not get an error, and the way of distinguishing my two foo’s was by tacking the argument types onto the name, so C++ is clearly supported. Two things really impressed me though.

  1. The second foo variant just returns it’s first argument – Clang generated only a “ret” since the argument was already in HL which is also the return value register.
  2. My call to foo from main had constant arguments so Clang looked at the code being called and just calculated the result as a constant at compile time. This is nothing short of splendid!

I’m not at all sure what the Z80 code in the first foo is doing but i assume it’s at least correct if not optimal.

Advertisements

From → LLVM

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: