-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathasr_to_llvm.cpp
4315 lines (4101 loc) · 195 KB
/
asr_to_llvm.cpp
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
#include <iostream>
#include <memory>
#include <unordered_map>
#include <functional>
#include <string_view>
#include <utility>
#include <llvm/ADT/STLExtras.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/IR/Argument.h>
#include <llvm/IR/Attributes.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/Support/Casting.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/ADT/APFloat.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Vectorize.h>
#include <llvm/ExecutionEngine/ObjectCache.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>
#include <libasr/asr.h>
#include <libasr/containers.h>
#include <libasr/codegen/asr_to_llvm.h>
#include <libasr/pass/do_loops.h>
#include <libasr/pass/for_all.h>
#include <libasr/pass/implied_do_loops.h>
#include <libasr/pass/array_op.h>
#include <libasr/pass/select_case.h>
#include <libasr/pass/global_stmts.h>
#include <libasr/pass/param_to_const.h>
#include <libasr/pass/nested_vars.h>
#include <libasr/pass/print_arr.h>
#include <libasr/pass/arr_slice.h>
#include <libasr/pass/flip_sign.h>
#include <libasr/pass/div_to_mul.h>
#include <libasr/pass/fma.h>
#include <libasr/pass/loop_unroll.h>
#include <libasr/pass/sign_from_value.h>
#include <libasr/pass/class_constructor.h>
#include <libasr/pass/unused_functions.h>
#include <libasr/pass/inline_function_calls.h>
#include <libasr/exception.h>
#include <libasr/asr_utils.h>
#include <libasr/codegen/llvm_utils.h>
#include <libasr/codegen/llvm_array_utils.h>
#if LLVM_VERSION_MAJOR >= 11
# define FIXED_VECTOR_TYPE llvm::FixedVectorType
#else
# define FIXED_VECTOR_TYPE llvm::VectorType
#endif
namespace LFortran {
namespace {
// This exception is used to abort the visitor pattern when an error occurs.
// This is only used locally in this file, not propagated outside. An error
// must be already present in ASRToLLVMVisitor::diag before throwing this
// exception. This is checked with an assert when the CodeGenAbort is
// caught.
class CodeGenAbort
{
};
// Local exception that is only used in this file to exit the visitor
// pattern and caught later (not propagated outside). It accepts an error
// message that is then appended at the end of ASRToLLVMVisitor::diag. The
// `diag` can already contain other errors or warnings. This is a
// convenience class. One can also report the error into `diag` directly and
// call `CodeGenAbort` instead.
class CodeGenError
{
public:
diag::Diagnostic d;
public:
CodeGenError(const std::string &msg)
: d{diag::Diagnostic(msg, diag::Level::Error, diag::Stage::CodeGen)}
{ }
CodeGenError(const std::string &msg, const Location &loc)
: d{diag::Diagnostic(msg, diag::Level::Error, diag::Stage::CodeGen, {
diag::Label("", {loc})
})}
{ }
};
}
using ASR::is_a;
using ASR::down_cast;
using ASR::down_cast2;
using LFortran::ASRUtils::expr_type;
using LFortran::ASRUtils::symbol_get_past_external;
using LFortran::ASRUtils::EXPR2VAR;
using LFortran::ASRUtils::EXPR2FUN;
using LFortran::ASRUtils::EXPR2SUB;
using LFortran::ASRUtils::intent_local;
using LFortran::ASRUtils::intent_return_var;
using LFortran::ASRUtils::determine_module_dependencies;
using LFortran::ASRUtils::is_arg_dummy;
// Platform dependent fast unique hash:
uint64_t static get_hash(ASR::asr_t *node)
{
return (uint64_t)node;
}
void printf(llvm::LLVMContext &context, llvm::Module &module,
llvm::IRBuilder<> &builder, const std::vector<llvm::Value*> &args)
{
llvm::Function *fn_printf = module.getFunction("_lfortran_printf");
if (!fn_printf) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context), {llvm::Type::getInt8PtrTy(context)}, true);
fn_printf = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, "_lfortran_printf", &module);
}
builder.CreateCall(fn_printf, args);
}
void exit(llvm::LLVMContext &context, llvm::Module &module,
llvm::IRBuilder<> &builder, llvm::Value* exit_code)
{
llvm::Function *fn_exit = module.getFunction("exit");
if (!fn_exit) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context), {llvm::Type::getInt32Ty(context)},
false);
fn_exit = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, "exit", &module);
}
builder.CreateCall(fn_exit, {exit_code});
}
void string_init(llvm::LLVMContext &context, llvm::Module &module,
llvm::IRBuilder<> &builder, llvm::Value* arg_size, llvm::Value* arg_string) {
std::string func_name = "_lfortran_string_init";
llvm::Function *fn = module.getFunction(func_name);
if (!fn) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context), {
llvm::Type::getInt32Ty(context),
llvm::Type::getInt8PtrTy(context)
}, true);
fn = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, func_name, module);
}
std::vector<llvm::Value*> args = {arg_size, arg_string};
builder.CreateCall(fn, args);
}
class ASRToLLVMVisitor : public ASR::BaseVisitor<ASRToLLVMVisitor>
{
private:
//! To be used by visit_DerivedRef.
std::string der_type_name;
//! Helpful for debugging while testing LLVM code
void print_util(llvm::Value* v, std::string fmt_chars, std::string endline="\t") {
std::vector<llvm::Value *> args;
std::vector<std::string> fmt;
args.push_back(v);
fmt.push_back(fmt_chars);
std::string fmt_str;
for (size_t i=0; i<fmt.size(); i++) {
fmt_str += fmt[i];
if (i < fmt.size()-1) fmt_str += " ";
}
fmt_str += endline;
llvm::Value *fmt_ptr = builder->CreateGlobalStringPtr(fmt_str);
std::vector<llvm::Value *> printf_args;
printf_args.push_back(fmt_ptr);
printf_args.insert(printf_args.end(), args.begin(), args.end());
printf(context, *module, *builder, printf_args);
}
public:
diag::Diagnostics &diag;
llvm::LLVMContext &context;
std::unique_ptr<llvm::Module> module;
std::unique_ptr<llvm::IRBuilder<>> builder;
Platform platform;
Allocator &al;
llvm::Value *tmp;
llvm::BasicBlock *current_loophead, *current_loopend, *proc_return;
std::string mangle_prefix;
bool prototype_only;
llvm::StructType *complex_type_4, *complex_type_8;
llvm::StructType *complex_type_4_ptr, *complex_type_8_ptr;
llvm::PointerType *character_type;
std::unordered_map<std::uint32_t, std::unordered_map<std::string, llvm::Type*>> arr_arg_type_cache;
std::map<std::string, std::pair<llvm::Type*, llvm::Type*>> fname2arg_type;
// Maps for containing information regarding derived types
std::map<std::string, llvm::StructType*> name2dertype;
std::map<std::string, std::string> dertype2parent;
std::map<std::string, std::map<std::string, int>> name2memidx;
std::map<uint64_t, llvm::Value*> llvm_symtab; // llvm_symtab_value
std::map<uint64_t, llvm::Function*> llvm_symtab_fn;
std::map<std::string, uint64_t> llvm_symtab_fn_names;
std::map<uint64_t, llvm::Value*> llvm_symtab_fn_arg;
std::map<uint64_t, llvm::BasicBlock*> llvm_goto_targets;
// Data members for handling nested functions
std::map<uint64_t, std::vector<uint64_t>> nesting_map; /* For saving the
relationship between enclosing and nested functions */
std::vector<uint64_t> nested_globals; /* For saving the hash of variables
from a parent scope needed in a nested function */
std::map<uint64_t, std::vector<llvm::Type*>> nested_func_types; /* For
saving the hash of a parent function needing to give access to
variables in a nested function, as well as the variable types */
llvm::StructType* nested_global_struct; /*The struct type that will hold
variables needed in a nested function; will contain types as given in
the runtime descriptor member */
std::string nested_desc_name; // For setting the name of the global struct
std::vector<uint64_t> nested_call_out; /* Hash of functions containing
nested functions that can call functions besides the nested functions
- in such cases we need a means to save the local context */
llvm::StructType* nested_global_struct_vals; /*Equivalent struct type to
nested_global_struct, but holding types that nested_global_struct points
to. Needed in cases where we need to store values and preserve a local
context */
llvm::ArrayType* nested_global_stack; /* An array type for holding numerous
nested_global_struct_vals, serving as a stack to reload values when
we may are leaving or re-entering states with a need to preserve
context*/
std::string nested_stack_name; // The name of the nested_global_stack
std::string nested_sp_name; /* The stack pointer name for the
nested_global_stack */
uint64_t parent_function_hash;
uint64_t calling_function_hash; /* These hashes are compared to resulted
from the nested_vars analysis pass to determine if we need to save or
reload a local scope (and increment or decrement the stack pointer) */
const ASR::Function_t *parent_function = nullptr;
const ASR::Subroutine_t *parent_subroutine = nullptr; /* For ensuring we are
in a nested_function before checking if we need to declare stack
types */
std::unique_ptr<LLVMUtils> llvm_utils;
std::unique_ptr<LLVMArrUtils::Descriptor> arr_descr;
ASRToLLVMVisitor(Allocator &al, llvm::LLVMContext &context, Platform platform,
diag::Diagnostics &diagnostics) :
diag{diagnostics},
context(context),
builder(std::make_unique<llvm::IRBuilder<>>(context)),
platform{platform},
al{al},
prototype_only(false),
llvm_utils(std::make_unique<LLVMUtils>(context, builder.get())),
arr_descr(LLVMArrUtils::Descriptor::get_descriptor(context,
builder.get(),
llvm_utils.get(),
LLVMArrUtils::DESCR_TYPE::_SimpleCMODescriptor))
{
}
llvm::Value* CreateLoad(llvm::Value *x) {
return LFortran::LLVM::CreateLoad(*builder, x);
}
llvm::Value* CreateGEP(llvm::Value *x, std::vector<llvm::Value *> &idx) {
return LFortran::LLVM::CreateGEP(*builder, x, idx);
}
// Inserts a new block `bb` using the current builder
// and terminates the previous block if it is not already terminated
void start_new_block(llvm::BasicBlock *bb) {
llvm::BasicBlock *last_bb = builder->GetInsertBlock();
llvm::Function *fn = last_bb->getParent();
llvm::Instruction *block_terminator = last_bb->getTerminator();
if (block_terminator == nullptr) {
// The previous block is not terminated --- terminate it by jumping
// to our new block
builder->CreateBr(bb);
}
fn->getBasicBlockList().push_back(bb);
builder->SetInsertPoint(bb);
}
inline bool verify_dimensions_t(ASR::dimension_t* m_dims, int n_dims) {
if( n_dims <= 0 ) {
return false;
}
bool is_ok = true;
for( int r = 0; r < n_dims; r++ ) {
if( m_dims[r].m_end == nullptr ) {
is_ok = false;
break;
}
}
return is_ok;
}
llvm::Type*
get_el_type(ASR::ttype_t* m_type_, int a_kind) {
llvm::Type* el_type = nullptr;
if (ASR::is_a<ASR::Pointer_t>(*m_type_)) {
ASR::ttype_t *t2 = ASR::down_cast<ASR::Pointer_t>(m_type_)->m_type;
switch(t2->type) {
case ASR::ttypeType::Integer: {
el_type = getIntType(a_kind, true);
break;
}
case ASR::ttypeType::Real: {
el_type = getFPType(a_kind, true);
break;
}
case ASR::ttypeType::Complex: {
el_type = getComplexType(a_kind, true);
break;
}
case ASR::ttypeType::Logical: {
el_type = llvm::Type::getInt1Ty(context);
break;
}
case ASR::ttypeType::Derived: {
el_type = getDerivedType(m_type_);
break;
}
case ASR::ttypeType::Character: {
el_type = character_type;
break;
}
default:
break;
}
} else {
switch(m_type_->type) {
case ASR::ttypeType::Integer: {
el_type = getIntType(a_kind);
break;
}
case ASR::ttypeType::Real: {
el_type = getFPType(a_kind);
break;
}
case ASR::ttypeType::Complex: {
el_type = getComplexType(a_kind);
break;
}
case ASR::ttypeType::Logical: {
el_type = llvm::Type::getInt1Ty(context);
break;
}
case ASR::ttypeType::Derived: {
el_type = getDerivedType(m_type_);
break;
}
case ASR::ttypeType::Character: {
el_type = character_type;
break;
}
default:
break;
}
}
return el_type;
}
void fill_array_details(llvm::Value* arr, ASR::dimension_t* m_dims,
int n_dims) {
std::vector<std::pair<llvm::Value*, llvm::Value*>> llvm_dims;
for( int r = 0; r < n_dims; r++ ) {
ASR::dimension_t m_dim = m_dims[r];
visit_expr(*(m_dim.m_start));
llvm::Value* start = tmp;
visit_expr(*(m_dim.m_end));
llvm::Value* end = tmp;
llvm_dims.push_back(std::make_pair(start, end));
}
arr_descr->fill_array_details(arr, m_dims, n_dims, llvm_dims);
}
/*
This function fills the descriptor
(pointer to the first element, offset and descriptor of each dimension)
of the array which are allocated memory in heap.
*/
inline void fill_malloc_array_details(llvm::Value* arr, ASR::dimension_t* m_dims,
int n_dims) {
std::vector<std::pair<llvm::Value*, llvm::Value*>> llvm_dims;
for( int r = 0; r < n_dims; r++ ) {
ASR::dimension_t m_dim = m_dims[r];
visit_expr(*(m_dim.m_start));
llvm::Value* start = tmp;
visit_expr(*(m_dim.m_end));
llvm::Value* end = tmp;
llvm_dims.push_back(std::make_pair(start, end));
}
arr_descr->fill_malloc_array_details(arr, n_dims, llvm_dims, module.get());
}
inline llvm::Type* getIntType(int a_kind, bool get_pointer=false) {
llvm::Type* type_ptr = nullptr;
if( get_pointer ) {
switch(a_kind)
{
case 1:
type_ptr = llvm::Type::getInt8PtrTy(context);
break;
case 2:
type_ptr = llvm::Type::getInt16PtrTy(context);
break;
case 4:
type_ptr = llvm::Type::getInt32PtrTy(context);
break;
case 8:
type_ptr = llvm::Type::getInt64PtrTy(context);
break;
default:
throw CodeGenError("Only 32 and 64 bits integer kinds are supported.");
}
} else {
switch(a_kind)
{
case 1:
type_ptr = llvm::Type::getInt8Ty(context);
break;
case 2:
type_ptr = llvm::Type::getInt16Ty(context);
break;
case 4:
type_ptr = llvm::Type::getInt32Ty(context);
break;
case 8:
type_ptr = llvm::Type::getInt64Ty(context);
break;
default:
throw CodeGenError("Only 32 and 64 bits integer kinds are supported.");
}
}
return type_ptr;
}
inline llvm::Type* getFPType(int a_kind, bool get_pointer=false) {
llvm::Type* type_ptr = nullptr;
if( get_pointer ) {
switch(a_kind)
{
case 4:
type_ptr = llvm::Type::getFloatPtrTy(context);
break;
case 8:
type_ptr = llvm::Type::getDoublePtrTy(context);
break;
default:
throw CodeGenError("Only 32 and 64 bits real kinds are supported.");
}
} else {
switch(a_kind)
{
case 4:
type_ptr = llvm::Type::getFloatTy(context);
break;
case 8:
type_ptr = llvm::Type::getDoubleTy(context);
break;
default:
throw CodeGenError("Only 32 and 64 bits real kinds are supported.");
}
}
return type_ptr;
}
inline llvm::Type* getComplexType(int a_kind, bool get_pointer=false) {
llvm::Type* type = nullptr;
switch(a_kind)
{
case 4:
type = complex_type_4;
break;
case 8:
type = complex_type_8;
break;
default:
throw CodeGenError("Only 32 and 64 bits complex kinds are supported.");
}
if( type != nullptr ) {
if( get_pointer ) {
return type->getPointerTo();
} else {
return type;
}
}
return nullptr;
}
llvm::Type* getDerivedType(ASR::DerivedType_t* der_type, bool is_pointer=false) {
std::string der_type_name = std::string(der_type->m_name);
llvm::StructType* der_type_llvm;
if( name2dertype.find(der_type_name) != name2dertype.end() ) {
der_type_llvm = name2dertype[der_type_name];
} else {
std::vector<llvm::Type*> member_types;
int member_idx = 0;
if( der_type->m_parent != nullptr ) {
ASR::DerivedType_t *par_der_type = ASR::down_cast<ASR::DerivedType_t>(
symbol_get_past_external(der_type->m_parent));
llvm::Type* par_llvm = getDerivedType(par_der_type);
member_types.push_back(par_llvm);
dertype2parent[der_type_name] = std::string(par_der_type->m_name);
member_idx += 1;
}
std::map<std::string, ASR::symbol_t*> scope = der_type->m_symtab->scope;
for( auto itr = scope.begin(); itr != scope.end(); itr++ ) {
ASR::Variable_t* member = (ASR::Variable_t*)(&(itr->second->base));
llvm::Type* mem_type = nullptr;
switch( member->m_type->type ) {
case ASR::ttypeType::Integer: {
int a_kind = down_cast<ASR::Integer_t>(member->m_type)->m_kind;
mem_type = getIntType(a_kind);
break;
}
case ASR::ttypeType::Real: {
int a_kind = down_cast<ASR::Real_t>(member->m_type)->m_kind;
mem_type = getFPType(a_kind);
break;
}
case ASR::ttypeType::Derived: {
mem_type = getDerivedType(member->m_type);
break;
}
case ASR::ttypeType::Complex: {
int a_kind = down_cast<ASR::Complex_t>(member->m_type)->m_kind;
mem_type = getComplexType(a_kind);
break;
}
case ASR::ttypeType::Character: {
mem_type = character_type;
break;
}
default:
throw CodeGenError("Cannot identify the type of member, '" +
std::string(member->m_name) +
"' in derived type, '" + der_type_name + "'.",
member->base.base.loc);
}
member_types.push_back(mem_type);
name2memidx[der_type_name][std::string(member->m_name)] = member_idx;
member_idx++;
}
der_type_llvm = llvm::StructType::create(context, member_types, der_type_name);
name2dertype[der_type_name] = der_type_llvm;
}
if( is_pointer ) {
return der_type_llvm->getPointerTo();
}
return (llvm::Type*) der_type_llvm;
}
llvm::Type* getDerivedType(ASR::ttype_t* _type, bool is_pointer=false) {
ASR::Derived_t* der = (ASR::Derived_t*)(&(_type->base));
ASR::symbol_t* der_sym;
if( der->m_derived_type->type == ASR::symbolType::ExternalSymbol ) {
ASR::ExternalSymbol_t* der_extr = (ASR::ExternalSymbol_t*)(&(der->m_derived_type->base));
der_sym = der_extr->m_external;
} else {
der_sym = der->m_derived_type;
}
ASR::DerivedType_t* der_type = (ASR::DerivedType_t*)(&(der_sym->base));
return getDerivedType(der_type, is_pointer);
}
llvm::Type* getClassType(ASR::ttype_t* _type, bool is_pointer=false) {
ASR::Class_t* der = (ASR::Class_t*)(&(_type->base));
ASR::symbol_t* der_sym;
if( der->m_class_type->type == ASR::symbolType::ExternalSymbol ) {
ASR::ExternalSymbol_t* der_extr = (ASR::ExternalSymbol_t*)(&(der->m_class_type->base));
der_sym = der_extr->m_external;
} else {
der_sym = der->m_class_type;
}
ASR::ClassType_t* der_type = (ASR::ClassType_t*)(&(der_sym->base));
std::string der_type_name = std::string(der_type->m_name);
llvm::StructType* der_type_llvm;
if( name2dertype.find(der_type_name) != name2dertype.end() ) {
der_type_llvm = name2dertype[der_type_name];
} else {
std::map<std::string, ASR::symbol_t*> scope = der_type->m_symtab->scope;
std::vector<llvm::Type*> member_types;
int member_idx = 0;
for( auto itr = scope.begin(); itr != scope.end(); itr++ ) {
if (!ASR::is_a<ASR::ClassProcedure_t>(*itr->second) &&
!ASR::is_a<ASR::GenericProcedure_t>(*itr->second)) {
ASR::Variable_t* member = ASR::down_cast<ASR::Variable_t>(itr->second);
llvm::Type* mem_type = nullptr;
switch( member->m_type->type ) {
case ASR::ttypeType::Integer: {
int a_kind = down_cast<ASR::Integer_t>(member->m_type)->m_kind;
mem_type = getIntType(a_kind);
break;
}
case ASR::ttypeType::Real: {
int a_kind = down_cast<ASR::Real_t>(member->m_type)->m_kind;
mem_type = getFPType(a_kind);
break;
}
case ASR::ttypeType::Class: {
mem_type = getClassType(member->m_type);
break;
}
case ASR::ttypeType::Complex: {
int a_kind = down_cast<ASR::Complex_t>(member->m_type)->m_kind;
mem_type = getComplexType(a_kind);
break;
}
default:
throw CodeGenError("Cannot identify the type of member, '" +
std::string(member->m_name) +
"' in derived type, '" + der_type_name + "'.",
member->base.base.loc);
}
member_types.push_back(mem_type);
name2memidx[der_type_name][std::string(member->m_name)] = member_idx;
member_idx++;
}
}
der_type_llvm = llvm::StructType::create(context, member_types, der_type_name);
name2dertype[der_type_name] = der_type_llvm;
}
if( is_pointer ) {
return der_type_llvm->getPointerTo();
}
return (llvm::Type*) der_type_llvm;
}
/*
* Dispatches the required function from runtime library to
* perform the specified binary operation.
*
* @param left_arg llvm::Value* The left argument of the binary operator.
* @param right_arg llvm::Value* The right argument of the binary operator.
* @param runtime_func_name std::string The name of the function to be dispatched
* from runtime library.
* @returns llvm::Value* The result of the operation.
*
* Note
* ====
*
* Internally the call to this function gets transformed into a runtime call:
* void _lfortran_complex_add(complex* a, complex* b, complex *result)
*
* As of now the following values for func_name are supported,
*
* _lfortran_complex_add
* _lfortran_complex_sub
* _lfortran_complex_div
* _lfortran_complex_mul
*/
llvm::Value* lfortran_complex_bin_op(llvm::Value* left_arg, llvm::Value* right_arg,
std::string runtime_func_name,
llvm::Type* complex_type=nullptr)
{
if( complex_type == nullptr ) {
complex_type = complex_type_4;
}
llvm::Function *fn = module->getFunction(runtime_func_name);
if (!fn) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context), {
complex_type->getPointerTo(),
complex_type->getPointerTo(),
complex_type->getPointerTo()
}, true);
fn = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, runtime_func_name, *module);
}
llvm::AllocaInst *pleft_arg = builder->CreateAlloca(complex_type,
nullptr);
builder->CreateStore(left_arg, pleft_arg);
llvm::AllocaInst *pright_arg = builder->CreateAlloca(complex_type,
nullptr);
builder->CreateStore(right_arg, pright_arg);
llvm::AllocaInst *presult = builder->CreateAlloca(complex_type,
nullptr);
std::vector<llvm::Value*> args = {pleft_arg, pright_arg, presult};
builder->CreateCall(fn, args);
return CreateLoad(presult);
}
llvm::Value* lfortran_strop(llvm::Value* left_arg, llvm::Value* right_arg,
std::string runtime_func_name)
{
llvm::Function *fn = module->getFunction(runtime_func_name);
if (!fn) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context), {
character_type->getPointerTo(),
character_type->getPointerTo(),
character_type->getPointerTo()
}, false);
fn = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, runtime_func_name, *module);
}
llvm::AllocaInst *pleft_arg = builder->CreateAlloca(character_type,
nullptr);
builder->CreateStore(left_arg, pleft_arg);
llvm::AllocaInst *pright_arg = builder->CreateAlloca(character_type,
nullptr);
builder->CreateStore(right_arg, pright_arg);
llvm::AllocaInst *presult = builder->CreateAlloca(character_type,
nullptr);
std::vector<llvm::Value*> args = {pleft_arg, pright_arg, presult};
builder->CreateCall(fn, args);
return CreateLoad(presult);
}
llvm::Value* lfortran_str_len(llvm::Value* str)
{
std::string runtime_func_name = "_lfortran_str_len";
llvm::Function *fn = module->getFunction(runtime_func_name);
if (!fn) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getInt32Ty(context), {
character_type->getPointerTo()
}, false);
fn = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, runtime_func_name, *module);
}
return builder->CreateCall(fn, {str});
}
// This function is called as:
// float complex_re(complex a)
// And it extracts the real part of the complex number
llvm::Value *complex_re(llvm::Value *c, llvm::Type* complex_type=nullptr) {
if( complex_type == nullptr ) {
complex_type = complex_type_4;
}
if( c->getType()->isPointerTy() ) {
c = CreateLoad(c);
}
llvm::AllocaInst *pc = builder->CreateAlloca(complex_type, nullptr);
builder->CreateStore(c, pc);
std::vector<llvm::Value *> idx = {
llvm::ConstantInt::get(context, llvm::APInt(32, 0)),
llvm::ConstantInt::get(context, llvm::APInt(32, 0))};
llvm::Value *pim = CreateGEP(pc, idx);
return CreateLoad(pim);
}
llvm::Value *complex_im(llvm::Value *c, llvm::Type* complex_type=nullptr) {
if( complex_type == nullptr ) {
complex_type = complex_type_4;
}
llvm::AllocaInst *pc = builder->CreateAlloca(complex_type, nullptr);
builder->CreateStore(c, pc);
std::vector<llvm::Value *> idx = {
llvm::ConstantInt::get(context, llvm::APInt(32, 0)),
llvm::ConstantInt::get(context, llvm::APInt(32, 1))};
llvm::Value *pim = CreateGEP(pc, idx);
return CreateLoad(pim);
}
llvm::Value *complex_from_floats(llvm::Value *re, llvm::Value *im,
llvm::Type* complex_type=nullptr) {
if( complex_type == nullptr ) {
complex_type = complex_type_4;
}
llvm::AllocaInst *pres = builder->CreateAlloca(complex_type, nullptr);
std::vector<llvm::Value *> idx1 = {
llvm::ConstantInt::get(context, llvm::APInt(32, 0)),
llvm::ConstantInt::get(context, llvm::APInt(32, 0))};
std::vector<llvm::Value *> idx2 = {
llvm::ConstantInt::get(context, llvm::APInt(32, 0)),
llvm::ConstantInt::get(context, llvm::APInt(32, 1))};
llvm::Value *pre = CreateGEP(pres, idx1);
llvm::Value *pim = CreateGEP(pres, idx2);
builder->CreateStore(re, pre);
builder->CreateStore(im, pim);
return CreateLoad(pres);
}
llvm::Value *nested_struct_rd(std::vector<llvm::Value*> vals,
llvm::StructType* rd) {
llvm::AllocaInst *pres = builder->CreateAlloca(rd, nullptr);
llvm::Value *pim = CreateGEP(pres, vals);
return CreateLoad(pim);
}
/**
* @brief This function generates the
* @detail This is converted to
*
* float lfortran_KEY(float *x)
*
* Where KEY can be any of the supported intrinsics; this is then
* transformed into a runtime call:
*
* void _lfortran_KEY(float x, float *result)
*/
llvm::Value* lfortran_intrinsic(llvm::Function *fn, llvm::Value* pa, int a_kind)
{
llvm::Type *presult_type = getFPType(a_kind);
llvm::AllocaInst *presult = builder->CreateAlloca(presult_type, nullptr);
llvm::Value *a = CreateLoad(pa);
std::vector<llvm::Value*> args = {a, presult};
builder->CreateCall(fn, args);
return CreateLoad(presult);
}
void visit_TranslationUnit(const ASR::TranslationUnit_t &x) {
module = std::make_unique<llvm::Module>("LFortran", context);
module->setDataLayout("");
// All loose statements must be converted to a function, so the items
// must be empty:
LFORTRAN_ASSERT(x.n_items == 0);
// Define LLVM types that we might need
// Complex type is represented as an identified struct in LLVM
// %complex = type { float, float }
std::vector<llvm::Type*> els_4 = {
llvm::Type::getFloatTy(context),
llvm::Type::getFloatTy(context)};
std::vector<llvm::Type*> els_8 = {
llvm::Type::getDoubleTy(context),
llvm::Type::getDoubleTy(context)};
std::vector<llvm::Type*> els_4_ptr = {
llvm::Type::getFloatPtrTy(context),
llvm::Type::getFloatPtrTy(context)};
std::vector<llvm::Type*> els_8_ptr = {
llvm::Type::getDoublePtrTy(context),
llvm::Type::getDoublePtrTy(context)};
complex_type_4 = llvm::StructType::create(context, els_4, "complex_4");
complex_type_8 = llvm::StructType::create(context, els_8, "complex_8");
complex_type_4_ptr = llvm::StructType::create(context, els_4_ptr, "complex_4_ptr");
complex_type_8_ptr = llvm::StructType::create(context, els_8_ptr, "complex_8_ptr");
character_type = llvm::Type::getInt8PtrTy(context);
llvm::Type* size_arg = (llvm::Type*)llvm::StructType::create(context, std::vector<llvm::Type*>({
arr_descr->get_dimension_descriptor_type(true),
getIntType(4)}), "size_arg");
fname2arg_type["size"] = std::make_pair(size_arg, size_arg->getPointerTo());
llvm::Type* bound_arg = static_cast<llvm::Type*>(arr_descr->get_dimension_descriptor_type(true));
fname2arg_type["lbound"] = std::make_pair(bound_arg, bound_arg->getPointerTo());
fname2arg_type["ubound"] = std::make_pair(bound_arg, bound_arg->getPointerTo());
// Process Variables first:
for (auto &item : x.m_global_scope->scope) {
if (is_a<ASR::Variable_t>(*item.second)) {
visit_symbol(*item.second);
}
}
prototype_only = false;
for (auto &item : x.m_global_scope->scope) {
if (is_a<ASR::Module_t>(*item.second) &&
item.first.find("lfortran_intrinsic_optimization") != std::string::npos) {
ASR::Module_t* mod = ASR::down_cast<ASR::Module_t>(item.second);
for( auto &moditem: mod->m_symtab->scope ) {
ASR::symbol_t* sym = ASRUtils::symbol_get_past_external(moditem.second);
if (is_a<ASR::Subroutine_t>(*sym)) {
visit_Subroutine(*ASR::down_cast<ASR::Subroutine_t>(sym));
} else if (is_a<ASR::Function_t>(*sym)) {
visit_Function(*ASR::down_cast<ASR::Function_t>(sym));
}
}
}
}
prototype_only = true;
// Generate function prototypes
for (auto &item : x.m_global_scope->scope) {
if (is_a<ASR::Function_t>(*item.second)) {
visit_Function(*ASR::down_cast<ASR::Function_t>(item.second));
}
if (is_a<ASR::Subroutine_t>(*item.second)) {
visit_Subroutine(*ASR::down_cast<ASR::Subroutine_t>(item.second));
}
}
prototype_only = false;
// TODO: handle depencencies across modules and main program
// Then do all the modules in the right order
std::vector<std::string> build_order
= determine_module_dependencies(x);
for (auto &item : build_order) {
LFORTRAN_ASSERT(x.m_global_scope->scope.find(item)
!= x.m_global_scope->scope.end());
ASR::symbol_t *mod = x.m_global_scope->scope[item];
visit_symbol(*mod);
}
// Then do all the procedures
for (auto &item : x.m_global_scope->scope) {
if (is_a<ASR::Function_t>(*item.second)
|| is_a<ASR::Subroutine_t>(*item.second)) {
visit_symbol(*item.second);
}
}
// Then the main program
for (auto &item : x.m_global_scope->scope) {
if (is_a<ASR::Program_t>(*item.second)) {
visit_symbol(*item.second);
}
}
}
void visit_Allocate(const ASR::Allocate_t& x) {
for( size_t i = 0; i < x.n_args; i++ ) {
ASR::alloc_arg_t curr_arg = x.m_args[i];
std::uint32_t h = get_hash((ASR::asr_t*)curr_arg.m_a);
LFORTRAN_ASSERT(llvm_symtab.find(h) != llvm_symtab.end());
llvm::Value* x_arr = llvm_symtab[h];
fill_malloc_array_details(x_arr, curr_arg.m_dims, curr_arg.n_dims);
}
if (x.m_stat) {
ASR::Variable_t *asr_target = EXPR2VAR(x.m_stat);
uint32_t h = get_hash((ASR::asr_t*)asr_target);
if (llvm_symtab.find(h) != llvm_symtab.end()) {
llvm::Value *target, *value;
target = llvm_symtab[h];
// Store 0 (success) in the stat variable
value = llvm::ConstantInt::get(context, llvm::APInt(32, 0));
builder->CreateStore(value, target);
} else {
throw CodeGenError("Stat variable in allocate not found in LLVM symtab");
}
}
}
void visit_Nullify(const ASR::Nullify_t& x) {
for( size_t i = 0; i < x.n_vars; i++ ) {
std::uint32_t h = get_hash((ASR::asr_t*)x.m_vars[i]);
llvm::Value *target = llvm_symtab[h];
llvm::Type* tp = target->getType()->getContainedType(0);
llvm::Value* np = builder->CreateIntToPtr(
llvm::ConstantInt::get(context, llvm::APInt(32, 0)), tp);
builder->CreateStore(np, target);
}
}
inline void call_lfortran_free(llvm::Function* fn) {
llvm::Value* arr = CreateLoad(arr_descr->get_pointer_to_data(tmp));
llvm::AllocaInst *arg_arr = builder->CreateAlloca(character_type, nullptr);
builder->CreateStore(builder->CreateBitCast(arr, character_type), arg_arr);
std::vector<llvm::Value*> args = {CreateLoad(arg_arr)};
builder->CreateCall(fn, args);
arr_descr->set_is_allocated_flag(tmp, 0);
}
template <typename T>
void _Deallocate(const T& x) {
std::string func_name = "_lfortran_free";
llvm::Function *free_fn = module->getFunction(func_name);
if (!free_fn) {
llvm::FunctionType *function_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(context), {
character_type
}, true);
free_fn = llvm::Function::Create(function_type,
llvm::Function::ExternalLinkage, func_name, *module);
}
for( size_t i = 0; i < x.n_vars; i++ ) {
const ASR::symbol_t* curr_obj = x.m_vars[i];
ASR::Variable_t *v = ASR::down_cast<ASR::Variable_t>(
symbol_get_past_external(curr_obj));
fetch_var(v);
if( x.class_type == ASR::stmtType::ImplicitDeallocate ) {
llvm::Value *cond = arr_descr->get_is_allocated_flag(tmp);