-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathllvm_builder.jou
590 lines (496 loc) · 25.2 KB
/
llvm_builder.jou
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# This file abstracts away all LLVM things needed to build the LLVM IR for a
# function or method.
#
# The idea is that instead of building just LLVM IR, we can also build other
# useful data structures by modifying only the IR builder, such as UVG. This
# means we don't walk through the AST in multiple different places that could
# handle some corner cases differently.
import "stdlib/math.jou"
import "stdlib/mem.jou"
import "stdlib/str.jou"
import "stdlib/io.jou"
import "../errors_and_warnings.jou"
import "../ast.jou"
import "./either_builder.jou"
import "../llvm.jou"
import "../target.jou"
import "../types.jou"
import "./ast_to_builder.jou"
# LLVM doesn't have a built-in union type, and you're supposed to abuse other types for that:
# https://mapping-high-level-constructs-to-llvm-ir.readthedocs.io/en/latest/basic-constructs/unions.html
#
# My first idea was to use an array of bytes that is big enough to fit anything.
# However, that might not be aligned properly.
#
# Then I tried choosing the member type that has the biggest align, and making a large enough array of it.
# Because the align is always a power of two, the memory will be suitably aligned for all member types.
# But it didn't work for some reason I still don't understand.
#
# Then I figured out how clang does it and did it the same way.
# We make a struct that contains:
# - the most aligned type as chosen before
# - array of i8 as padding to make it the right size.
# But for some reason that didn't work either.
#
# As a "last resort" I just use an array of i64 large enough and hope it's aligned as needed.
def union_type_to_llvm(types: LLVMType**, ntypes: int) -> LLVMType*:
# For some reason uncommenting this makes stuff compile almost 2x slower...
#if ntypes == 1:
# return types[0]
sizeneeded = 0L
for i = 0; i < ntypes; i++:
size1 = LLVMABISizeOfType(target.target_data, types[i])
size2 = LLVMStoreSizeOfType(target.target_data, types[i])
# If this assert fails, you need to figure out which of the size functions should be used.
# I don't know what their difference is.
# And if you need the alignment, there's 3 different functions for that...
assert size1 == size2
sizeneeded = llmax(sizeneeded, size1)
return LLVMArrayType(LLVMInt64Type(), ((sizeneeded+7)/8) as int)
def class_type_to_llvm(type: Type*) -> LLVMType*:
assert type->kind == TypeKind.Class
n = type->classdata.nfields
flat_elems: LLVMType** = malloc(sizeof(flat_elems[0]) * n)
for i = 0; i < n; i++:
flat_elems[i] = type_to_llvm(type->classdata.fields[i].type)
# Combine together fields of the same union.
combined: LLVMType** = malloc(sizeof(combined[0]) * n)
combinedlen = 0
for start = 0; start < n; start = end:
end = start + 1
while end < n and type->classdata.fields[start].union_id == type->classdata.fields[end].union_id:
end++
combined[combinedlen++] = union_type_to_llvm(&flat_elems[start], end-start)
result = LLVMStructType(combined, combinedlen, False as int)
free(flat_elems)
free(combined)
return result
def type_to_llvm(type: Type*) -> LLVMType*:
match type->kind:
case TypeKind.Array:
return LLVMArrayType(type_to_llvm(type->array.item_type), type->array.len)
case TypeKind.Pointer | TypeKind.VoidPointer:
# Element type doesn't matter in new LLVM versions.
return LLVMPointerType(LLVMInt8Type(), 0)
case TypeKind.FloatingPoint:
if type->size_in_bits == 32:
return LLVMFloatType()
if type->size_in_bits == 64:
return LLVMDoubleType()
assert False
case TypeKind.SignedInteger | TypeKind.UnsignedInteger:
return LLVMIntType(type->size_in_bits)
case TypeKind.Bool:
return LLVMInt1Type()
case TypeKind.OpaqueClass:
# this is compiler internal/temporary thing and should never end up here
assert False
case TypeKind.Class:
return class_type_to_llvm(type)
case TypeKind.Enum:
return LLVMInt32Type()
def signature_to_llvm(sig: Signature*) -> LLVMType*:
assert sig->nargs <= 100
argtypes: LLVMType*[100]
for i = 0; i < sig->nargs; i++:
argtypes[i] = type_to_llvm(sig->argtypes[i])
# TODO: tell llvm, if we know a function is noreturn ?
if sig->returntype == NULL: # "-> noreturn" or "-> None"
returntype = LLVMVoidType()
else:
returntype = type_to_llvm(sig->returntype)
return LLVMFunctionType(returntype, argtypes, sig->nargs, sig->takes_varargs as int)
def declare_in_llvm(sig: Signature*, mod: LLVMModule*) -> LLVMValue*:
fullname: byte[500]
self_class = sig->get_self_class()
if self_class == NULL:
# function
snprintf(fullname, sizeof(fullname), "%s", sig->name)
else:
# method
snprintf(fullname, sizeof(fullname), "%s.%s", self_class->name, sig->name)
# Make it so that this can be called many times without issue
llvm_func = LLVMGetNamedFunction(mod, fullname)
if llvm_func == NULL:
llvm_func = LLVMAddFunction(mod, fullname, signature_to_llvm(sig))
assert llvm_func != NULL
return llvm_func
def build_llvm_signed_mod(builder: LLVMBuilder*, lhs: LLVMValue*, rhs: LLVMValue*) -> LLVMValue*:
# Jou's % operator ensures that a%b has same sign as b:
# jou_mod(a, b) = llvm_mod(llvm_mod(a, b) + b, b)
llmod = LLVMBuildSRem(builder, lhs, rhs, "smod_tmp")
sum = LLVMBuildAdd(builder, llmod, rhs, "smod_tmp")
return LLVMBuildSRem(builder, sum, rhs, "smod")
def build_llvm_signed_div(builder: LLVMBuilder*, lhs: LLVMValue*, rhs: LLVMValue*) -> LLVMValue*:
# LLVM's provides two divisions. One truncates, the other is an "exact div"
# that requires there is no remainder. Jou uses floor division which is
# neither of the two, but is quite easy to implement:
#
# floordiv(a, b) = exact_div(a - jou_mod(a, b), b)
#
top = LLVMBuildSub(builder, lhs, build_llvm_signed_mod(builder, lhs, rhs), "sdiv_tmp")
return LLVMBuildExactSDiv(builder, top, rhs, "sdiv")
def build_llvm_cast(builder: LLVMBuilder*, obj: LLVMValue*, from: Type*, to: Type*) -> LLVMValue*:
assert from != NULL
assert to != NULL
# Always treat enums as ints
if from->kind == TypeKind.Enum:
from = intType
if to->kind == TypeKind.Enum:
to = intType
if from == to:
return obj
if from->is_pointer_type() and to->is_pointer_type():
# All pointers are the same type in LLVM
return obj
if from->is_number_type() and to->is_number_type():
if from->is_integer_type() and to->is_integer_type():
# Examples:
# signed 8-bit 0xFF (-1) --> 16-bit 0xFFFF (-1 or max value)
# unsigned 8-bit 0xFF (255) --> 16-bit 0x00FF (255)
return LLVMBuildIntCast2(builder, obj, type_to_llvm(to), (from->kind == TypeKind.SignedInteger) as int, "cast")
if from->is_integer_type() and to->kind == TypeKind.FloatingPoint:
# integer --> double/float
if from->kind == TypeKind.SignedInteger:
return LLVMBuildSIToFP(builder, obj, type_to_llvm(to), "cast")
else:
return LLVMBuildUIToFP(builder, obj, type_to_llvm(to), "cast")
if from->kind == TypeKind.FloatingPoint and to->is_integer_type():
# double/float --> integer
if to->kind == TypeKind.SignedInteger:
return LLVMBuildFPToSI(builder, obj, type_to_llvm(to), "cast")
else:
return LLVMBuildFPToUI(builder, obj, type_to_llvm(to), "cast")
if from->kind == TypeKind.FloatingPoint and to->kind == TypeKind.FloatingPoint:
# double/float --> double/float
return LLVMBuildFPCast(builder, obj, type_to_llvm(to), "cast")
assert False
if from->is_integer_type() and to->is_pointer_type():
return LLVMBuildIntToPtr(builder, obj, type_to_llvm(to), "cast")
if from->is_pointer_type() and to->is_integer_type():
return LLVMBuildPtrToInt(builder, obj, type_to_llvm(to), "cast")
if from == boolType and to->is_integer_type():
return LLVMBuildIntCast2(builder, obj, type_to_llvm(to), False as int, "cast")
printf("cast failed: %s --> %s\n", from->name, to->name)
assert False
# TODO: useful, but doesn't belong here
def find_enum_member(enumtype: Type*, name: byte*) -> int:
assert enumtype->kind == TypeKind.Enum
for i = 0; i < enumtype->enummembers.count; i++:
if strcmp(enumtype->enummembers.names[i], name) == 0:
return i
assert False
class LBuilderValue:
type: Type*
llvm_value: LLVMValue*
# Not named LLVMBuilder because that is the name of LLVM's thing.
class LBuilder:
llvm_module: LLVMModule*
llvm_builder: LLVMBuilder*
llvm_func: LLVMValue*
alloca_block: LLVMBasicBlock* # local variables created here before code of function runs
code_start_block: LLVMBasicBlock*
current_block: LLVMBasicBlock*
returns_a_value: bool
def begin_function(self, sig: Signature*, public: bool) -> None:
self->llvm_func = declare_in_llvm(sig, self->llvm_module)
self->returns_a_value = sig->returntype != NULL
self->alloca_block = LLVMAppendBasicBlock(self->llvm_func, "alloca")
self->code_start_block = LLVMAppendBasicBlock(self->llvm_func, "code_start")
LLVMPositionBuilderAtEnd(self->llvm_builder, self->code_start_block)
self->current_block = self->code_start_block
if not public:
LLVMSetLinkage(self->llvm_func, LLVMLinkage.Private)
def end_function(self) -> None:
if self->returns_a_value:
# Implicit "return" at the end of a function that should return a value
LLVMBuildUnreachable(self->llvm_builder)
else:
LLVMBuildRetVoid(self->llvm_builder)
LLVMPositionBuilderAtEnd(self->llvm_builder, self->alloca_block)
LLVMBuildBr(self->llvm_builder, self->code_start_block)
# TODO: use the location for debug info
def set_location(self, location: Location) -> None:
pass
def stack_alloc(self, t: Type*, varname: byte*) -> LBuilderValue:
if varname == NULL:
debug_name = "stack_alloc"
else:
debug_name = varname
# Place all allocations to the same block at start of function, so that
# we don't overflow the stack when the part of code that creates local
# var runs many times.
LLVMPositionBuilderAtEnd(self->llvm_builder, self->alloca_block)
llvm_ptr = LLVMBuildAlloca(self->llvm_builder, type_to_llvm(t), debug_name)
LLVMPositionBuilderAtEnd(self->llvm_builder, self->current_block)
llvm_ptr = LLVMBuildBitCast(self->llvm_builder, llvm_ptr, type_to_llvm(voidPtrType), "legacy_llvm14_cast")
return LBuilderValue{type = t->pointer_type(), llvm_value = llvm_ptr}
# TODO: Everything named legacy_llvm14_cast can be removed once we drop LLVM 14 support
# Needed due to LLVM opaque pointer types transition
#
# TODO: which casts are necessary on LLVM 14 and which are not?
# *ptr = value
def set_ptr(self, ptr: LBuilderValue, value: LBuilderValue) -> None:
if ptr.type != value.type->pointer_type():
printf("Cannot set value of %s to %s\n", ptr.type->name, value.type->name)
assert ptr.type == value.type->pointer_type()
ptr_type = LLVMPointerType(type_to_llvm(value.type), 0)
llvm_ptr = LLVMBuildBitCast(self->llvm_builder, ptr.llvm_value, ptr_type, "legacy_llvm14_cast")
LLVMBuildStore(self->llvm_builder, value.llvm_value, llvm_ptr)
# *ptr
def dereference(self, ptr: LBuilderValue) -> LBuilderValue:
assert ptr.type->kind == TypeKind.Pointer
llvm_result = LLVMBuildLoad2(self->llvm_builder, type_to_llvm(ptr.type->value_type), ptr.llvm_value, "dereference")
return LBuilderValue{type = ptr.type->value_type, llvm_value = llvm_result}
# Returns &ptr[index]
def indexed_pointer(self, ptr: LBuilderValue, index: LBuilderValue) -> LBuilderValue:
assert ptr.type->kind == TypeKind.Pointer
assert index.type == longType # doesn't work right if it's other type
llvm_result = LLVMBuildGEP2(
self->llvm_builder,
type_to_llvm(ptr.type->value_type),
ptr.llvm_value,
&index.llvm_value,
1,
"indexed_pointer",
)
llvm_result = LLVMBuildBitCast(self->llvm_builder, llvm_result, type_to_llvm(voidPtrType), "legacy_llvm14_cast")
return LBuilderValue{type = ptr.type, llvm_value = llvm_result}
# Returns &ptr->field
def class_field_pointer(self, ptr: LBuilderValue, field_name: byte*) -> LBuilderValue:
assert ptr.type->kind == TypeKind.Pointer
classtype = ptr.type->value_type
assert classtype->kind == TypeKind.Class
# TODO: method to find field
field: ClassField* = NULL
for f = classtype->classdata.fields; f < &classtype->classdata.fields[classtype->classdata.nfields]; f++:
if strcmp(f->name, field_name) == 0:
field = f
break
assert field != NULL
llvm_struct_type = type_to_llvm(classtype)
llvm_ptr = LLVMBuildBitCast(self->llvm_builder, ptr.llvm_value, LLVMPointerType(llvm_struct_type, 0), "legacy_llvm14_cast")
llvm_result = LLVMBuildStructGEP2(self->llvm_builder, llvm_struct_type, llvm_ptr, field->union_id, field->name)
llvm_result = LLVMBuildBitCast(self->llvm_builder, llvm_result, type_to_llvm(voidPtrType), "legacy_llvm14_cast")
return LBuilderValue{type = field->type->pointer_type(), llvm_value = llvm_result}
# &global_variable
def global_var_ptr(self, name: byte*, var_type: Type*) -> LBuilderValue:
llvm_result = LLVMGetNamedGlobal(self->llvm_module, name)
assert llvm_result != NULL
llvm_result = LLVMBuildBitCast(self->llvm_builder, llvm_result, type_to_llvm(voidPtrType), "legacy_llvm14_cast")
return LBuilderValue{type = var_type->pointer_type(), llvm_value = llvm_result}
# i'th argument given to this function
def get_argument(self, i: int, argtype: Type*) -> LBuilderValue:
llvm_result = LLVMGetParam(self->llvm_func, i)
return LBuilderValue{type = argtype, llvm_value = llvm_result}
# Function or method call, self included in args if method
def call(self, sig: Signature*, args: LBuilderValue*, nargs: int) -> LBuilderValue:
assert nargs >= sig->nargs
if nargs > sig->nargs:
assert sig->takes_varargs
assert nargs <= 100
llvm_args: LLVMValue*[100]
for i = 0; i < nargs; i++:
if i < sig->nargs:
# not a vararg
assert args[i].type == sig->argtypes[i]
llvm_args[i] = args[i].llvm_value
debug_name: byte[100] = ""
if sig->returntype != NULL:
snprintf(debug_name, sizeof(debug_name), "%s_return_value", sig->name)
llvm_func = declare_in_llvm(sig, self->llvm_module)
llvm_return_value = LLVMBuildCall2(self->llvm_builder, signature_to_llvm(sig), llvm_func, llvm_args, nargs, debug_name)
if sig->returntype == NULL:
return LBuilderValue{}
else:
assert llvm_return_value != NULL
return LBuilderValue{type = sig->returntype, llvm_value = llvm_return_value}
# string as array of bytes
def string_array(self, s: byte*, array_size: int) -> LBuilderValue:
assert strlen(s) < array_size
padded: byte* = malloc(array_size)
memset(padded, 0, array_size)
strcpy(padded, s)
llvm_array = LLVMConstString(padded, array_size, True as int)
free(padded)
return LBuilderValue{type = byteType->array_type(array_size), llvm_value = llvm_array}
# string as '\0' terminated pointer
def string(self, s: byte*) -> LBuilderValue:
llvm_array = self->string_array(s, (strlen(s) + 1) as int).llvm_value
llvm_string = LLVMAddGlobal(self->llvm_module, LLVMTypeOf(llvm_array), "string_literal")
LLVMSetLinkage(llvm_string, LLVMLinkage.Private) # This makes it a static global variable
LLVMSetInitializer(llvm_string, llvm_array)
llvm_string = LLVMBuildBitCast(self->llvm_builder, llvm_string, type_to_llvm(byteType->pointer_type()), "legacy_llvm14_cast")
return LBuilderValue{type = byteType->pointer_type(), llvm_value = llvm_string}
def boolean(self, b: bool) -> LBuilderValue:
return LBuilderValue{
type = boolType,
llvm_value = LLVMConstInt(LLVMInt1Type(), b as long, False as int),
}
def integer(self, t: Type*, value: long) -> LBuilderValue:
assert t->is_integer_type()
return LBuilderValue{
type = t,
llvm_value = LLVMConstInt(type_to_llvm(t), value, (t->kind == TypeKind.SignedInteger) as int),
}
def float_or_double(self, t: Type*, string: byte*) -> LBuilderValue:
assert t->kind == TypeKind.FloatingPoint
return LBuilderValue{
type = t,
llvm_value = LLVMConstRealOfString(type_to_llvm(t), string)
}
def zero_of_type(self, t: Type*) -> LBuilderValue:
return LBuilderValue{
type = t,
llvm_value = LLVMConstNull(type_to_llvm(t)),
}
def enum_member(self, t: Type*, name: byte*) -> LBuilderValue:
return LBuilderValue{
type = t,
llvm_value = LLVMConstInt(LLVMInt32Type(), find_enum_member(t, name), False as int),
}
# a + b
def add(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.FloatingPoint:
llvm_sum = LLVMBuildFAdd(self->llvm_builder, a.llvm_value, b.llvm_value, "float_sum")
case TypeKind.SignedInteger | TypeKind.UnsignedInteger:
llvm_sum = LLVMBuildAdd(self->llvm_builder, a.llvm_value, b.llvm_value, "int_sum")
case _:
assert False
return LBuilderValue{type = a.type, llvm_value = llvm_sum}
# a - b
def sub(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.FloatingPoint:
llvm_diff = LLVMBuildFSub(self->llvm_builder, a.llvm_value, b.llvm_value, "float_diff")
case TypeKind.SignedInteger | TypeKind.UnsignedInteger:
llvm_diff = LLVMBuildSub(self->llvm_builder, a.llvm_value, b.llvm_value, "int_diff")
case _:
assert False
return LBuilderValue{type = a.type, llvm_value = llvm_diff}
# a * b
def mul(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.FloatingPoint:
llvm_prod = LLVMBuildFMul(self->llvm_builder, a.llvm_value, b.llvm_value, "float_prod")
case TypeKind.SignedInteger | TypeKind.UnsignedInteger:
llvm_prod = LLVMBuildMul(self->llvm_builder, a.llvm_value, b.llvm_value, "int_prod")
case _:
assert False
return LBuilderValue{type = a.type, llvm_value = llvm_prod}
# a / b
def div(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.FloatingPoint:
llvm_quot = LLVMBuildFDiv(self->llvm_builder, a.llvm_value, b.llvm_value, "float_quot")
case TypeKind.SignedInteger:
llvm_quot = build_llvm_signed_div(self->llvm_builder, a.llvm_value, b.llvm_value)
case TypeKind.UnsignedInteger:
llvm_quot = LLVMBuildUDiv(self->llvm_builder, a.llvm_value, b.llvm_value, "uint_quot")
case _:
assert False
return LBuilderValue{type = a.type, llvm_value = llvm_quot}
# a % b
def mod(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.FloatingPoint:
llvm_mod = LLVMBuildFRem(self->llvm_builder, a.llvm_value, b.llvm_value, "float_mod")
case TypeKind.SignedInteger:
llvm_mod = build_llvm_signed_mod(self->llvm_builder, a.llvm_value, b.llvm_value)
case TypeKind.UnsignedInteger:
llvm_mod = LLVMBuildURem(self->llvm_builder, a.llvm_value, b.llvm_value, "uint_mod")
case _:
assert False
return LBuilderValue{type = a.type, llvm_value = llvm_mod}
# a == b
def eq(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.SignedInteger | TypeKind.UnsignedInteger | TypeKind.Enum | TypeKind.Bool:
llvm_result = LLVMBuildICmp(self->llvm_builder, LLVMIntPredicate.EQ, a.llvm_value, b.llvm_value, "eq")
case TypeKind.FloatingPoint:
llvm_result = LLVMBuildFCmp(self->llvm_builder, LLVMRealPredicate.OEQ, a.llvm_value, b.llvm_value, "eq")
case _:
assert False
return LBuilderValue{type = boolType, llvm_value = llvm_result}
# a < b
def lt(self, a: LBuilderValue, b: LBuilderValue) -> LBuilderValue:
assert a.type == b.type
match a.type->kind:
case TypeKind.SignedInteger:
llvm_result = LLVMBuildICmp(self->llvm_builder, LLVMIntPredicate.SLT, a.llvm_value, b.llvm_value, "lt")
case TypeKind.UnsignedInteger:
llvm_result = LLVMBuildICmp(self->llvm_builder, LLVMIntPredicate.ULT, a.llvm_value, b.llvm_value, "lt")
case TypeKind.FloatingPoint:
llvm_result = LLVMBuildFCmp(self->llvm_builder, LLVMRealPredicate.OLT, a.llvm_value, b.llvm_value, "lt")
case _:
assert False
return LBuilderValue{type = boolType, llvm_value = llvm_result}
# not value
def not_(self, value: LBuilderValue) -> LBuilderValue:
llvm_result = LLVMBuildXor(self->llvm_builder, value.llvm_value, LLVMConstInt(LLVMInt1Type(), 1, False as int), "not")
return LBuilderValue{type = boolType, llvm_value = llvm_result}
# sizeof(any value of given type)
def size_of(self, t: Type*) -> LBuilderValue:
return LBuilderValue{
type = longType,
llvm_value = LLVMSizeOf(type_to_llvm(t)),
}
# memset(ptr, 0, sizeof(*ptr))
def memset_to_zero(self, ptr: LBuilderValue) -> None:
assert ptr.type->kind == TypeKind.Pointer
size = self->size_of(ptr.type->value_type).llvm_value
zero_byte = LLVMConstInt(LLVMInt8Type(), 0, False as int)
LLVMBuildMemSet(self->llvm_builder, ptr.llvm_value, zero_byte, size, 0)
# value as to
def cast(self, value: LBuilderValue, to: Type*) -> LBuilderValue:
llvm_result = build_llvm_cast(self->llvm_builder, value.llvm_value, value.type, to)
return LBuilderValue{type = to, llvm_value = llvm_result}
# Blocks are used to implement e.g. if statements and loops.
def add_block(self) -> LLVMBasicBlock*:
return LLVMAppendBasicBlock(self->llvm_func, "block")
# Decide which block will contain the resulting instructions.
def set_current_block(self, block: LLVMBasicBlock*) -> None:
LLVMPositionBuilderAtEnd(self->llvm_builder, block)
self->current_block = block
def branch(self, cond: LBuilderValue, then: LLVMBasicBlock*, otherwise: LLVMBasicBlock*) -> None:
LLVMBuildCondBr(self->llvm_builder, cond.llvm_value, then, otherwise)
def jump(self, next_block: LLVMBasicBlock*) -> None:
LLVMBuildBr(self->llvm_builder, next_block)
def unreachable(self) -> None:
LLVMBuildUnreachable(self->llvm_builder)
def ret(self, value: LBuilderValue*) -> None:
if value == NULL:
LLVMBuildRetVoid(self->llvm_builder)
else:
LLVMBuildRet(self->llvm_builder, value->llvm_value)
@public
def build_llvm_ir(ast: AstFile*) -> LLVMModule*:
module = LLVMModuleCreateWithName(ast->path)
LLVMSetTarget(module, target.triple)
LLVMSetDataLayout(module, target.data_layout)
builder = LBuilder{llvm_module = module, llvm_builder = LLVMCreateBuilder()}
builder_wrapper = EitherBuilder{lbuilder = &builder}
for g = ast->types.globals; g < &ast->types.globals[ast->types.nglobals]; g++:
t = type_to_llvm(g->type)
globalptr = LLVMAddGlobal(module, t, g->name)
if g->defined_in_current_file:
LLVMSetInitializer(globalptr, LLVMConstNull(t))
for stmt = ast->body.statements; stmt < &ast->body.statements[ast->body.nstatements]; stmt++:
match stmt->kind:
case AstStatementKind.FunctionDef:
feed_ast_to_builder(&stmt->function, stmt->location, &builder_wrapper)
case AstStatementKind.Class:
for inner = stmt->classdef.body->statements; inner < &stmt->classdef.body->statements[stmt->classdef.body->nstatements]; inner++:
if inner->kind == AstStatementKind.MethodDef:
feed_ast_to_builder(&inner->method, inner->location, &builder_wrapper)
case _:
pass
LLVMDisposeBuilder(builder.llvm_builder)
return module