From 943ed04b775949e8bc4948bcb8d762a32ab14f76 Mon Sep 17 00:00:00 2001 From: ov-4 Date: Thu, 29 Jan 2026 14:24:05 +0000 Subject: Added array --- lib/CodeGen/CodeGen.cc | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) (limited to 'lib/CodeGen/CodeGen.cc') diff --git a/lib/CodeGen/CodeGen.cc b/lib/CodeGen/CodeGen.cc index 31d113a..57d76eb 100644 --- a/lib/CodeGen/CodeGen.cc +++ b/lib/CodeGen/CodeGen.cc @@ -1,15 +1,20 @@ #include "cps/CodeGen.h" +#include "cps/ArrayHandler.h" #include "llvm/IR/Verifier.h" #include "cps/Lexer.h" using namespace llvm; using namespace cps; +CodeGen::~CodeGen() = default; + CodeGen::CodeGen() { TheContext = std::make_unique(); TheModule = std::make_unique("cps_module", *TheContext); Builder = std::make_unique>(*TheContext); + Arrays = std::make_unique(*TheContext, *Builder, *TheModule, NamedValues); + SetupExternalFunctions(); } @@ -24,6 +29,8 @@ void CodeGen::SetupExternalFunctions() { PrintfFormatStr = Builder->CreateGlobalStringPtr("%d\n", "fmt_nl", 0, TheModule.get()); ScanfFormatStr = Builder->CreateGlobalStringPtr("%d", "fmt_in", 0, TheModule.get()); + + Arrays->setupExternalFunctions(); } AllocaInst *CodeGen::CreateEntryBlockAlloca(Function *TheFunction, const std::string &VarName) { @@ -64,8 +71,14 @@ Value *CodeGen::emitExpr(ExprAST *Expr) { fprintf(stderr, "Error: Unknown variable name %s\n", Var->getName().c_str()); return nullptr; } + return Builder->CreateLoad(Type::getInt32Ty(*TheContext), A, Var->getName().c_str()); } + + + if (auto *ArrAcc = dynamic_cast(Expr)) { + return Arrays->emitArrayAccess(ArrAcc, *this); + } if (auto *Bin = dynamic_cast(Expr)) { Value *L = emitExpr(Bin->getLHS()); @@ -234,6 +247,16 @@ void CodeGen::emitForStmt(ForStmtAST *Stmt) { void CodeGen::emitStmt(StmtAST *Stmt) { if (!Stmt) return; + if (auto *ArrDecl = dynamic_cast(Stmt)) { + Arrays->emitArrayDeclare(ArrDecl, *this); + return; + } + + if (auto *ArrAssign = dynamic_cast(Stmt)) { + Arrays->emitArrayAssign(ArrAssign, *this); + return; + } + if (auto *Decl = dynamic_cast(Stmt)) { Function *TheFunction = Builder->GetInsertBlock()->getParent(); AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Decl->getName()); @@ -261,12 +284,16 @@ void CodeGen::emitStmt(StmtAST *Stmt) { } } else if (auto *Out = dynamic_cast(Stmt)) { - Value *Val = emitExpr(Out->getExpr()); - if (Val) { - std::vector Args; - Args.push_back(PrintfFormatStr); - Args.push_back(Val); - Builder->CreateCall(PrintfFunc, Args); + bool handled = Arrays->tryEmitArrayOutput(Out->getExpr(), *this, PrintfFunc, PrintfFormatStr); + + if (!handled) { + Value *Val = emitExpr(Out->getExpr()); + if (Val) { + std::vector Args; + Args.push_back(PrintfFormatStr); + Args.push_back(Val); + Builder->CreateCall(PrintfFunc, Args); + } } } else if (auto *IfStmt = dynamic_cast(Stmt)) { -- cgit v1.3.1-4-g156e