-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.cpp
More file actions
1096 lines (904 loc) · 40 KB
/
codegen.cpp
File metadata and controls
1096 lines (904 loc) · 40 KB
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 "ast.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <llvm/IR/Verifier.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/InstCombine/InstCombine.h>
#include <llvm/Transforms/Utils/Mem2Reg.h>
#include <llvm/Transforms/Scalar/GVN.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/IR/PassManager.h>
#include <llvm/Passes/PassBuilder.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/Utils/Cloning.h>
// Debug flag to enable verbose output
#define DEBUG_OUTPUT 1
// Helper function for debug output
void debugOutput(const std::string& message) {
#if DEBUG_OUTPUT
std::cout << "[DEBUG] " << message << std::endl;
#endif
}
static void ensureTerminatorForBlock(llvm::BasicBlock *BB, llvm::Function *F, llvm::IRBuilder<> &Builder) {
// If there's already a terminator, do nothing.
if (BB->getTerminator()) return;
Builder.SetInsertPoint(BB);
if (F->getReturnType()->isVoidTy()) {
Builder.CreateRetVoid();
} else {
Builder.CreateRet(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(F->getContext()), 0));
}
}
// Helper functions for printf
static llvm::Function* createPrintfFunction(CodeGenContext& context) {
std::vector<llvm::Type*> args;
args.push_back(llvm::PointerType::get(context.context, 0));
llvm::FunctionType* printfType = llvm::FunctionType::get(
llvm::Type::getInt32Ty(context.context), args, true);
llvm::Function* func = llvm::Function::Create(
printfType, llvm::Function::ExternalLinkage, "printf", context.module.get());
return func;
}
// Helper function to create allocas at the entry block of a function
llvm::AllocaInst* CodeGenContext::createEntryBlockAlloca(llvm::Function* function,
const std::string& varName,
llvm::Type* type) {
if (!function) {
std::cerr << "Error: Null function in createEntryBlockAlloca" << std::endl;
return nullptr;
}
llvm::IRBuilder<> TmpB(&function->getEntryBlock(),
function->getEntryBlock().begin());
return TmpB.CreateAlloca(type, nullptr, varName.c_str());
}
// Implementation of code generation for expressions
llvm::Value* IntLiteral::codegen(CodeGenContext& context) {
return llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.context), value);
}
llvm::Value* BoolLiteral::codegen(CodeGenContext& context) {
return llvm::ConstantInt::get(llvm::Type::getInt1Ty(context.context), value ? 1 : 0);
}
llvm::Value* StringLiteral::codegen(CodeGenContext& context) {
llvm::Constant* strConstant = llvm::ConstantDataArray::getString(context.context, value);
// Create a global variable for the string constant
llvm::GlobalVariable* globalStr = new llvm::GlobalVariable(
*context.module, strConstant->getType(), true,
llvm::GlobalValue::PrivateLinkage, strConstant, ".str");
// Get a pointer to the beginning of the string
llvm::Value* zero = llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.context), 0);
std::vector<llvm::Value*> indices;
indices.push_back(zero);
indices.push_back(zero);
// Use the correct GEP instruction for LLVM 19
return context.builder.CreateGEP(strConstant->getType(), globalStr,
llvm::ArrayRef<llvm::Value*>(indices), "strptr");
}
llvm::Value* VarExpr::codegen(CodeGenContext& context) {
// Look up the variable in the named values map
auto it = context.namedValues.find(name);
if (it == context.namedValues.end() || !it->second) {
std::cerr << "Unknown variable: " << name << std::endl;
return nullptr;
}
llvm::AllocaInst* alloca = it->second;
if (!alloca) {
std::cerr << "Error: Null alloca for variable: " << name << std::endl;
return nullptr;
}
// Use the correct load instruction for LLVM 19
return context.builder.CreateLoad(alloca->getAllocatedType(), alloca, name.c_str());
}
llvm::Value* BinaryExpr::codegen(CodeGenContext& context) {
if (!lhs || !rhs) {
std::cerr << "Error: Null operand in binary expression" << std::endl;
return nullptr;
}
llvm::Value* L = lhs->codegen(context);
llvm::Value* R = rhs->codegen(context);
if (!L || !R) {
std::cerr << "Error: Failed to generate code for binary expression operands" << std::endl;
return nullptr;
}
// Handle logical operations
if (op == BinaryOp::AND || op == BinaryOp::OR) {
// Convert operands to boolean if needed
if (!L->getType()->isIntegerTy(1)) {
L = context.builder.CreateICmpNE(
L, llvm::ConstantInt::get(L->getType(), 0), "tobool");
}
if (!R->getType()->isIntegerTy(1)) {
R = context.builder.CreateICmpNE(
R, llvm::ConstantInt::get(R->getType(), 0), "tobool");
}
if (op == BinaryOp::AND) {
return context.builder.CreateAnd(L, R, "andtmp");
} else { // op == BinaryOp::OR
return context.builder.CreateOr(L, R, "ortmp");
}
}
// Check if we're dealing with string concatenation (string + anything)
bool isStringL = L->getType()->isPointerTy();
bool isStringR = R->getType()->isPointerTy();
// If either operand is a string and we're doing addition, handle as string concatenation
if (op == BinaryOp::ADD && (isStringL || isStringR)) {
// Get or create the printf function for formatting
llvm::Function* printfFunc = context.module.get()->getFunction("printf");
if (!printfFunc) {
printfFunc = createPrintfFunction(context);
}
// Get or create snprintf function for string formatting
llvm::Function* snprintfFunc = context.module.get()->getFunction("snprintf");
if (!snprintfFunc) {
std::vector<llvm::Type*> args;
args.push_back(llvm::PointerType::get(context.context, 0)); // char* buffer
args.push_back(llvm::Type::getInt32Ty(context.context)); // size_t size
args.push_back(llvm::PointerType::get(context.context, 0)); // const char* format
llvm::FunctionType* snprintfType = llvm::FunctionType::get(
llvm::Type::getInt32Ty(context.context), args, true);
snprintfFunc = llvm::Function::Create(
snprintfType, llvm::Function::ExternalLinkage, "snprintf", context.module.get());
}
// Create a buffer for the result
llvm::AllocaInst* buffer = context.builder.CreateAlloca(
llvm::ArrayType::get(llvm::Type::getInt8Ty(context.context), 1024),
nullptr, "concat_buffer");
std::vector<llvm::Value*> formatArgs;
// Format string depends on the types of operands
std::string formatStr;
if (isStringL && isStringR) {
formatStr = "%s%s"; // string + string
formatArgs.push_back(L);
formatArgs.push_back(R);
} else if (isStringL && R->getType()->isIntegerTy()) {
formatStr = "%s%d"; // string + int
formatArgs.push_back(L);
formatArgs.push_back(R);
} else if (isStringR && L->getType()->isIntegerTy()) {
formatStr = "%d%s"; // int + string
formatArgs.push_back(L);
formatArgs.push_back(R);
} else {
std::cerr << "Unsupported operand types for string concatenation" << std::endl;
return nullptr;
}
// Create the format string
llvm::Value* formatStrVal = context.builder.CreateGlobalStringPtr(formatStr);
// Create the call to snprintf
std::vector<llvm::Value*> snprintfArgs;
snprintfArgs.push_back(context.builder.CreateBitCast(buffer, llvm::PointerType::get(context.context, 0)));
snprintfArgs.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.context), 1024));
snprintfArgs.push_back(formatStrVal);
snprintfArgs.insert(snprintfArgs.end(), formatArgs.begin(), formatArgs.end());
context.builder.CreateCall(snprintfFunc, snprintfArgs);
// Return the buffer as a string
return context.builder.CreateBitCast(buffer, llvm::PointerType::get(context.context, 0), "concat_result");
}
// For non-string operations, ensure both operands have the same type
if (L->getType() != R->getType()) {
debugOutput("Type mismatch in binary expression");
// Try to convert types if possible (e.g., int to float or vice versa)
if (L->getType()->isIntegerTy() && R->getType()->isIntegerTy()) {
// If both are integers but different bit widths, convert to the larger one
unsigned LBits = L->getType()->getIntegerBitWidth();
unsigned RBits = R->getType()->getIntegerBitWidth();
if (LBits < RBits) {
L = context.builder.CreateIntCast(L, R->getType(), true, "cast");
} else {
R = context.builder.CreateIntCast(R, L->getType(), true, "cast");
}
} else {
// For now, we don't handle other type conversions
return nullptr;
}
}
switch (op) {
case BinaryOp::ADD:
return context.builder.CreateAdd(L, R, "addtmp");
case BinaryOp::SUB:
return context.builder.CreateSub(L, R, "subtmp");
case BinaryOp::MUL:
return context.builder.CreateMul(L, R, "multmp");
case BinaryOp::DIV:
return context.builder.CreateSDiv(L, R, "divtmp");
case BinaryOp::EQ:
return context.builder.CreateICmpEQ(L, R, "eqtmp");
case BinaryOp::NEQ:
return context.builder.CreateICmpNE(L, R, "neqtmp");
case BinaryOp::LT:
return context.builder.CreateICmpSLT(L, R, "lttmp");
case BinaryOp::GT:
return context.builder.CreateICmpSGT(L, R, "gttmp");
default:
std::cerr << "Unknown binary operator" << std::endl;
return nullptr;
}
}
// Implementation of code generation for statements
llvm::Value* DeclStmt::codegen(CodeGenContext& context) {
if (!initializer) {
std::cerr << "Error: Null initializer in declaration statement" << std::endl;
return nullptr;
}
// Check if variable already exists in current scope
auto it = context.namedValues.find(name);
if (it != context.namedValues.end()) {
std::cerr << "Error: Variable '" << name << "' already defined in this scope" << std::endl;
return nullptr;
}
llvm::Function* function = context.builder.GetInsertBlock()->getParent();
if (!function) {
std::cerr << "Error: Null function in declaration statement" << std::endl;
return nullptr;
}
// Generate code for the initializer
llvm::Value* initVal = initializer->codegen(context);
if (!initVal) {
std::cerr << "Error: Failed to generate initializer for " << name << std::endl;
return nullptr;
}
// Create an alloca for this variable
llvm::AllocaInst* alloca = context.createEntryBlockAlloca(
function, name, initVal->getType());
if (!alloca) {
std::cerr << "Error: Failed to create alloca for " << name << std::endl;
return nullptr;
}
// Store the initial value into the alloca
context.builder.CreateStore(initVal, alloca);
// Add the variable to the symbol table
context.namedValues[name] = alloca;
return alloca;
}
llvm::Value* AssignStmt::codegen(CodeGenContext& context) {
if (!value) {
std::cerr << "Error: Null value in assignment statement" << std::endl;
return nullptr;
}
// Look up the variable in the named values map
auto it = context.namedValues.find(name);
if (it == context.namedValues.end() || !it->second) {
std::cerr << "Unknown variable: " << name << std::endl;
return nullptr;
}
llvm::AllocaInst* alloca = it->second;
// Generate code for the value being assigned
llvm::Value* val = value->codegen(context);
if (!val) {
std::cerr << "Error: Failed to generate value for assignment to " << name << std::endl;
return nullptr;
}
// Store the value into the alloca
context.builder.CreateStore(val, alloca);
return val;
}
llvm::Value* IfStmt::codegen(CodeGenContext& context) {
debugOutput("Generating code for if statement");
if (!condition) {
std::cerr << "Error: Null condition in if statement" << std::endl;
return nullptr;
}
llvm::Value* condValue = condition->codegen(context);
if (!condValue) {
std::cerr << "Error: Failed to generate condition for if statement" << std::endl;
return nullptr;
}
// Convert condition to a boolean (i1)
if (!condValue->getType()->isIntegerTy(1)) {
condValue = context.builder.CreateICmpNE(
condValue, llvm::ConstantInt::get(condValue->getType(), 0), "ifcond");
}
llvm::Function* function = context.builder.GetInsertBlock()->getParent();
if (!function) {
std::cerr << "Error: Null function in if statement" << std::endl;
return nullptr;
}
// Save the current block to continue from
llvm::BasicBlock* currentBlock = context.builder.GetInsertBlock();
// Create blocks for the then, else, and merge cases
llvm::BasicBlock* thenBB = llvm::BasicBlock::Create(context.context, "then", function);
llvm::BasicBlock* elseBB = elseBlock ?
llvm::BasicBlock::Create(context.context, "else") : nullptr;
llvm::BasicBlock* mergeBB = llvm::BasicBlock::Create(context.context, "ifcont");
// Create the conditional branch
context.builder.CreateCondBr(condValue, thenBB, elseBB ? elseBB : mergeBB);
// Emit the 'then' block
context.builder.SetInsertPoint(thenBB);
debugOutput("Setting insertion point to then block");
if (thenBlock) {
for (auto stmt : *thenBlock) {
if (stmt) {
stmt->codegen(context);
// If we just generated a return statement, don't continue generating code
if (dynamic_cast<ReturnStmt*>(stmt) && !context.builder.GetInsertBlock()->getTerminator()) {
break;
}
}
}
}
// Create a branch to the merge block if there isn't already a terminator
if (!context.builder.GetInsertBlock()->getTerminator()) {
debugOutput("Adding branch from then block to merge block");
context.builder.CreateBr(mergeBB);
}
// Emit the 'else' block if present
if (elseBlock) {
// Add the else block to the function
elseBB->insertInto(function);
context.builder.SetInsertPoint(elseBB);
debugOutput("Setting insertion point to else block");
for (auto stmt : *elseBlock) {
if (stmt) {
stmt->codegen(context);
// If we just generated a return statement, don't continue generating code
if (dynamic_cast<ReturnStmt*>(stmt) && !context.builder.GetInsertBlock()->getTerminator()) {
break;
}
}
}
// Create a branch to the merge block if there isn't already a terminator
if (!context.builder.GetInsertBlock()->getTerminator()) {
debugOutput("Adding branch from else block to merge block");
context.builder.CreateBr(mergeBB);
}
}
// Add the merge block to the function
mergeBB->insertInto(function);
// Set insertion point to merge block
context.builder.SetInsertPoint(mergeBB);
debugOutput("Setting insertion point to merge block");
return llvm::Constant::getNullValue(llvm::Type::getInt32Ty(context.context));
}
llvm::Value* LoopStmt::codegen(CodeGenContext& context) {
debugOutput("Generating code for loop statement");
if (!count) {
std::cerr << "Error: Null count in loop statement" << std::endl;
return nullptr;
}
llvm::Function* function = context.builder.GetInsertBlock()->getParent();
if (!function) {
std::cerr << "Error: Null function in loop statement" << std::endl;
return nullptr;
}
// Save the current insertion point (preheader)
llvm::BasicBlock* preheaderBB = context.builder.GetInsertBlock();
static int loopCounter = 0;
loopCounter++;
llvm::BasicBlock* loopBB = llvm::BasicBlock::Create(context.context,
"loop" + std::to_string(loopCounter), function);
llvm::BasicBlock* afterBB = llvm::BasicBlock::Create(context.context,
"afterloop" + std::to_string(loopCounter));
// Generate the loop count
llvm::Value* countValue = count->codegen(context);
if (!countValue) {
std::cerr << "Error: Failed to generate count for loop statement" << std::endl;
return nullptr;
}
// Create and initialize counter variable to 0
llvm::AllocaInst* counter = context.createEntryBlockAlloca(
function, "loopcounter", llvm::Type::getInt32Ty(context.context));
context.builder.CreateStore(
llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.context), 0), counter);
// Branch from preheader to loop block
if (!preheaderBB->getTerminator()) {
context.builder.CreateBr(loopBB);
}
// Start insertion in loop body
context.builder.SetInsertPoint(loopBB);
debugOutput("Setting insertion point to loop block");
// Generate the loop body statements
if (body) {
for (auto stmt : *body) {
if (stmt) {
stmt->codegen(context);
// If we just generated a return statement, don't continue generating code
if (dynamic_cast<ReturnStmt*>(stmt) && !context.builder.GetInsertBlock()->getTerminator()) {
break;
}
}
}
}
// If we have a terminator (like a return), skip the rest of the loop logic
if (context.builder.GetInsertBlock()->getTerminator()) {
// Add the after block to the function and set insertion point
afterBB->insertInto(function);
context.builder.SetInsertPoint(afterBB);
return llvm::Constant::getNullValue(llvm::Type::getInt32Ty(context.context));
}
// Increment the counter
llvm::Value* currentCount = context.builder.CreateLoad(
counter->getAllocatedType(), counter, "currentcount");
llvm::Value* nextCount = context.builder.CreateAdd(
currentCount, llvm::ConstantInt::get(
llvm::Type::getInt32Ty(context.context), 1), "nextcount");
context.builder.CreateStore(nextCount, counter);
// Check loop condition: nextCount < countValue
llvm::Value* endCond = context.builder.CreateICmpSLT(
nextCount, countValue, "loopcond");
// Conditional branch: back to loop or to after block
context.builder.CreateCondBr(endCond, loopBB, afterBB);
// Append the after block and set insertion point
afterBB->insertInto(function);
context.builder.SetInsertPoint(afterBB);
debugOutput("Setting insertion point to afterloop block");
return llvm::Constant::getNullValue(
llvm::Type::getInt32Ty(context.context));
}
llvm::Value* PrintStmt::codegen(CodeGenContext& context) {
if (!value) {
std::cerr << "Error: Null value in print statement" << std::endl;
return nullptr;
}
// Get or create the printf function
llvm::Function* printfFunc = context.module.get()->getFunction("printf");
if (!printfFunc) {
printfFunc = createPrintfFunction(context);
}
if (!printfFunc) {
std::cerr << "Error: Failed to create printf function" << std::endl;
return nullptr;
}
// Special handling for BinaryExpr with string concatenation
if (auto binExpr = dynamic_cast<BinaryExpr*>(value)) {
if (binExpr->op == BinaryOp::ADD) {
// Check if either operand is a string
bool isStringLiteral = dynamic_cast<StringLiteral*>(binExpr->lhs) != nullptr ||
dynamic_cast<StringLiteral*>(binExpr->rhs) != nullptr;
if (isStringLiteral) {
// Handle string concatenation in print statement
std::vector<llvm::Value*> printfArgs;
std::string formatStr;
// Generate left operand
llvm::Value* lhsVal = binExpr->lhs->codegen(context);
if (!lhsVal) return nullptr;
// Generate right operand
llvm::Value* rhsVal = binExpr->rhs->codegen(context);
if (!rhsVal) return nullptr;
// Determine format string based on operand types
if (lhsVal->getType()->isPointerTy() && rhsVal->getType()->isIntegerTy()) {
// String + Int
formatStr = "%s%d\n";
printfArgs.push_back(context.builder.CreateGlobalStringPtr(formatStr));
printfArgs.push_back(lhsVal);
printfArgs.push_back(rhsVal);
} else if (lhsVal->getType()->isIntegerTy() && rhsVal->getType()->isPointerTy()) {
// Int + String
formatStr = "%d%s\n";
printfArgs.push_back(context.builder.CreateGlobalStringPtr(formatStr));
printfArgs.push_back(lhsVal);
printfArgs.push_back(rhsVal);
} else if (lhsVal->getType()->isPointerTy() && rhsVal->getType()->isPointerTy()) {
// String + String
formatStr = "%s%s\n";
printfArgs.push_back(context.builder.CreateGlobalStringPtr(formatStr));
printfArgs.push_back(lhsVal);
printfArgs.push_back(rhsVal);
} else {
// Fall back to normal binary expression
llvm::Value* val = binExpr->codegen(context);
if (!val) return nullptr;
if (val->getType()->isIntegerTy(32)) {
formatStr = "%d\n";
printfArgs.push_back(context.builder.CreateGlobalStringPtr(formatStr));
printfArgs.push_back(val);
} else if (val->getType()->isPointerTy()) {
formatStr = "%s\n";
printfArgs.push_back(context.builder.CreateGlobalStringPtr(formatStr));
printfArgs.push_back(val);
} else {
std::cerr << "Unsupported type for print statement" << std::endl;
return nullptr;
}
}
return context.builder.CreateCall(printfFunc, printfArgs, "printfcall");
}
}
}
// Normal handling for non-concatenation expressions
llvm::Value* val = value->codegen(context);
if (!val) {
std::cerr << "Error: Failed to generate value for print statement" << std::endl;
return nullptr;
}
// Choose format string based on the type of the value
std::string formatStr;
std::vector<llvm::Value*> args;
llvm::Type* valType = val->getType();
if (valType->isIntegerTy(32)) {
formatStr = "%d\n";
args.push_back(val);
} else if (valType->isIntegerTy(1)) {
// Boolean - print as "true" or "false"
formatStr = "%s\n";
llvm::Value* trueStr = context.builder.CreateGlobalStringPtr("true");
llvm::Value* falseStr = context.builder.CreateGlobalStringPtr("false");
args.push_back(context.builder.CreateSelect(val, trueStr, falseStr));
} else if (valType->isPointerTy()) {
// For pointers (including string pointers)
formatStr = "%s\n";
args.push_back(val);
} else {
std::cerr << "Unsupported type for print statement" << std::endl;
return nullptr;
}
// Create the format string
llvm::Value* formatStrVal = context.builder.CreateGlobalStringPtr(formatStr);
// Create the call to printf
std::vector<llvm::Value*> printfArgs;
printfArgs.push_back(formatStrVal);
printfArgs.insert(printfArgs.end(), args.begin(), args.end());
return context.builder.CreateCall(printfFunc, printfArgs, "printfcall");
}
// Implementation for the new ReturnStmt class
llvm::Value* ReturnStmt::codegen(CodeGenContext& context) {
debugOutput("Generating code for return statement");
if (!value) {
std::cerr << "Error: Null value in return statement" << std::endl;
return nullptr;
}
// Generate code for the return value
llvm::Value* retVal = value->codegen(context);
if (!retVal) {
std::cerr << "Error: Failed to generate return value" << std::endl;
return nullptr;
}
// Get the current function
llvm::Function* function = context.builder.GetInsertBlock()->getParent();
if (!function) {
std::cerr << "Error: Null function in return statement" << std::endl;
return nullptr;
}
// Check if the function return type matches the return value type
llvm::Type* funcRetType = function->getReturnType();
llvm::Type* valType = retVal->getType();
// If the function is declared as void but we're returning a value, change the function type
if (funcRetType->isVoidTy() && !valType->isVoidTy()) {
// This is a bit complex and would require modifying the function signature
// For simplicity, we'll just convert the return value to match the function type
debugOutput("Warning: Returning a value from a void function");
context.builder.CreateRetVoid();
return retVal;
}
// If the types don't match, try to convert
if (funcRetType != valType) {
if (funcRetType->isIntegerTy() && valType->isIntegerTy()) {
// Convert between integer types
retVal = context.builder.CreateIntCast(retVal, funcRetType, true, "cast_ret");
} else {
std::cerr << "Error: Return value type doesn't match function return type" << std::endl;
return nullptr;
}
}
// Create the return instruction
context.builder.CreateRet(retVal);
return retVal;
}
// Implementation for FunctionDef with parameters
llvm::Value* FunctionDef::codegen(CodeGenContext& context) {
debugOutput("Generating code for function: " + name);
if (!body) {
std::cerr << "Error: Null body in function definition" << std::endl;
return nullptr;
}
// Check if the function contains a return statement to determine return type
bool hasReturnStmt = false;
llvm::Type* returnType = llvm::Type::getVoidTy(context.context);
// Scan the function body for return statements
for (auto stmt : *body) {
if (auto retStmt = dynamic_cast<ReturnStmt*>(stmt)) {
hasReturnStmt = true;
// For simplicity, we'll assume all functions return int32 if they have a return statement
returnType = llvm::Type::getInt32Ty(context.context);
break;
}
}
// Create function type with parameters
std::vector<llvm::Type*> argTypes(params.size(), llvm::Type::getInt32Ty(context.context));
llvm::FunctionType* funcType = llvm::FunctionType::get(returnType, argTypes, false);
// Create the function
llvm::Function* function = llvm::Function::Create(
funcType, llvm::Function::ExternalLinkage, name, context.module.get());
if (!function) {
std::cerr << "Error: Failed to create function: " << name << std::endl;
return nullptr;
}
// Set names for all arguments
unsigned idx = 0;
for (auto &arg : function->args()) {
if (idx < params.size()) {
arg.setName(params[idx++]);
}
}
// Add the function to our function table before generating body
// This allows for recursive calls
context.functions[name] = function;
// Create a basic block for the function entry
llvm::BasicBlock* entryBB = llvm::BasicBlock::Create(context.context, "entry", function);
// Save the current insertion point
llvm::BasicBlock* savedBlock = context.builder.GetInsertBlock();
llvm::Function* savedFunction = savedBlock ? savedBlock->getParent() : nullptr;
// Set insertion point to the new function's entry block
context.builder.SetInsertPoint(entryBB);
debugOutput("Setting insertion point to entry block of function: " + name);
// Save the current named values
std::map<std::string, llvm::AllocaInst*> oldNamedValues = context.namedValues;
context.namedValues.clear(); // Clear the named values for the new function scope
// Create allocas for all parameters
idx = 0;
for (auto &arg : function->args()) {
// Create an alloca for this argument
llvm::AllocaInst* alloca = context.createEntryBlockAlloca(
function, arg.getName().str(), arg.getType());
// Store the initial value into the alloca
context.builder.CreateStore(&arg, alloca);
// Add arguments to variable symbol table
context.namedValues[arg.getName().str()] = alloca;
}
// Generate code for the function body
for (auto stmt : *body) {
if (stmt) {
stmt->codegen(context);
// If we just generated a return statement, don't continue generating code
if (dynamic_cast<ReturnStmt*>(stmt)) {
break;
}
}
}
// Ensure the function has a terminator
if (!context.builder.GetInsertBlock()->getTerminator()) {
if (returnType->isVoidTy()) {
context.builder.CreateRetVoid();
} else {
// Default return value for non-void functions
context.builder.CreateRet(llvm::ConstantInt::get(returnType, 0));
}
}
// Verify the function
std::string verifyErrors;
llvm::raw_string_ostream errStream(verifyErrors);
bool hasErrors = llvm::verifyFunction(*function, &errStream);
if (hasErrors) {
std::cerr << "Function verification failed for " << name << ":" << std::endl;
std::cerr << verifyErrors << std::endl;
function->eraseFromParent();
return nullptr;
}
// Restore the previous named values
context.namedValues = oldNamedValues;
// Restore the previous insertion point
if (savedBlock) {
context.builder.SetInsertPoint(savedBlock);
}
return function;
}
// Updated FunctionCall implementation to handle arguments
llvm::Value* FunctionCall::codegen(CodeGenContext& context) {
// Look up the function in the function table
auto it = context.functions.find(name);
if (it == context.functions.end() || !it->second) {
std::cerr << "Unknown function: " << name << std::endl;
return nullptr;
}
llvm::Function* function = it->second;
if (!function) {
std::cerr << "Error: Null function pointer for: " << name << std::endl;
return nullptr;
}
// Check argument count
if (function->arg_size() != (args ? args->size() : 0)) {
std::cerr << "Error: Function " << name << " called with wrong number of arguments. ";
std::cerr << "Expected " << function->arg_size() << ", got " << (args ? args->size() : 0) << std::endl;
return nullptr;
}
// Process arguments if present
std::vector<llvm::Value*> argValues;
if (args) {
for (auto arg : *args) {
if (arg) {
llvm::Value* argValue = arg->codegen(context);
if (argValue) {
argValues.push_back(argValue);
} else {
std::cerr << "Error: Failed to generate code for function argument" << std::endl;
return nullptr;
}
}
}
}
// Create the function call
llvm::Value* callResult = context.builder.CreateCall(function, argValues);
// If the function returns void, return a dummy value
if (function->getReturnType()->isVoidTy()) {
return llvm::Constant::getNullValue(llvm::Type::getInt32Ty(context.context));
}
return callResult;
}
static void finalizeFunction(llvm::Function *F) {
if (F->isDeclaration()) return; // skip external declarations
// A single IRBuilder we can reuse for all blocks
llvm::IRBuilder<> Builder(F->getContext());
for (llvm::BasicBlock &BB : *F) {
// Check if the block has a terminator
if (!BB.getTerminator()) {
Builder.SetInsertPoint(&BB);
// Add appropriate terminator based on function return type
if (F->getReturnType()->isVoidTy()) {
Builder.CreateRetVoid();
} else {
Builder.CreateRet(llvm::ConstantInt::get(
llvm::Type::getInt32Ty(F->getContext()), 0));
}
}
}
}
llvm::Value* Program::codegen(CodeGenContext& context) {
debugOutput("Generating code for main program");
// Create the main function
std::vector<llvm::Type*> argTypes;
llvm::FunctionType* mainFuncType = llvm::FunctionType::get(
llvm::Type::getInt32Ty(context.context), argTypes, false);
llvm::Function* mainFunc = llvm::Function::Create(
mainFuncType, llvm::Function::ExternalLinkage, "main", context.module.get());
if (!mainFunc) {
std::cerr << "Error: Failed to create main function" << std::endl;
return nullptr;
}
// Create a basic block for the entry point
llvm::BasicBlock* entryBB = llvm::BasicBlock::Create(context.context, "entry", mainFunc);
context.builder.SetInsertPoint(entryBB);
debugOutput("Setting insertion point to entry block of main function");
// First, process all function definitions to make them available for calls
if (statements) {
for (auto stmt : *statements) {
if (auto funcDef = dynamic_cast<FunctionDef*>(stmt)) {
funcDef->codegen(context);
}
}
}
// Make sure we're still in the main function's entry block
context.builder.SetInsertPoint(entryBB);
// Then process all non-function-definition statements
if (statements) {
for (auto stmt : *statements) {
if (!dynamic_cast<FunctionDef*>(stmt)) {
stmt->codegen(context);
// If we just generated a return statement, don't continue generating code
if (dynamic_cast<ReturnStmt*>(stmt) && !context.builder.GetInsertBlock()->getTerminator()) {
break;
}
}
}
}
// Add a return 0 to the main function if it doesn't already have a terminator
if (!context.builder.GetInsertBlock()->getTerminator()) {
context.builder.CreateRet(llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.context), 0));
}
return mainFunc;
}
// Generate code for the entire program
void CodeGenContext::generateCode(Program* program) {
if (!program) {
std::cerr << "Error: Null program in generateCode" << std::endl;
return;
}
std::cout << "Starting code generation..." << std::endl;
llvm::Value* result = program->codegen(*this);
std::cout << "Code generation " << (result ? "successful" : "failed") << std::endl;
// Verify the entire module
std::string verifyErrors;
llvm::raw_string_ostream errStream(verifyErrors);
bool hasErrors = llvm::verifyModule(*module, &errStream);
if (hasErrors) {
std::cerr << "Module verification failed:" << std::endl;
std::cerr << verifyErrors << std::endl;
} else {
debugOutput("Module verified successfully");
}
}
// Print the generated IR
void CodeGenContext::printIR() {
if (!module) {
std::cerr << "Error: No module to print" << std::endl;
return;
}
std::cout << "Printing generated LLVM IR:" << std::endl;
module->print(llvm::outs(), nullptr);
}
// Write the generated IR to a file
void CodeGenContext::writeIR(const std::string& filename) {
std::error_code EC;
llvm::raw_fd_ostream dest(filename, EC, llvm::sys::fs::OF_None);
if (EC) {
std::cerr << "Could not open file: " << EC.message() << std::endl;
return;
}
module->print(dest, nullptr);
}
// Run optimization passes on the generated code
void CodeGenContext::optimize() {
llvm::LoopAnalysisManager LAM;