-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
codegen.cr
2039 lines (1686 loc) · 59.4 KB
/
codegen.cr
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require "llvm"
require "../syntax/parser"
require "../syntax/visitor"
require "../semantic"
require "../program"
require "./llvm_builder_helper"
module Crystal
MAIN_NAME = "__crystal_main"
RAISE_NAME = "__crystal_raise"
MALLOC_NAME = "__crystal_malloc"
MALLOC_ATOMIC_NAME = "__crystal_malloc_atomic"
REALLOC_NAME = "__crystal_realloc"
PERSONALITY_NAME = "__crystal_personality"
GET_EXCEPTION_NAME = "__crystal_get_exception"
class Program
def run(code, filename = nil, debug = Debug::Default)
parser = Parser.new(code)
parser.filename = filename
node = parser.parse
node = normalize node
node = semantic node
evaluate node, debug: debug
end
def evaluate(node, debug = Debug::Default)
llvm_mod = codegen(node, single_module: true, debug: debug)[""].mod
main = llvm_mod.functions[MAIN_NAME]
main_return_type = main.return_type
# It seems the JIT doesn't like it if we return an empty type (struct {})
llvm_context = llvm_mod.context
main_return_type = llvm_context.void if node.type.nil_type?
wrapper = llvm_mod.functions.add("__evaluate_wrapper", [] of LLVM::Type, main_return_type) do |func|
func.basic_blocks.append "entry" do |builder|
argc = llvm_context.int32.const_int(0)
argv = llvm_context.void_pointer.pointer.null
ret = builder.call(main, [argc, argv])
(node.type.void? || node.type.nil_type?) ? builder.ret : builder.ret(ret)
end
end
llvm_mod.verify
# We use the block form so we dispose the JIT as soon as possible.
# This isn't really needed, but on LLVM 3.9 it sometimes messes the
# stack trace for unwind, or so it seems, or there's something else
# that for now we can't understand.
#
# Since this only affects specs (not the code that is generated by
# the compiler) we can postpone the understanding and continue
# running specs just fine.
#
# See https://github.com/crystal-lang/crystal/pull/3439
LLVM::JITCompiler.new(llvm_mod) do |jit|
jit.run_function wrapper, [] of LLVM::GenericValue, llvm_context
end
end
def codegen(node, single_module = false, debug = Debug::Default, expose_crystal_main = true)
visitor = CodeGenVisitor.new self, node, single_module: single_module, debug: debug, expose_crystal_main: expose_crystal_main
node.accept visitor
visitor.process_finished_hooks
visitor.finish
visitor.modules
end
def llvm_typer
@llvm_typer ||= LLVMTyper.new(self, LLVM::Context.new)
end
def size_of(type)
size = llvm_typer.size_of(llvm_typer.llvm_type(type))
size = 1 if size == 0
size
end
def instance_size_of(type)
llvm_typer.size_of(llvm_typer.llvm_struct_type(type))
end
end
class CodeGenVisitor < Visitor
SYMBOL_TABLE_NAME = ":symbol_table"
include LLVMBuilderHelper
getter llvm_mod : LLVM::Module
getter builder : CrystalLLVMBuilder
getter main : LLVM::Function
getter modules : Hash(String, ModuleInfo)
getter context : Context
getter llvm_typer : LLVMTyper
getter alloca_block : LLVM::BasicBlock
getter entry_block : LLVM::BasicBlock
property last : LLVM::Value
class LLVMVar
getter pointer : LLVM::Value
getter type : Type
# Normally a variable is associated with an alloca.
# So for example, if you have a "x = Reference.new" you will have
# an "Reference**" llvm value and you need to load that value
# to access it.
# However, the "self" argument is not copied to a local variable:
# it's accessed from the arguments list, and it a "Reference*"
# llvm value, so in a way it's "already loaded".
# This field is true if that's the case.
getter already_loaded : Bool
def initialize(@pointer, @type, @already_loaded = false)
end
end
alias LLVMVars = Hash(String, LLVMVar)
record Handler, node : ExceptionHandler, context : Context
record StringKey, mod : LLVM::Module, string : String
record ModuleInfo, mod : LLVM::Module, typer : LLVMTyper, builder : CrystalLLVMBuilder
@abi : LLVM::ABI
@main_ret_type : Type
@argc : LLVM::Value
@argv : LLVM::Value
@empty_md_list : LLVM::Value
@rescue_block : LLVM::BasicBlock?
@malloc_fun : LLVM::Function?
@malloc_atomic_fun : LLVM::Function?
@sret_value : LLVM::Value?
@cant_pass_closure_to_c_exception_call : Call?
@realloc_fun : LLVM::Function?
@main_llvm_context : LLVM::Context
@main_llvm_typer : LLVMTyper
@main_module_info : ModuleInfo
@main_builder : CrystalLLVMBuilder
def initialize(@program : Program, @node : ASTNode, single_module = false, @debug = Debug::Default, expose_crystal_main = true)
@single_module = !!single_module
@abi = @program.target_machine.abi
@llvm_context = LLVM::Context.new
# LLVM::Context.register(@llvm_context, "main")
@llvm_mod = @llvm_context.new_module("main_module")
@main_mod = @llvm_mod
@main_llvm_context = @main_mod.context
@llvm_typer = LLVMTyper.new(@program, @llvm_context)
@main_llvm_typer = @llvm_typer
@llvm_id = LLVMId.new(@program)
@main_ret_type = node.type? || @program.nil_type
ret_type = @llvm_typer.llvm_return_type(@main_ret_type)
@main = @llvm_mod.functions.add(MAIN_NAME, [llvm_context.int32, llvm_context.void_pointer.pointer], ret_type)
@main.linkage = LLVM::Linkage::Internal unless expose_crystal_main
emit_main_def_debug_metadata(@main, "??") unless @debug.none?
@context = Context.new @main, @program
@context.return_type = @main_ret_type
@argc = @main.params[0]
@argc.name = "argc"
@argv = @main.params[1]
@argv.name = "argv"
@builder = new_builder(@main_llvm_context)
@main_builder = @builder
@main_module_info = ModuleInfo.new(@main_mod, @main_llvm_typer, @builder)
@modules = {"" => @main_module_info} of String => ModuleInfo
@types_to_modules = {} of Type => ModuleInfo
@alloca_block, @entry_block = new_entry_block_chain "alloca", "entry"
@in_lib = false
@strings = {} of StringKey => LLVM::Value
@symbols = {} of String => Int32
@symbol_table_values = [] of LLVM::Value
program.symbols.each_with_index do |sym, index|
@symbols[sym] = index
@symbol_table_values << build_string_constant(sym, sym)
end
unless program.symbols.empty?
symbol_table = define_symbol_table @llvm_mod, @llvm_typer
symbol_table.initializer = llvm_type(@program.string).const_array(@symbol_table_values)
end
@last = llvm_nil
@fun_literal_count = 0
# This flag is to generate less code. If there's an if in the middle
# of a series of expressions we don't need the result, so there's no
# need to build a phi for it.
# Also, we don't need the value of unions returned from calls if they
# are not going to be used.
@needs_value = true
@empty_md_list = metadata([] of Int32)
@unused_fun_defs = [] of FunDef
@proc_counts = Hash(String, Int32).new(0)
@llvm_mod.data_layout = self.data_layout
# We need to define __crystal_malloc and __crystal_realloc as soon as possible,
# to avoid some memory being allocated with plain malloc.
codgen_well_known_functions @node
initialize_argv_and_argc
initialize_simple_class_vars_and_constants
if @debug.line_numbers? && (filename = @program.filename)
set_current_debug_location Location.new(filename, 1, 1)
end
alloca_vars @program.vars, @program
emit_vars_debug_info(@program.vars) if @debug.variables?
end
getter llvm_typer
getter llvm_context
def new_builder(llvm_context)
wrap_builder(llvm_context.new_builder)
end
# Here we only initialize simple constants and class variables, those
# that has simple values like 1, "foo" and other literals.
def initialize_simple_class_vars_and_constants
@program.class_var_and_const_initializers.each do |initializer|
case initializer
when Const
# Simple constants are never initialized: they are always inlined
next if initializer.compile_time_value
next unless initializer.simple?
initialize_simple_const(initializer)
when ClassVarInitializer
next unless initializer.node.simple_literal?
class_var = initializer.owner.class_vars[initializer.name]
next if class_var.thread_local?
initialize_class_var(initializer.owner, initializer.name, initializer.meta_vars, initializer.node)
end
end
end
def wrap_builder(builder)
CrystalLLVMBuilder.new builder, llvm_typer, @program.printf(@llvm_mod, llvm_context)
end
def define_symbol_table(llvm_mod, llvm_typer)
llvm_mod.globals.add llvm_typer.llvm_type(@program.string).array(@symbol_table_values.size), SYMBOL_TABLE_NAME
end
def data_layout
@program.target_machine.data_layout
end
class CodegenWellKnownFunctions < Visitor
@codegen : CodeGenVisitor
def initialize(@codegen)
end
def visit(node : FileNode)
true
end
def visit(node : Expressions)
true
end
def visit(node : FunDef)
case node.name
when MALLOC_NAME, MALLOC_ATOMIC_NAME, REALLOC_NAME, RAISE_NAME, PERSONALITY_NAME, GET_EXCEPTION_NAME
@codegen.accept node
end
false
end
def visit(node : ASTNode)
false
end
end
def codgen_well_known_functions(node)
visitor = CodegenWellKnownFunctions.new(self)
node.accept visitor
end
def visit_any(node)
!@builder.end
end
def type
context.type.not_nil!
end
def finish
codegen_return @main_ret_type
# If there are no instructions in the alloca block and the
# const block, we just removed them (less noise)
if alloca_block.instructions.empty?
alloca_block.delete
else
br_block_chain alloca_block, entry_block
end
@unused_fun_defs.each do |node|
codegen_fun node.real_name, node.external, @program, is_exported_fun: true
end
env_dump = ENV["DUMP"]?
case env_dump
when Nil
# Nothing
when "1"
dump_all_llvm = true
else
dump_llvm_regex = Regex.new(env_dump)
end
@modules.each do |name, info|
mod = info.mod
push_debug_info_metadata(mod) unless @debug.none?
mod.dump if dump_all_llvm || name =~ dump_llvm_regex
# Always run verifications so we can catch bugs earlier and more often.
# We can probably remove this, or only enable this when compiling in
# release mode, once we reach 1.0.
mod.verify
end
end
def visit(node : Attribute)
false
end
def visit(node : FunDef)
if @in_lib
return false
end
unless node.external.dead?
# Mark as dead so we don't generate it twice
# (can happen with well known functions like __crystal_raise)
node.external.dead = true
if node.external.used?
codegen_fun node.real_name, node.external, @program, is_exported_fun: true
else
# If the fun is not invoked we codegen it at the end so
# we don't have issues with constants being used before
# they are declared.
# But, apparenty, llvm requires us to define them so that
# calls can find them, so we do so.
codegen_fun node.real_name, node.external, @program, is_exported_fun: false
@unused_fun_defs << node
end
end
false
end
def visit(node : FileNode)
with_context(Context.new(context.fun, context.type)) do
file_module = @program.file_module(node.filename)
if vars = file_module.vars?
set_current_debug_location Location.new(node.filename, 1, 1) if @debug.line_numbers?
alloca_vars vars, file_module
emit_vars_debug_info(vars) if @debug.variables?
end
node.node.accept self
@last = llvm_nil
end
false
end
def visit(node : Nop)
@last = llvm_nil
end
def visit(node : NilLiteral)
@last = llvm_nil
end
def visit(node : BoolLiteral)
@last = int1(node.value ? 1 : 0)
end
def visit(node : CharLiteral)
@last = int32(node.value.ord)
end
def visit(node : NumberLiteral)
case node.kind
when :i8
@last = int8(node.value.to_i8)
when :u8
@last = int8(node.value.to_u8)
when :i16
@last = int16(node.value.to_i16)
when :u16
@last = int16(node.value.to_u16)
when :i32
@last = int32(node.value.to_i32)
when :u32
@last = int32(node.value.to_u32)
when :i64
@last = int64(node.value.to_i64)
when :u64
@last = int64(node.value.to_u64)
when :f32
@last = llvm_context.float.const_float(node.value)
when :f64
@last = llvm_context.double.const_double(node.value)
end
end
def visit(node : StringLiteral)
@last = build_string_constant(node.value, node.value)
end
def visit(node : SymbolLiteral)
@last = int(@symbols[node.value])
end
def visit(node : TupleLiteral)
request_value do
type = node.type.as(TupleInstanceType)
@last = allocate_tuple(type) do |tuple_type, i|
exp = node.elements[i]
exp.accept self
{exp.type, @last}
end
end
false
end
def visit(node : NamedTupleLiteral)
request_value do
type = node.type.as(NamedTupleInstanceType)
struct_type = alloca llvm_type(type)
node.entries.each do |entry|
entry.value.accept self
index = type.name_index(entry.key).not_nil!
assign aggregate_index(struct_type, index), type.entries[index].type, entry.value.type, @last
end
@last = struct_type
end
false
end
def visit(node : PointerOf)
@last = case node_exp = node.exp
when Var
context.vars[node_exp.name].pointer
when InstanceVar
instance_var_ptr context.type.remove_typedef, node_exp.name, llvm_self_ptr
when ClassVar
# Make sure the class var is initializer before taking a pointer of it
if node_exp.var.initializer
initialize_class_var(node_exp)
end
get_global class_var_global_name(node_exp.var.owner, node_exp.var.name), node_exp.type, node_exp.var
when Global
get_global node_exp.name, node_exp.type, node_exp.var
when Path
# Make sure the constant is initialized before taking a pointer of it
const = node_exp.target_const.not_nil!
read_const_pointer(const)
when ReadInstanceVar
node_exp.obj.accept self
instance_var_ptr (node_exp.obj.type), node_exp.name, @last
else
raise "BUG: #{node}"
end
false
end
def visit(node : ProcLiteral)
fun_literal_name = fun_literal_name(node)
is_closure = node.def.closure?
# If we don't care about a proc literal's return type then we mark the associated
# def as returning void. This can't be done in the type inference phase because
# of bindings and type propagation.
if node.force_nil?
node.def.set_type @program.nil
else
# Use proc literal's type, which might have a broader type then the body
# (for example, return type: Int32 | String, body: String)
node.def.set_type node.return_type
end
the_fun = codegen_fun fun_literal_name, node.def, context.type, fun_module_info: @main_module_info, is_fun_literal: true, is_closure: is_closure
the_fun = check_main_fun fun_literal_name, the_fun
fun_ptr = bit_cast(the_fun, llvm_context.void_pointer)
if is_closure
ctx_ptr = bit_cast(context.closure_ptr.not_nil!, llvm_context.void_pointer)
else
ctx_ptr = llvm_context.void_pointer.null
end
@last = make_fun node.type, fun_ptr, ctx_ptr
false
end
def fun_literal_name(node : ProcLiteral)
location = node.location.try &.original_location
if location && (type = node.type?)
proc_name = true
filename = location.filename.as(String)
fun_literal_name = Crystal.safe_mangling(@program, "~proc#{type}@#{Crystal.relative_filename(filename)}:#{location.line_number}")
else
proc_name = false
fun_literal_name = "~fun_literal"
end
proc_count = @proc_counts[fun_literal_name]
proc_count += 1
@proc_counts[fun_literal_name] = proc_count
if proc_count > 1
if proc_name
fun_literal_name = "#{fun_literal_name[0...5]}#{proc_count}#{fun_literal_name[5..-1]}"
else
fun_literal_name = "#{fun_literal_name}#{proc_count}"
end
end
fun_literal_name
end
def visit(node : ProcPointer)
owner = node.call.target_def.owner
if obj = node.obj
accept obj
call_self = @last
elsif owner.passed_as_self?
call_self = llvm_self
end
last_fun = target_def_fun(node.call.target_def, owner)
set_current_debug_location(node) if @debug.line_numbers?
fun_ptr = bit_cast(last_fun, llvm_context.void_pointer)
if call_self && !owner.metaclass? && !owner.is_a?(LibType)
ctx_ptr = bit_cast(call_self, llvm_context.void_pointer)
else
ctx_ptr = llvm_context.void_pointer.null
end
@last = make_fun node.type, fun_ptr, ctx_ptr
false
end
def visit(node : Expressions)
old_needs_value = @needs_value
@needs_value = false
last_index = node.expressions.size - 1
node.expressions.each_with_index do |exp, i|
@needs_value = true if old_needs_value && i == last_index
accept exp
end
@needs_value = old_needs_value
false
end
def visit(node : Return)
node_type = accept_control_expression(node)
codegen_return_node(node, node_type)
false
end
def codegen_return_node(node, node_type)
old_last = @last
execute_ensures_until(node.target.as(Def))
@last = old_last
if return_phi = context.return_phi
return_phi.add @last, node_type
else
codegen_return node_type
end
end
def codegen_return(type : NoReturnType | Nil)
unreachable
end
def codegen_return(type : Type)
return if @builder.end
method_type = context.return_type.not_nil!
if method_type.void?
ret
elsif method_type.nil_type?
ret
elsif method_type.no_return?
unreachable
else
value = upcast(@last, method_type, type)
ret to_rhs(value, method_type)
end
end
def visit(node : ClassDef)
node.hook_expansions.try &.each &.accept self
accept node.body
@last = llvm_nil
false
end
def visit(node : ModuleDef)
accept node.body
@last = llvm_nil
false
end
def visit(node : LibDef)
@in_lib = true
node.body.accept self
@in_lib = false
@last = llvm_nil
false
end
def visit(node : CStructOrUnionDef)
@last = llvm_nil
false
end
def visit(node : EnumDef)
node.members.each do |member|
if member.is_a?(Assign)
member.accept self
end
end
@last = llvm_nil
false
end
def visit(node : ExternalVar)
@last = llvm_nil
false
end
def visit(node : TypeDef)
@last = llvm_nil
false
end
def visit(node : Alias)
@last = llvm_nil
false
end
def visit(node : TypeOf)
@last = type_id(node.type)
false
end
def visit(node : SizeOf)
@last = trunc(llvm_size(node.exp.type.sizeof_type), llvm_context.int32)
false
end
def visit(node : InstanceSizeOf)
@last = trunc(llvm_struct_size(node.exp.type.sizeof_type), llvm_context.int32)
false
end
def visit(node : Include)
node.hook_expansions.try &.each &.accept self
@last = llvm_nil
false
end
def visit(node : Extend)
node.hook_expansions.try &.each &.accept self
@last = llvm_nil
false
end
def visit(node : If)
if node.truthy?
node.cond.accept self
node.then.accept self
if @needs_value && (node_type = node.type?) && (then_type = node.then.type?)
@last = upcast(@last, node_type, then_type)
end
return false
end
if node.falsey?
node.cond.accept self
node.else.accept self
if @needs_value && (node_type = node.type?) && (else_type = node.else.type?)
@last = upcast(@last, node_type, else_type)
end
return false
end
then_block, else_block = new_blocks "then", "else"
request_value do
set_current_debug_location(node) if @debug.line_numbers?
codegen_cond_branch node.cond, then_block, else_block
end
Phi.open(self, node, @needs_value) do |phi|
codegen_if_branch phi, node.then, then_block, false
codegen_if_branch phi, node.else, else_block, true
end
false
end
def codegen_if_branch(phi, node, branch_block, last)
position_at_end branch_block
accept node
phi.add @last, node.type?, last
end
def visit(node : While)
set_ensure_exception_handler(node)
with_cloned_context do
while_block, body_block, exit_block = new_blocks "while", "body", "exit"
context.while_block = while_block
context.while_exit_block = exit_block
context.break_phi = nil
context.next_phi = nil
br while_block
position_at_end while_block
request_value do
set_current_debug_location node.cond if @debug.line_numbers?
codegen_cond_branch node.cond, body_block, exit_block
end
position_at_end body_block
request_value(false) do
accept node.body
end
br while_block
position_at_end exit_block
if node.no_returns?
unreachable
else
@last = llvm_nil
end
end
false
end
def codegen_cond_branch(node_cond, then_block, else_block)
cond codegen_cond(node_cond), then_block, else_block
nil
end
def codegen_cond(node : ASTNode)
accept node
codegen_cond node.type.remove_indirection
end
def visit(node : Not)
accept node.exp
@last = codegen_cond node.exp.type.remove_indirection
@last = not @last
false
end
def visit(node : Break)
set_current_debug_location(node) if @debug.line_numbers?
node_type = accept_control_expression(node)
if break_phi = context.break_phi
old_last = @last
execute_ensures_until(node.target.as(Call))
@last = old_last
break_phi.add @last, node_type
elsif while_exit_block = context.while_exit_block
execute_ensures_until(node.target.as(While))
br while_exit_block
else
node.raise "BUG: unknown exit for break"
end
false
end
def visit(node : Next)
set_current_debug_location(node) if @debug.line_numbers?
node_type = accept_control_expression(node)
case target = node.target
when Block
if next_phi = context.next_phi
old_last = @last
execute_ensures_until(target.as(Block))
@last = old_last
next_phi.add @last, node_type
return false
end
when While
if while_block = context.while_block
execute_ensures_until(target.as(While))
br while_block
return false
end
else
# The only possibility is that we are in a captured block,
# so this is the same as a return
codegen_return_node(node, node_type)
return false
end
node.raise "BUG: unknown exit for next"
end
def accept_control_expression(node)
if exp = node.exp
request_value do
accept exp
end
exp.type? || @program.nil
else
@last = llvm_nil
@program.nil
end
end
def visit(node : Assign)
return false if node.discarded?
target, value = node.target, node.value
codegen_assign(target, value, node)
end
def codegen_assign(target : Underscore, value, node)
accept value
false
end
def codegen_assign(target : Path, value, node)
const = target.target_const.not_nil!
if const.used? && !const.simple? && !const.compile_time_value
initialize_const(const)
end
@last = llvm_nil
false
end
def codegen_assign(target, value, node)
target_type = target.type?
# This means it's an instance variable initialize of a generic type,
# or a class variable initializer
unless target_type
if target.is_a?(ClassVar)
# This is the case of a class var initializer
initialize_class_var(target)
end
return false
end
# This is the case of an instance variable initializer
if target.is_a?(InstanceVar) && !context.type.is_a?(InstanceVarContainer)
return false
end
request_value do
accept value
end
return if value.no_returns?
last = @last
set_current_debug_location node if @debug.line_numbers?
ptr = case target
when InstanceVar
instance_var_ptr context.type, target.name, llvm_self_ptr
when Global
get_global target.name, target_type, target.var
when ClassVar
read_class_var_ptr(target)
when Var
# Can't assign void
return if target.type.void?
# If assigning to a special variable in a method that yields,
# assign to that variable too.
check_assign_to_special_var_in_block(target, value)
var = context.vars[target.name]?
if var
target_type = var.type
var.pointer
else
target.raise "BUG: missing var #{target}"
end
else
node.raise "Unknown assign target in codegen: #{target}"
end
@last = last
llvm_value = last
# When setting an instance variable of an extern type, if it's a Proc
# type we need to check that the value is not a closure and just get
# the function pointer
if target.is_a?(InstanceVar) && context.type.extern? && target.type.proc?
llvm_value = check_proc_is_not_closure(llvm_value, target.type)
end
assign ptr, target_type, value.type, llvm_value
false
end
def check_assign_to_special_var_in_block(target, value)
if (block_context = context.block_context?) && target.special_var?
var = block_context.vars[target.name]
assign var.pointer, var.type, value.type, @last
end
end
def get_global(name, type, real_var, initial_value = nil)
if real_var.thread_local?
get_thread_local(name, type, real_var)
else
get_global_var(name, type, real_var, initial_value)
end
end
def get_global_var(name, type, real_var, initial_value = nil)
ptr = @llvm_mod.globals[name]?
unless ptr
llvm_type = llvm_type(type)
thread_local = real_var.thread_local?
# Declare global in this module as external
ptr = @llvm_mod.globals.add(llvm_type, name)
ptr.thread_local = true if thread_local
if @llvm_mod == @main_mod
ptr.initializer = initial_value || llvm_type.null
else
ptr.linkage = LLVM::Linkage::External
# Define it in main if it's not already defined
main_ptr = @main_mod.globals[name]?
unless main_ptr
main_llvm_type = @main_llvm_typer.llvm_type(type)
main_ptr = @main_mod.globals.add(main_llvm_type, name)
main_ptr.initializer = initial_value || main_llvm_type.null
main_ptr.thread_local = true if thread_local
end
end
end
ptr
end
def get_thread_local(name, type, real_var)
# If it's thread local, we use a NoInline function to access it
# because of http://lists.llvm.org/pipermail/llvm-dev/2016-February/094736.html