Add standard library tutorial-3
authorLuke Lau <luke_lau@icloud.com>
Sat, 9 Nov 2019 18:20:12 +0000 (18:20 +0000)
committerLuke Lau <luke_lau@icloud.com>
Sat, 9 Nov 2019 18:37:05 +0000 (18:37 +0000)
We want to be able to call a function inside our for loop that has some
sort of side effect that we can observe: How about printing to stdout?
Our language isn't quite sophisticated enough yet to handle writing to
files and handles or make system calls, but we can work around this by
writing this code in another language and calling it from Kaleidoscope.

In this chapter we are going to write our standard library in C, but
feel free to experiment with compiling and linking other languages: Try
making raw system calls in assembly, or even writing it in Haskell!

The standard library contains one function, putchard, which takes in a
double and prints a character to stdout. It's the equivalent of
putchar(3), but since Kaleidoscope only works with doubles we need to
cast it first.

Once you have finished this chapter, you should now be able to run the
following code to print out a bunch of characters:

ready> extern putchard(x)

declare external ccc  double @putchard(double)

ready> for i = 0, i < 10 in putchard(42+i)

define external ccc  double @__anon_expr()    {

preheader_0:

  %initcond_0 = fcmp olt double 0.000000e0, 1.000000e1

  %initcond_1 = uitofp i1 %initcond_0 to double

  %initcond_2 = fcmp one double 0.000000e0, %initcond_1

  br i1 %initcond_2, label %loop_0, label %after_0

loop_0:

  %i_0 = phi double [0.000000e0, %preheader_0], [%nextvar_0, %loop_0]

  %body_0 = fadd double 4.200000e1, %i_0

  %body_1 =  call ccc  double  @putchard(double  %body_0)

  %nextvar_0 = fadd double %i_0, 1.000000e0

  %cond_0 = fcmp olt double %i_0, 1.000000e1

  %cond_1 = uitofp i1 %cond_0 to double

  %cond_2 = fcmp one double 0.000000e0, %cond_1

  br i1 %cond_2, label %loop_0, label %after_0

after_0:

  ret double 0.000000e0

}

Resolving MangledSymbol "_putchard" to 0x10574c2d0

*+,-./01234


Trivial merge