-
Notifications
You must be signed in to change notification settings - Fork 0
/
CompilerContext.cpp
1370 lines (1204 loc) · 43.5 KB
/
CompilerContext.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 "Compiler.h"
#include "CompilerContext.h"
#include "Types/Function.h"
#include "Lexer.h"
#include "Expressions.h"
#include "DeclarationExpressions.h"
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif // _DEBUG
using namespace Jet;
CompilerContext* CompilerContext::AddFunction(const std::string& fname, Type* ret, const std::vector<std::pair<Type*, std::string>>& args, Type* member, bool lambda)
{
Function* func = 0;
if (member)
{
//ok, if member just pass the type so we dont have to do this crap
int i = member->name.length() + 2;
std::string fname2 = fname.substr(++i, fname.length() - i);
auto range = member->data->functions.equal_range(fname2);
for (auto ii = range.first; ii != range.second; ii++)
{
//printf("found option for %s with %i args\n", fname.c_str(), ii->second->argst.size());
if (ii->second->arguments.size() == args.size())
{
func = ii->second;
}
}
}
else
{
func = root->ns->GetFunction(fname);
if (!func)
{
//no function exists, create it
func = new Function(fname, lambda);
func->return_type = ret;
func->arguments = args;
if (member == false)
this->root->ns->members.insert({ fname, func });
}
}
func->Load(this->root);
auto n = new CompilerContext(this->root, this);
n->function = func;
func->context = n;
llvm::BasicBlock *bb = llvm::BasicBlock::Create(root->context, "entry", n->function->f);
root->builder.SetInsertPoint(bb);
// Do not export lambdas
if (lambda)
func->do_export = false;
return n;
}
CValue CompilerContext::UnaryOperation(TokenType operation, CValue value)
{
llvm::Value* res = 0;
if (operation == TokenType::BAnd)
{
//this should already have been done elsewhere, so error
assert(false);
}
if (value.type->type == Types::Float || value.type->type == Types::Double)
{
switch (operation)
{
case TokenType::Minus:
res = root->builder.CreateFNeg(value.val);
break;
default:
this->root->Error("Invalid Unary Operation '" + TokenToString[operation] + "' On Type '" + value.type->ToString() + "'", *current_token);
break;
}
return CValue(value.type, res);
}
else if (value.type->IsInteger())//value.type->type == Types::Int || value.type->type == Types::Short || value.type->type == Types::Char)
{
//integer probably
switch (operation)
{
case TokenType::Increment:
res = root->builder.CreateAdd(value.val, root->builder.getInt32(1));
break;
case TokenType::Decrement:
res = root->builder.CreateSub(value.val, root->builder.getInt32(1));
break;
case TokenType::Minus:
res = root->builder.CreateNeg(value.val);
break;
case TokenType::BNot:
res = root->builder.CreateNot(value.val);
break;
default:
this->root->Error("Invalid Unary Operation '" + TokenToString[operation] + "' On Type '" + value.type->ToString() + "'", *current_token);
break;
}
return CValue(value.type, res);
}
else if (value.type->type == Types::Pointer)
{
switch (operation)
{
case TokenType::Asterisk:
return CValue(value.type->base, this->root->builder.CreateLoad(value.val), value.val);
case TokenType::Increment:
return CValue(value.type, this->root->builder.CreateGEP(value.val, root->builder.getInt32(1)));
case TokenType::Decrement:
return CValue(value.type, this->root->builder.CreateGEP(value.val, root->builder.getInt32(-1)));
default:
this->root->Error("Invalid Unary Operation '" + TokenToString[operation] + "' On Type '" + value.type->base->ToString() + "'", *current_token);
}
}
else if (value.type->type == Types::Bool)
{
switch (operation)
{
case TokenType::Not:
return CValue(value.type, this->root->builder.CreateNot(value.val));
default:
break;
}
}
this->root->Error("Invalid Unary Operation '" + TokenToString[operation] + "' On Type '" + value.type->ToString() + "'", *current_token);
}
void CompilerContext::Store(CValue loc, CValue val, bool RVO)
{
if (loc.type->base->type == Types::Struct && RVO == false)
{
if (loc.type->base->data->is_class == true)
this->root->Error("Cannot copy class '" + loc.type->base->data->name + "' unless it has a copy operator.", *this->current_token);
// Handle equality operator if we can find it
auto funiter = val.type->data->functions.find("=");
//todo: search through multimap to find one with the right number of args
if (funiter != val.type->data->functions.end() && funiter->second->arguments.size() == 2)
{
llvm::Value* pointer = val.pointer;
if (val.pointer == 0)//its a value type (return value)
{
//ok, lets be dumb
//copy it to an alloca
auto TheFunction = this->function->f;
llvm::IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
TheFunction->getEntryBlock().begin());
pointer = TmpB.CreateAlloca(val.type->GetLLVMType(), 0, "return_pass_tmp");
this->root->builder.CreateStore(val.val, pointer);
}
Function* fun = funiter->second;
fun->Load(this->root);
std::vector<CValue> argsv = { loc, CValue(loc.type, pointer) };
fun->Call(this, argsv, true);
if (pointer != val.pointer)
{
//destruct temp one
this->Destruct(CValue(val.type->GetPointerType(), pointer), 0);
}
return;
}
}
auto vall = this->DoCast(loc.type->base, val);
// Handle copying
if (loc.type->base->type == Types::Struct)
{
if (vall.val)
{
llvm::Instruction* I = llvm::dyn_cast<llvm::Instruction>(vall.val);
I->eraseFromParent();// remove the load so we dont freak out llvm doing a struct copy
}
auto dptr = root->builder.CreatePointerCast(loc.val, root->CharPointerType->GetLLVMType());
auto sptr = root->builder.CreatePointerCast(vall.pointer, root->CharPointerType->GetLLVMType());
root->builder.CreateMemCpy(dptr, sptr, loc.type->base->GetSize(), 1);
return;
}
else if (loc.type->base->type == Types::InternalArray)
{
llvm::Instruction* I = llvm::dyn_cast<llvm::Instruction>(vall.val);
I->eraseFromParent();// remove the load so we dont freak out llvm doing a struct copy
auto dptr = root->builder.CreatePointerCast(loc.val, root->CharPointerType->GetLLVMType());
auto sptr = root->builder.CreatePointerCast(vall.pointer, root->CharPointerType->GetLLVMType());
root->builder.CreateMemCpy(dptr, sptr, loc.type->base->GetSize(), 1);
return;
}
root->builder.CreateStore(vall.val, loc.val);
}
CValue CompilerContext::BinaryOperation(Jet::TokenType op, CValue left, CValue lhsptr, CValue right)
{
llvm::Value* res = 0;
if (left.type->type == Types::Pointer && right.type->IsInteger())
{
//ok, lets just do a GeP
if (op == TokenType::Plus)
return CValue(left.type, this->root->builder.CreateGEP(left.val, right.val));
else if (op == TokenType::Minus)
return CValue(left.type, this->root->builder.CreateGEP(left.val, this->root->builder.CreateNeg(right.val)));
}
else if (left.type->type == Types::Struct)
{
//operator overloads
const static std::map<Jet::TokenType, std::string> token_to_string = {
{ TokenType::Plus, "+" },
{ TokenType::Minus, "-" },
{ TokenType::Slash, "/" },
{ TokenType::Asterisk, "*" },
{ TokenType::LeftShift, "<<" },
{ TokenType::RightShift, ">>" },
{ TokenType::BAnd, "&" },
{ TokenType::BOr, "|" },
{ TokenType::Xor, "^" },
{ TokenType::Modulo, "%" },
{ TokenType::LessThan, "<" },
{ TokenType::GreaterThan, ">" },
{ TokenType::LessThanEqual, "<=" },
{ TokenType::GreaterThanEqual, ">=" }
};
auto res = token_to_string.find(op);
if (res != token_to_string.end())
{
auto funiter = left.type->data->functions.find(res->second);
//todo: search through multimap to find one with the right number of args
//check args
if (funiter != left.type->data->functions.end() && funiter->second->arguments.size() == 2)
{
Function* fun = funiter->second;
fun->Load(this->root);
std::vector<CValue> argsv = { lhsptr, right };
return fun->Call(this, argsv, true);//for now lets keep these operators non-virtual
}
}
}
//try to do a cast
right = this->DoCast(left.type, right);
if (left.type->type != right.type->type)
{
root->Error("Cannot perform a binary operation between two incompatible types", *this->current_token);
}
if (left.type->type == Types::Float || left.type->type == Types::Double)
{
switch (op)
{
case TokenType::AddAssign:
case TokenType::Plus:
res = root->builder.CreateFAdd(left.val, right.val);
break;
case TokenType::SubtractAssign:
case TokenType::Minus:
res = root->builder.CreateFSub(left.val, right.val);
break;
case TokenType::MultiplyAssign:
case TokenType::Asterisk:
res = root->builder.CreateFMul(left.val, right.val);
break;
case TokenType::DivideAssign:
case TokenType::Slash:
res = root->builder.CreateFDiv(left.val, right.val);
break;
case TokenType::LessThan:
//use U or O?
res = root->builder.CreateFCmpULT(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::LessThanEqual:
res = root->builder.CreateFCmpULE(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::GreaterThan:
res = root->builder.CreateFCmpUGT(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::GreaterThanEqual:
res = root->builder.CreateFCmpUGE(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::Equals:
res = root->builder.CreateFCmpUEQ(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::NotEqual:
res = root->builder.CreateFCmpUNE(left.val, right.val);
return CValue(root->BoolType, res);
break;
default:
this->root->Error("Invalid Binary Operation '" + TokenToString[op] + "' On Type '" + left.type->ToString() + "'", *current_token);
break;
}
return CValue(left.type, res);
}
else if (left.type->IsInteger())
{
//integer probably
switch (op)
{
case TokenType::AddAssign:
case TokenType::Plus:
res = root->builder.CreateAdd(left.val, right.val);
break;
case TokenType::SubtractAssign:
case TokenType::Minus:
res = root->builder.CreateSub(left.val, right.val);
break;
case TokenType::MultiplyAssign:
case TokenType::Asterisk:
res = root->builder.CreateMul(left.val, right.val);
break;
case TokenType::DivideAssign:
case TokenType::Slash:
if (left.type->IsSignedInteger())//signed
res = root->builder.CreateSDiv(left.val, right.val);
else//unsigned
res = root->builder.CreateUDiv(left.val, right.val);
break;
case TokenType::Modulo:
if (left.type->IsSignedInteger())//signed
res = root->builder.CreateSRem(left.val, right.val);
else//unsigned
res = root->builder.CreateURem(left.val, right.val);
break;
case TokenType::LessThan:
//use U or S?
if (left.type->IsSignedInteger())
res = root->builder.CreateICmpSLT(left.val, right.val);
else
res = root->builder.CreateICmpULT(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::LessThanEqual:
if (left.type->IsSignedInteger())
res = root->builder.CreateICmpSLE(left.val, right.val);
else
res = root->builder.CreateICmpULE(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::GreaterThan:
if (left.type->IsSignedInteger())
res = root->builder.CreateICmpSGT(left.val, right.val);
else
res = root->builder.CreateICmpUGT(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::GreaterThanEqual:
if (left.type->IsSignedInteger())
res = root->builder.CreateICmpSGE(left.val, right.val);
else
res = root->builder.CreateICmpUGE(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::Equals:
res = root->builder.CreateICmpEQ(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::NotEqual:
res = root->builder.CreateICmpNE(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::BAnd:
case TokenType::AndAssign:
res = root->builder.CreateAnd(left.val, right.val);
break;
case TokenType::BOr:
case TokenType::OrAssign:
res = root->builder.CreateOr(left.val, right.val);
break;
case TokenType::Xor:
case TokenType::XorAssign:
res = root->builder.CreateXor(left.val, right.val);
break;
case TokenType::LeftShift:
res = root->builder.CreateShl(left.val, right.val);
break;
case TokenType::RightShift:
res = root->builder.CreateLShr(left.val, right.val);
break;
default:
this->root->Error("Invalid Binary Operation '" + TokenToString[op] + "' On Type '" + left.type->ToString() + "'", *current_token);
break;
}
return CValue(left.type, res);
}
else if (left.type->type == Types::Pointer)
{
//com
switch (op)
{
case TokenType::Equals:
res = root->builder.CreateICmpEQ(left.val, right.val);
return CValue(root->BoolType, res);
break;
case TokenType::NotEqual:
res = root->builder.CreateICmpNE(left.val, right.val);
return CValue(root->BoolType, res);
break;
}
}
this->root->Error("Invalid Binary Operation '" + TokenToString[op] + "' On Type '" + left.type->ToString() + "'", *current_token);
}
Function* CompilerContext::GetMethod(const std::string& name, const std::vector<Type*>& args, Type* Struct)
{
Function* fun = 0;
if (Struct == 0)
{
//global function?
auto iter = this->root->GetFunction(name);
if (iter == 0)
{
//check if its a type, if so try and find a constructor
auto type = this->root->TryLookupType(name);
if (type != 0 && type->type == Types::Struct)
{
type->Load(this->root);
//look for a constructor
//if we are template, remove the templated part
auto tmp_name = name;
if (name.back() == '>')
tmp_name = name.substr(0, name.find_first_of('<'));
auto range = type->data->functions.equal_range(tmp_name);
for (auto ii = range.first; ii != range.second; ii++)
{
if (ii->second->arguments.size() == args.size() + 1)
fun = ii->second;
}
if (fun)
{
return fun;
}
}
}
if (name[name.length() - 1] == '>')//its a template
{
int i = name.find_first_of('<');
auto base_name = name.substr(0, i);
//auto range = this->root->functions.equal_range(name);
auto type = this->root->LookupType(name);
if (type)
{
auto fun = type->data->functions.find(type->data->template_base->name);
if (fun != type->data->functions.end())
return fun->second;
else
return 0;
}
//instantiate here
this->root->Error("Not implemented", *this->current_token);
//return range.first->second;
}
//look for the best one
fun = this->root->GetFunction(name, args);
if (fun && fun->templates.size() > 0)
{
auto templates = new Type*[fun->templates.size()];
for (unsigned int i = 0; i < fun->templates.size(); i++)
templates[i] = 0;
//need to infer
if (fun->arguments.size() > 0)
{
int i = 0;
for (auto ii : fun->templates)
{
//look for stuff in args
int i2 = 0;
for (auto iii : fun->arguments)
{
//get the name of the variable
unsigned int subl = 0;
for (; subl < iii.first->name.length(); subl++)
{
if (!IsLetter(iii.first->name[subl]))//todo this might break with numbers in variable names
break;
}
//check if it refers to same type
std::string sub = iii.first->name.substr(0, subl);
//check if it refers to this type
if (sub/*iii.first->name*/ == ii.second)
{
//found it
if (templates[i] != 0 && templates[i] != args[i2])
this->root->Error("Could not infer template type", *this->current_token);
//need to convert back to root type
Type* top_type = args[i2];
Type* cur_type = args[i2];
//work backwards to get to the type
int pos = iii.first->name.size() - 1;
while (pos >= 0)
{
char c = iii.first->name[pos];
if (c == '*' && cur_type->type == Types::Pointer)
cur_type = cur_type->base;
else if (!IsLetter(c))
this->root->Error("Could not infer template type", *this->current_token);
pos--;
}
templates[i] = cur_type;
}
i2++;
}
i++;
}
}
for (unsigned int i = 0; i < fun->templates.size(); i++)
{
if (templates[i] == 0)
this->root->Error("Could not infer template type", *this->current_token);
}
auto oldname = fun->expression->name.text;
fun->expression->name.text += '<';
for (unsigned int i = 0; i < fun->templates.size(); i++)
{
fun->expression->name.text += templates[i]->ToString();
if (i + 1 < fun->templates.size())
fun->expression->name.text += ',';
}
fun->expression->name.text += '>';
auto rname = fun->expression->name.text;
//register the types
int i = 0;
for (auto ii : fun->templates)
{
//check if traits match
if (templates[i]->MatchesTrait(this->root, ii.first->trait) == false)
root->Error("Type '" + templates[i]->name + "' doesn't match Trait '" + ii.first->name + "'", *root->current_function->current_token);
root->ns->members.insert({ ii.second, templates[i++] });
}
//store then restore insertion point
auto rp = root->builder.GetInsertBlock();
auto dp = root->builder.getCurrentDebugLocation();
fun->expression->CompileDeclarations(this);
fun->expression->DoCompile(this);
root->builder.SetCurrentDebugLocation(dp);
if (rp)
root->builder.SetInsertPoint(rp);
fun->expression->name.text = oldname;
//time to recompile and stuff
return root->ns->members.find(rname)->second.fn;
}
return fun;
}
else
{
return Struct->GetMethod(name, args, this);
}
}
CValue CompilerContext::Call(const std::string& name, const std::vector<CValue>& args, Type* Struct, bool devirtualize)
{
std::vector<Type*> arsgs;
for (auto ii : args)
arsgs.push_back(ii.type);
auto old_tok = this->current_token;
Function* fun = this->GetMethod(name, arsgs, Struct);
this->current_token = old_tok;
if (fun == 0 && Struct == 0)
{
//try and find something like a variable or constructor in the global namespace
auto type = this->root->TryLookupType(name);
if (type != 0 && type->type == Types::Struct)// If we found a type, call its constructor like a function
{
// Look for its constructor
auto range = type->data->functions.equal_range(name);
for (auto ii = range.first; ii != range.second; ii++)
{
if (ii->second->arguments.size() == args.size())
fun = ii->second;
}
if (fun)
{
//ok, we allocate, call then
//allocate thing
type->Load(this->root);
auto TheFunction = this->function->f;
llvm::IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
TheFunction->getEntryBlock().begin());
auto Alloca = TmpB.CreateAlloca(type->GetLLVMType(), 0, "constructortemp");
std::vector<llvm::Value*> argsv;
int i = 1;
argsv.push_back(Alloca);// add 'this' ptr
for (auto ii : args)// add other arguments
argsv.push_back(this->DoCast(fun->arguments[i++].first, ii).val);//try and cast to the correct type if we can
fun->Load(this->root);
this->root->builder.CreateCall(fun->f, argsv);
return CValue(type, this->root->builder.CreateLoad(Alloca), Alloca);
}
else // Fake a constructor if we couldnt find one
{
type->Load(this->root);
if (type->type == Types::Struct)
{
auto TheFunction = this->function->f;
llvm::IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
TheFunction->getEntryBlock().begin());
auto Alloca = TmpB.CreateAlloca(type->GetLLVMType(), 0, "constructortemp");
//store defaults here...
return CValue(type, this->root->builder.CreateLoad(Alloca), Alloca);
}
return CValue(type, type->GetDefaultValue(this->root));
}
}
else
{
//try to find it in variables
auto var = this->GetVariable(name);
if (var.type->type != Types::Function && (var.type->type != Types::Pointer || var.type->base->type != Types::Function))
{
if (var.type->type == Types::Pointer && var.type->base->type == Types::Struct && var.type->base->data->template_base && var.type->base->data->template_base->name == "function")
{
auto function_ptr = this->root->builder.CreateGEP(var.val, { this->root->builder.getInt32(0), this->root->builder.getInt32(0) }, "fptr");
//get the template param to examine the type
auto type = var.type->base->data->members.begin()->second.ty;// .find("T")->second.ty;
if (args.size() != type->function->args.size())
this->root->Error("Too many args in function call got " + std::to_string(args.size()) + " expected " + std::to_string(type->function->args.size()), *this->current_token);
std::vector<llvm::Value*> argsv;
for (unsigned int i = 0; i < args.size(); i++)
argsv.push_back(this->DoCast(type->function->args[i], args[i]).val);//try and cast to the correct type if we can
//add the data
auto data_ptr = this->root->builder.CreateGEP(var.val, { this->root->builder.getInt32(0), this->root->builder.getInt32(1) });
data_ptr = this->root->builder.CreateGEP(data_ptr, { this->root->builder.getInt32(0), this->root->builder.getInt32(0) });
argsv.push_back(data_ptr);
llvm::Value* fun = this->root->builder.CreateLoad(function_ptr);
auto rtype = fun->getType()->getContainedType(0)->getContainedType(0);
std::vector<llvm::Type*> fargs;
for (unsigned int i = 1; i < fun->getType()->getContainedType(0)->getNumContainedTypes(); i++)
fargs.push_back(fun->getType()->getContainedType(0)->getContainedType(i));
fargs.push_back(this->root->builder.getInt8PtrTy());
auto fp = llvm::FunctionType::get(rtype, fargs, false)->getPointerTo();
fun = this->root->builder.CreatePointerCast(fun, fp);
return CValue(type->function->return_type, this->root->builder.CreateCall(fun, argsv));
}
else
this->root->Error("Cannot call non-function type", *this->current_token);
}
if (var.type->type == Types::Pointer && var.type->base->type == Types::Function)
{
var.val = this->root->builder.CreateLoad(var.val);
var.type = var.type->base;
}
std::vector<llvm::Value*> argsv;
for (unsigned int i = 0; i < args.size(); i++)
argsv.push_back(this->DoCast(var.type->function->args[i], args[i]).val);//try and cast to the correct type if we can
return CValue(var.type->function->return_type, this->root->builder.CreateCall(var.val, argsv));
}
this->root->Error("Function '" + name + "' with " + std::to_string(args.size()) + " arguments is not defined", *this->current_token);
}
else if (fun == 0)
{
this->root->Error("Function '" + name + "' is not defined on object '" + Struct->ToString() + "'", *this->current_token);
}
fun->Load(this->root);
//todo: fixme this isnt a very reliable fix
if (args.size() + (fun->return_type->type == Types::Struct ? 1 : 0) != fun->f->arg_size() && fun->arguments.size() > 0 && fun->arguments[0].second == "this")
{
//ok, we allocate, call then
//allocate thing
auto type = fun->arguments[0].first->base;
type->Load(this->root);
auto TheFunction = this->function->f;
llvm::IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
TheFunction->getEntryBlock().begin());
auto Alloca = TmpB.CreateAlloca(type->GetLLVMType(), 0, "constructortemp");
std::vector<llvm::Value*> argsv;
int i = 1;
//add struct
argsv.push_back(Alloca);
for (auto ii : args)
argsv.push_back(this->DoCast(fun->arguments[i++].first, ii).val);//try and cast to the correct type if we can
fun->Load(this->root);
this->root->builder.CreateCall(fun->f, argsv);
return CValue(type, this->root->builder.CreateLoad(Alloca));
}
else if (args.size() != fun->f->arg_size() && fun->return_type->type != Types::Struct)
{
this->root->Error("Function expected " + std::to_string(fun->f->arg_size()) + " arguments, got " + std::to_string(args.size()), *this->current_token);
}
std::vector<CValue> argsv;
for (unsigned int i = 0; i < args.size(); i++)
argsv.push_back(this->DoCast(fun->arguments[i].first, args[i]));//try and cast to the correct type if we can
return fun->Call(this, argsv, devirtualize);
}
void CompilerContext::SetDebugLocation(const Token& t)
{
assert(this->function->loaded);
this->root->builder.SetCurrentDebugLocation(llvm::DebugLoc::get(t.line, t.column, this->function->scope));
}
CValue CompilerContext::GetVariable(const std::string& name)
{
auto cur = this->scope;
CValue value;
do
{
auto iter = cur->named_values.find(name);
if (iter != cur->named_values.end())
{
value = iter->second;
break;
}
cur = cur->prev;
} while (cur);
if (value.type->type == Types::Void)
{
auto sym = this->root->GetVariableOrFunction(name);
if (sym.type != SymbolType::Invalid)
{
if (sym.type == SymbolType::Function)
{
auto function = sym.fn;
function->Load(this->root);
return CValue(function->GetType(this->root), function->f);
}
else if (sym.type == SymbolType::Variable)
{
//variable
return *sym.val;
}
}
if (this->function->is_lambda)
{
auto var = this->parent->GetVariable(name);
//look in locals above me
CValue location = this->Load("_capture_data");
auto storage_t = this->function->lambda.storage_type;
//todo make sure this is the right location to do all of this
//append the new type
std::vector<llvm::Type*> types;
for (unsigned int i = 0; i < this->captures.size(); i++)
types.push_back(storage_t->getContainedType(i));
types.push_back(var.type->base->GetLLVMType());
storage_t = this->function->lambda.storage_type = storage_t->create(types);
auto data = root->builder.CreatePointerCast(location.val, storage_t->getPointerTo());
//load it, then store it as a local
auto val = root->builder.CreateGEP(data, { root->builder.getInt32(0), root->builder.getInt32(this->captures.size()) });
CValue value;
value.val = root->builder.CreateAlloca(var.type->base->GetLLVMType());
value.type = var.type;
this->RegisterLocal(name, value);//need to register it as immutable
root->builder.CreateStore(root->builder.CreateLoad(val), value.val);
this->captures.push_back(name);
return value;
}
this->root->Error("Undeclared identifier '" + name + "'", *current_token);
}
return value;
}
llvm::ReturnInst* CompilerContext::Return(CValue ret)
{
if (this->function == 0)
{
this->root->Error("Cannot return from outside function!", *current_token);
}
// Call destructors
auto cur = this->scope;
do
{
if (cur->destructed == false)
{
cur->Destruct(this, ret.pointer);
}
cur->destructed = true;
cur = cur->prev;
} while (cur);
if (ret.type->type == Types::Void)
{
return root->builder.CreateRetVoid();
}
else if (ret.type->type == Types::Struct)
{
llvm::Instruction* I = llvm::dyn_cast<llvm::Instruction>(ret.val);
I->eraseFromParent();// remove the load so we dont freak out llvm doing a struct copy
//do a memcpy
auto dptr = root->builder.CreatePointerCast(this->function->f->arg_begin(), this->root->CharPointerType->GetLLVMType());
auto sptr = root->builder.CreatePointerCast(ret.pointer, this->root->CharPointerType->GetLLVMType());
root->builder.CreateMemCpy(dptr, sptr, ret.type->GetSize(), 1);
return root->builder.CreateRetVoid();
}
// Try and cast to the return type if we can
if (ret.val)
{
ret = this->DoCast(this->function->return_type, ret);
}
return root->builder.CreateRet(ret.val);
}
CValue CompilerContext::DoCast(Type* t, CValue value, bool Explicit)
{
if (value.type->type == t->type && value.type->data == t->data)
return value;
llvm::Type* tt = t->GetLLVMType();
if (value.type->type == Types::Float && t->type == Types::Double)
{
return CValue(t, root->builder.CreateFPExt(value.val, tt));
}
if (value.type->type == Types::Double && t->type == Types::Float)
{
// Todo warn for downcasting if implicit
return CValue(t, root->builder.CreateFPTrunc(value.val, tt));
}
if (value.type->type == Types::Double || value.type->type == Types::Float)
{
//float to int
if (t->IsSignedInteger())
return CValue(t, root->builder.CreateFPToSI(value.val, tt));
else if (t->IsInteger())
return CValue(t, root->builder.CreateFPToUI(value.val, tt));
//todo: maybe do a warning if implicit from float->int or larger as it cant directly fit 1 to 1
}
if (value.type->IsInteger())
{
//int to float
if (t->type == Types::Double || t->type == Types::Float)
{
if (value.type->IsSignedInteger())
return CValue(t, root->builder.CreateSIToFP(value.val, tt));
else
return CValue(t, root->builder.CreateUIToFP(value.val, tt));
}
if (t->type == Types::Bool)
return CValue(t, root->builder.CreateIsNotNull(value.val));
if (t->type == Types::Pointer)
{
llvm::ConstantInt* ty = llvm::dyn_cast<llvm::ConstantInt>(value.val);
if (Explicit == false && (ty == 0 || ty->getSExtValue() != 0))
root->Error("Cannot cast a non-zero integer value to pointer implicitly.", *this->current_token);
return CValue(t, root->builder.CreateIntToPtr(value.val, t->GetLLVMType()));
}
if (t->IsSignedInteger())
return CValue(t, root->builder.CreateSExtOrTrunc(value.val, tt));
else if (t->IsInteger())
return CValue(t, root->builder.CreateZExtOrTrunc(value.val, tt));
}
if (value.type->type == Types::Pointer)
{
if (t->type == Types::Bool)
return CValue(t, root->builder.CreateIsNotNull(value.val));
if (t->type == Types::Pointer && value.type->base->type == Types::Array && value.type->base->base == t->base)
return CValue(t, root->builder.CreatePointerCast(value.val, t->GetLLVMType(), "arraycast"));
if (value.type->base->type == Types::Struct && t->type == Types::Pointer && t->base->type == Types::Struct)
{
if (value.type->base->data->IsParent(t->base))
{
return CValue(t, root->builder.CreatePointerCast(value.val, t->GetLLVMType(), "ptr2ptr"));
}
}
if (Explicit)
{
if (t->type == Types::Pointer)
{
return CValue(t, root->builder.CreatePointerCast(value.val, t->GetLLVMType(), "ptr2ptr"));
}
else if (t->IsInteger())
{
return CValue(t, root->builder.CreatePtrToInt(value.val, t->GetLLVMType(), "ptr2int"));
}
}
}
if (value.type->type == Types::InternalArray)
{
if (t->type == Types::Array && t->base == value.type->base)
{
// construct an array and use that
auto str_type = root->GetArrayType(value.type->base);
//alloc the struct for it
auto Alloca = root->builder.CreateAlloca(str_type->GetLLVMType(), root->builder.getInt32(1), "into_array");
auto size = root->builder.getInt32(value.type->size);
//store size
auto size_p = root->builder.CreateGEP(Alloca, { root->builder.getInt32(0), root->builder.getInt32(0) });
root->builder.CreateStore(size, size_p);
//store data pointer
auto data_p = root->builder.CreateGEP(Alloca, { root->builder.getInt32(0), root->builder.getInt32(1) });
auto data_v = root->builder.CreateGEP(value.pointer, { root->builder.getInt32(0), root->builder.getInt32(0) });
//value.val->dump();
//value.val->getType()->dump();
//value.pointer->dump();
//value.pointer->getType()->dump();
root->builder.CreateStore(data_v, data_p);
// todo do we need this load?
return CValue(t, this->root->builder.CreateLoad(Alloca));
}
}
if (value.type->type == Types::Array)
{
if (t->type == Types::Pointer)// array to pointer
{
if (t->base == value.type->base)
{
//ok for now lets not allow this, users can just access the ptr field
/*std::vector<llvm::Value*> arr = { root->builder.getInt32(0), root->builder.getInt32(0) };