From 18366d3cc8fab7b022ae4149cd190940f4724183 Mon Sep 17 00:00:00 2001 From: Ethereal <18783417278@163.com> Date: Mon, 23 Mar 2026 15:40:10 +0800 Subject: [PATCH 01/11] =?UTF-8?q?=E5=88=86=E6=94=AF=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/antlr4/SysY.g4 | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/antlr4/SysY.g4 b/src/antlr4/SysY.g4 index 263aeef..c8f4794 100644 --- a/src/antlr4/SysY.g4 +++ b/src/antlr4/SysY.g4 @@ -1,3 +1,13 @@ +// SysY 完整语法文法 +// 支持完整的 SysY 语言子集,包括: +// - int/float/void 类型 +// - 全局/局部变量和常量声明 +// - 数组声明和初始化(一维和多维) +// - 函数定义和调用 +// - if-else, while, break, continue +// - 各种运算符(算术、关系、逻辑、一元) +// - 库函数调用 + // SysY 子集语法:支持形如 // int main() { int a = 1; int b = 2; return a + b; } // 的最小返回表达式编译。 From 3e4165c4bb8c65f7b4bc7b5b5722db822ee788ed Mon Sep 17 00:00:00 2001 From: Oliveira <1350121858@qq.com> Date: Mon, 23 Mar 2026 15:59:28 +0800 Subject: [PATCH 02/11] =?UTF-8?q?feat(grammar):=20=E5=AE=8C=E5=96=84=20Sys?= =?UTF-8?q?Y.g4=20=E8=AF=AD=E6=B3=95=E5=AE=9A=E4=B9=89=E6=94=AF=E6=8C=81?= =?UTF-8?q?=20Lab1=20=E8=A6=81=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 扩展 SysY 语法定义以支持更多合法程序 - 完善词法和语法规则,增强解析能力 - 确保符合 SysY 语言规范 --- src/antlr4/SysY.g4 | 138 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 112 insertions(+), 26 deletions(-) diff --git a/src/antlr4/SysY.g4 b/src/antlr4/SysY.g4 index 263aeef..487fc1e 100644 --- a/src/antlr4/SysY.g4 +++ b/src/antlr4/SysY.g4 @@ -1,31 +1,61 @@ -// SysY 子集语法:支持形如 -// int main() { int a = 1; int b = 2; return a + b; } -// 的最小返回表达式编译。 - -// 后续需要自行添加 - grammar SysY; /*===-------------------------------------------===*/ /* Lexer rules */ /*===-------------------------------------------===*/ +CONST: 'const'; INT: 'int'; +FLOAT: 'float'; +VOID: 'void'; +IF: 'if'; +ELSE: 'else'; +WHILE: 'while'; +BREAK: 'break'; +CONTINUE: 'continue'; RETURN: 'return'; ASSIGN: '='; ADD: '+'; +SUB: '-'; +MUL: '*'; +DIV: '/'; +MOD: '%'; +EQ: '=='; +NEQ: '!='; +LT: '<'; +GT: '>'; +LE: '<='; +GE: '>='; +NOT: '!'; +AND: '&&'; +OR: '||'; LPAREN: '('; RPAREN: ')'; +LBRACK: '['; +RBRACK: ']'; LBRACE: '{'; RBRACE: '}'; +COMMA: ','; SEMICOLON: ';'; ID: [a-zA-Z_][a-zA-Z_0-9]*; -ILITERAL: [0-9]+; -WS: [ \t\r\n] -> skip; +ILITERAL + : '0' | [1-9][0-9]* // Decimal + | '0' [0-7]+ // Octal + | ('0x' | '0X') [0-9a-fA-F]+ // Hex + ; + +FLITERAL + : ([0-9]* '.' [0-9]+ | [0-9]+ '.') ([eE] [+-]? [0-9]+)? + | [0-9]+ [eE] [+-]? [0-9]+ + | ('0x'|'0X') ([0-9a-fA-F]* '.' [0-9a-fA-F]+ | [0-9a-fA-F]+ '.') ([pP] [+-]? [0-9]+)? + | ('0x'|'0X') [0-9a-fA-F]+ [pP] [+-]? [0-9]+ + ; + +WS: [ \t\r\n]+ -> skip; LINECOMMENT: '//' ~[\r\n]* -> skip; BLOCKCOMMENT: '/*' .*? '*/' -> skip; @@ -34,31 +64,62 @@ BLOCKCOMMENT: '/*' .*? '*/' -> skip; /*===-------------------------------------------===*/ compUnit - : funcDef EOF + : (decl | funcDef)+ EOF ; decl - : btype varDef SEMICOLON + : constDecl + | varDecl + ; + +constDecl + : CONST btype constDef (COMMA constDef)* SEMICOLON ; btype : INT + | FLOAT + ; + +constDef + : ID (LBRACK constExp RBRACK)* ASSIGN constInitVal + ; + +constInitVal + : constExp + | LBRACE (constInitVal (COMMA constInitVal)*)? RBRACE + ; + +varDecl + : btype varDef (COMMA varDef)* SEMICOLON ; varDef - : lValue (ASSIGN initValue)? + : ID (LBRACK constExp RBRACK)* + | ID (LBRACK constExp RBRACK)* ASSIGN initValue ; initValue : exp + | LBRACE (initValue (COMMA initValue)*)? RBRACE ; funcDef - : funcType ID LPAREN RPAREN blockStmt + : funcType ID LPAREN funcFParams? RPAREN blockStmt ; funcType - : INT + : VOID + | INT + | FLOAT + ; + +funcFParams + : funcFParam (COMMA funcFParam)* + ; + +funcFParam + : btype ID (LBRACK RBRACK (LBRACK exp RBRACK)*)? ; blockStmt @@ -71,28 +132,53 @@ blockItem ; stmt - : returnStmt - ; - -returnStmt - : RETURN exp SEMICOLON + : lValue ASSIGN exp SEMICOLON # assignStmt + | exp? SEMICOLON # exprStmt + | blockStmt # blockStmtStmt + | IF LPAREN cond RPAREN stmt (ELSE stmt)? # ifStmt + | WHILE LPAREN cond RPAREN stmt # whileStmt + | BREAK SEMICOLON # breakStmt + | CONTINUE SEMICOLON # continueStmt + | RETURN exp? SEMICOLON # returnStmt ; exp - : LPAREN exp RPAREN # parenExp - | var # varExp - | number # numberExp - | exp ADD exp # additiveExp + : LPAREN exp RPAREN # parenExp + | lValue # lvalExp + | number # numberExp + | ID LPAREN funcRParams? RPAREN # callExp + | unaryOp exp # unaryExp + | exp (MUL | DIV | MOD) exp # mulExp + | exp (ADD | SUB) exp # addExp + | exp (LT | GT | LE | GE) exp # relExp + | exp (EQ | NEQ) exp # eqExp + | exp AND exp # lAndExp + | exp OR exp # lOrExp ; -var - : ID +cond + : exp ; lValue - : ID + : ID (LBRACK exp RBRACK)* ; number - : ILITERAL + : ILITERAL # intConst + | FLITERAL # floatConst + ; + +unaryOp + : ADD + | SUB + | NOT + ; + +funcRParams + : exp (COMMA exp)* + ; + +constExp + : exp ; From a85898b35ad06ed4680584f77a94a6d9698d050e Mon Sep 17 00:00:00 2001 From: lc <18783417278@163.com> Date: Mon, 30 Mar 2026 19:15:50 +0800 Subject: [PATCH 03/11] =?UTF-8?q?lab2=20IRGen=E9=83=A8=E5=88=86=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/lab2剩余任务分工.md | 21 +++++++++++++++++++++ include/ir/IR.h | 3 ++- src/ir/IRBuilder.cpp | 8 ++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 doc/lab2剩余任务分工.md diff --git a/doc/lab2剩余任务分工.md b/doc/lab2剩余任务分工.md new file mode 100644 index 0000000..9ba8abb --- /dev/null +++ b/doc/lab2剩余任务分工.md @@ -0,0 +1,21 @@ +### 人员 1:基础表达式与赋值支持(lc) + +- 任务 1.1:支持更多二元运算符(Sub, Mul, Div, Mod) +- 任务 1.2:支持一元运算符(正负号) +- 任务 1.3:支持赋值表达式 +- 任务 1.4:支持逗号分隔的多个变量声明 + +### 人员 2:控制流支持 + +- 任务 2.1:支持 if-else 条件语句 +- 任务 2.2:支持 while 循环语句 +- 任务 2.3:支持 break/continue 语句 +- 任务 2.4:支持比较和逻辑表达式 + +### 人员 3:函数与全局变量支持 + +- 任务 3.1:支持全局变量声明与初始化 +- 任务 3.2:支持函数参数处理 +- 任务 3.3:支持函数调用生成 +- 任务 3.4:支持 const 常量声明 + diff --git a/include/ir/IR.h b/include/ir/IR.h index b961192..a1a3329 100644 --- a/include/ir/IR.h +++ b/include/ir/IR.h @@ -152,7 +152,8 @@ class ConstantInt : public ConstantValue { }; // 后续还需要扩展更多指令类型。 -enum class Opcode { Add, Sub, Mul, Alloca, Load, Store, Ret }; +// enum class Opcode { Add, Sub, Mul, Alloca, Load, Store, Ret }; +enum class Opcode { Add, Sub, Mul, Div, Mod, Alloca, Load, Store, Ret }; // User 是所有“会使用其他 Value 作为输入”的 IR 对象的抽象基类。 // 当前实现中只有 Instruction 继承自 User。 diff --git a/src/ir/IRBuilder.cpp b/src/ir/IRBuilder.cpp index 90f03c4..37861c8 100644 --- a/src/ir/IRBuilder.cpp +++ b/src/ir/IRBuilder.cpp @@ -86,4 +86,12 @@ ReturnInst* IRBuilder::CreateRet(Value* v) { return insert_block_->Append(Type::GetVoidType(), v); } +BinaryInst* IRBuilder::CreateSub(Value* lhs, Value* rhs, const std::string& name) { + return CreateBinary(Opcode::Sub, lhs, rhs, name); +} + +BinaryInst* IRBuilder::CreateMul(Value* lhs, Value* rhs, const std::string& name) { + return CreateBinary(Opcode::Mul, lhs, rhs, name); +} + } // namespace ir From 83b6f17c7899e6a2d80e59e0d5dd4bf6c2059c3e Mon Sep 17 00:00:00 2001 From: lc <18783417278@163.com> Date: Mon, 30 Mar 2026 19:21:33 +0800 Subject: [PATCH 04/11] =?UTF-8?q?lab2=20IRGen=E9=83=A8=E5=88=86=E5=AE=9E?= =?UTF-8?q?=E7=8E=B02?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/irgen/IRGenExp.cpp | 48 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/src/irgen/IRGenExp.cpp b/src/irgen/IRGenExp.cpp index cf4797c..f20609e 100644 --- a/src/irgen/IRGenExp.cpp +++ b/src/irgen/IRGenExp.cpp @@ -70,11 +70,53 @@ std::any IRGenImpl::visitVarExp(SysYParser::VarExpContext* ctx) { std::any IRGenImpl::visitAdditiveExp(SysYParser::AdditiveExpContext* ctx) { if (!ctx || !ctx->exp(0) || !ctx->exp(1)) { - throw std::runtime_error(FormatError("irgen", "非法加法表达式")); + throw std::runtime_error(FormatError("irgen", "非法加减法表达式")); } ir::Value* lhs = EvalExpr(*ctx->exp(0)); ir::Value* rhs = EvalExpr(*ctx->exp(1)); + + ir::Opcode op = ir::Opcode::Add; + if (ctx->ADD()) { + op = ir::Opcode::Add; + } else if (ctx->SUB()) { + op = ir::Opcode::Sub; + } else { + throw std::runtime_error(FormatError("irgen", "未知的加减运算符")); + } + return static_cast( - builder_.CreateBinary(ir::Opcode::Add, lhs, rhs, - module_.GetContext().NextTemp())); + builder_.CreateBinary(op, lhs, rhs, module_.GetContext().NextTemp())); } + +std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) { + if (!ctx) { + throw std::runtime_error(FormatError("irgen", "非法乘除法表达式")); + } + + // 如果是 unaryExp 直接返回 + if (ctx->unaryExp()) { + return ctx->unaryExp()->accept(this); + } + + // 处理 MulExp op unaryExp 的递归形式 + if (!ctx->exp(0) || !ctx->unaryExp(0)) { + throw std::runtime_error(FormatError("irgen", "非法乘除法表达式结构")); + } + + ir::Value* lhs = std::any_cast(ctx->exp(0)->accept(this)); + ir::Value* rhs = std::any_cast(ctx->unaryExp(0)->accept(this)); + + ir::Opcode op = ir::Opcode::Mul; + if (ctx->MUL()) { + op = ir::Opcode::Mul; + } else if (ctx->DIV()) { + op = ir::Opcode::Div; + } else if (ctx->MOD()) { + op = ir::Opcode::Mod; + } else { + throw std::runtime_error(FormatError("irgen", "未知的乘除运算符")); + } + + return static_cast( + builder_.CreateBinary(op, lhs, rhs, module_.GetContext().NextTemp())); +} \ No newline at end of file From 02e5a7d4e7e3f32826515bac1d24fd1bfc9e36b5 Mon Sep 17 00:00:00 2001 From: Oliveira <1350121858@qq.com> Date: Mon, 30 Mar 2026 20:10:45 +0800 Subject: [PATCH 05/11] merge error --- src/antlr4/SysY.g4 | 171 ++++++++++++++++++++++++++++----------------- 1 file changed, 106 insertions(+), 65 deletions(-) diff --git a/src/antlr4/SysY.g4 b/src/antlr4/SysY.g4 index 4c5d788..262f07a 100644 --- a/src/antlr4/SysY.g4 +++ b/src/antlr4/SysY.g4 @@ -47,48 +47,44 @@ MUL: '*'; DIV: '/'; MOD: '%'; NOT: '!'; -SUB: '-'; -MUL: '*'; -DIV: '/'; -MOD: '%'; -EQ: '=='; -NEQ: '!='; -LT: '<'; -GT: '>'; -LE: '<='; -GE: '>='; -NOT: '!'; -AND: '&&'; -OR: '||'; LPAREN: '('; RPAREN: ')'; LBRACK: '['; RBRACK: ']'; -LBRACK: '['; -RBRACK: ']'; LBRACE: '{'; RBRACE: '}'; COMMA: ','; -COMMA: ','; SEMICOLON: ';'; ID: [a-zA-Z_][a-zA-Z_0-9]*; -ILITERAL - : '0' | [1-9][0-9]* // Decimal - | '0' [0-7]+ // Octal - | ('0x' | '0X') [0-9a-fA-F]+ // Hex +HEX_FLOAT_LITERAL + : ('0x' | '0X') HEX_DIGIT* '.' HEX_DIGIT+ BINARY_EXPONENT + | ('0x' | '0X') HEX_DIGIT+ '.' HEX_DIGIT* BINARY_EXPONENT + | ('0x' | '0X') HEX_DIGIT+ BINARY_EXPONENT + ; + +DEC_FLOAT_LITERAL + : DEC_DIGIT+ '.' DEC_DIGIT* DEC_EXPONENT? + | '.' DEC_DIGIT+ DEC_EXPONENT? + | DEC_DIGIT+ DEC_EXPONENT + ; + +HEX_INT_LITERAL + : ('0x' | '0X') HEX_DIGIT+ + ; + +OCT_INT_LITERAL + : '0' OCT_DIGIT+ ; -FLITERAL - : ([0-9]* '.' [0-9]+ | [0-9]+ '.') ([eE] [+-]? [0-9]+)? - | [0-9]+ [eE] [+-]? [0-9]+ - | ('0x'|'0X') ([0-9a-fA-F]* '.' [0-9a-fA-F]+ | [0-9a-fA-F]+ '.') ([pP] [+-]? [0-9]+)? - | ('0x'|'0X') [0-9a-fA-F]+ [pP] [+-]? [0-9]+ +DEC_INT_LITERAL + : '0' + | [1-9] DEC_DIGIT* ; -WS: [ \t\r\n]+ -> skip; +WS: [ \t\r\n] -> skip; LINECOMMENT: '//' ~[\r\n]* -> skip; BLOCKCOMMENT: '/*' .*? '*/' -> skip; @@ -130,16 +126,7 @@ bType ; constDef - : ID (LBRACK constExp RBRACK)* ASSIGN constInitVal - ; - -constInitVal - : constExp - | LBRACE (constInitVal (COMMA constInitVal)*)? RBRACE - ; - -varDecl - : btype varDef (COMMA varDef)* SEMICOLON + : ID constIndex* ASSIGN constInitVal ; varDef @@ -157,11 +144,11 @@ constInitVal initVal : exp - | LBRACE (initValue (COMMA initValue)*)? RBRACE + | LBRACE (initVal (COMMA initVal)*)? RBRACE ; funcDef - : funcType ID LPAREN funcFParams? RPAREN blockStmt + : funcType ID LPAREN funcFParams? RPAREN block ; funcType @@ -175,7 +162,7 @@ funcFParams ; funcFParam - : btype ID (LBRACK RBRACK (LBRACK exp RBRACK)*)? + : bType ID (LBRACK RBRACK (LBRACK exp RBRACK)*)? ; block @@ -188,53 +175,107 @@ blockItem ; stmt - : lValue ASSIGN exp SEMICOLON # assignStmt - | exp? SEMICOLON # exprStmt - | blockStmt # blockStmtStmt - | IF LPAREN cond RPAREN stmt (ELSE stmt)? # ifStmt - | WHILE LPAREN cond RPAREN stmt # whileStmt - | BREAK SEMICOLON # breakStmt - | CONTINUE SEMICOLON # continueStmt - | RETURN exp? SEMICOLON # returnStmt + : lVal ASSIGN exp SEMICOLON + | exp? SEMICOLON + | block + | IF LPAREN cond RPAREN stmt (ELSE stmt)? + | WHILE LPAREN cond RPAREN stmt + | BREAK SEMICOLON + | CONTINUE SEMICOLON + | RETURN exp? SEMICOLON ; exp - : LPAREN exp RPAREN # parenExp - | lValue # lvalExp - | number # numberExp - | ID LPAREN funcRParams? RPAREN # callExp - | unaryOp exp # unaryExp - | exp (MUL | DIV | MOD) exp # mulExp - | exp (ADD | SUB) exp # addExp - | exp (LT | GT | LE | GE) exp # relExp - | exp (EQ | NEQ) exp # eqExp - | exp AND exp # lAndExp - | exp OR exp # lOrExp + : addExp ; cond - : exp + : lOrExp ; -lValue +lVal : ID (LBRACK exp RBRACK)* ; +primaryExp + : LPAREN exp RPAREN + | lVal + | number + ; + number - : ILITERAL # intConst - | FLITERAL # floatConst + : intConst + | floatConst + ; + +intConst + : DEC_INT_LITERAL + | OCT_INT_LITERAL + | HEX_INT_LITERAL ; -unaryOp +floatConst + : DEC_FLOAT_LITERAL + | HEX_FLOAT_LITERAL + ; + +unaryExp + : primaryExp + | ID LPAREN funcRParams? RPAREN + | addUnaryOp unaryExp + ; + +addUnaryOp : ADD | SUB - | NOT ; funcRParams : exp (COMMA exp)* ; +mulExp + : unaryExp + | mulExp MUL unaryExp + | mulExp DIV unaryExp + | mulExp MOD unaryExp + ; + +addExp + : mulExp + | addExp ADD mulExp + | addExp SUB mulExp + ; + +relExp + : addExp + | relExp LT addExp + | relExp GT addExp + | relExp LE addExp + | relExp GE addExp + ; + +eqExp + : relExp + | eqExp EQ relExp + | eqExp NE relExp + ; + +lAndExp + : condUnaryExp + | lAndExp AND condUnaryExp + ; + +lOrExp + : lAndExp + | lOrExp OR lAndExp + ; + +condUnaryExp + : eqExp + | NOT condUnaryExp + ; + constExp - : exp + : addExp ; From fe3a3410a65011e8668cf422f9b017b6d63ebb13 Mon Sep 17 00:00:00 2001 From: lc <18783417278@163.com> Date: Mon, 30 Mar 2026 20:19:54 +0800 Subject: [PATCH 06/11] =?UTF-8?q?=E2=80=9CIRGen=E9=83=A8=E5=88=86=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=EF=BC=9A=E6=94=AF=E6=8C=81=E6=9B=B4=E5=A4=9A=E4=BA=8C?= =?UTF-8?q?=E5=85=83=E8=BF=90=E7=AE=97=E7=AC=A6=EF=BC=88Sub,=20Mul,=20Div,?= =?UTF-8?q?=20Mod=EF=BC=89=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/ir/IR.h | 2 + include/irgen/IRGen.h | 16 ++++---- src/ir/IRPrinter.cpp | 8 +++- src/ir/Instruction.cpp | 5 ++- src/irgen/IRGenDecl.cpp | 47 +++++++++++---------- src/irgen/IRGenExp.cpp | 90 ++++++++++++++++++++++++++++++----------- src/irgen/IRGenFunc.cpp | 20 ++++----- src/irgen/IRGenStmt.cpp | 23 ++++------- src/sem/Sema.cpp | 10 +++-- 9 files changed, 136 insertions(+), 85 deletions(-) diff --git a/include/ir/IR.h b/include/ir/IR.h index a1a3329..ed38827 100644 --- a/include/ir/IR.h +++ b/include/ir/IR.h @@ -301,6 +301,8 @@ class IRBuilder { BinaryInst* CreateBinary(Opcode op, Value* lhs, Value* rhs, const std::string& name); BinaryInst* CreateAdd(Value* lhs, Value* rhs, const std::string& name); + BinaryInst* CreateSub(Value* lhs, Value* rhs, const std::string& name); + BinaryInst* CreateMul(Value* lhs, Value* rhs, const std::string& name); AllocaInst* CreateAllocaI32(const std::string& name); LoadInst* CreateLoad(Value* ptr, const std::string& name); StoreInst* CreateStore(Value* val, Value* ptr); diff --git a/include/irgen/IRGen.h b/include/irgen/IRGen.h index 231ba90..24d0b3b 100644 --- a/include/irgen/IRGen.h +++ b/include/irgen/IRGen.h @@ -26,16 +26,16 @@ class IRGenImpl final : public SysYBaseVisitor { std::any visitCompUnit(SysYParser::CompUnitContext* ctx) override; std::any visitFuncDef(SysYParser::FuncDefContext* ctx) override; - std::any visitBlockStmt(SysYParser::BlockStmtContext* ctx) override; + std::any visitBlock(SysYParser::BlockContext* ctx) override; std::any visitBlockItem(SysYParser::BlockItemContext* ctx) override; std::any visitDecl(SysYParser::DeclContext* ctx) override; std::any visitStmt(SysYParser::StmtContext* ctx) override; std::any visitVarDef(SysYParser::VarDefContext* ctx) override; - std::any visitReturnStmt(SysYParser::ReturnStmtContext* ctx) override; - std::any visitParenExp(SysYParser::ParenExpContext* ctx) override; - std::any visitNumberExp(SysYParser::NumberExpContext* ctx) override; - std::any visitVarExp(SysYParser::VarExpContext* ctx) override; - std::any visitAdditiveExp(SysYParser::AdditiveExpContext* ctx) override; + std::any visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) override; + std::any visitNumber(SysYParser::NumberContext* ctx) override; + std::any visitLVal(SysYParser::LValContext* ctx) override; + std::any visitAddExp(SysYParser::AddExpContext* ctx) override; + std::any visitMulExp(SysYParser::MulExpContext* ctx) override; private: enum class BlockFlow { @@ -50,8 +50,8 @@ class IRGenImpl final : public SysYBaseVisitor { const SemanticContext& sema_; ir::Function* func_; ir::IRBuilder builder_; - // 名称绑定由 Sema 负责;IRGen 只维护“声明 -> 存储槽位”的代码生成状态。 - std::unordered_map storage_map_; + // 名称绑定由 Sema 负责;IRGen 只维护"变量名 -> 存储槽位"的代码生成状态。 + std::unordered_map storage_map_; }; std::unique_ptr GenerateIR(SysYParser::CompUnitContext& tree, diff --git a/src/ir/IRPrinter.cpp b/src/ir/IRPrinter.cpp index 30efbb6..6d7f486 100644 --- a/src/ir/IRPrinter.cpp +++ b/src/ir/IRPrinter.cpp @@ -32,6 +32,10 @@ static const char* OpcodeToString(Opcode op) { return "sub"; case Opcode::Mul: return "mul"; + case Opcode::Div: + return "sdiv"; + case Opcode::Mod: + return "srem"; case Opcode::Alloca: return "alloca"; case Opcode::Load: @@ -65,7 +69,9 @@ void IRPrinter::Print(const Module& module, std::ostream& os) { switch (inst->GetOpcode()) { case Opcode::Add: case Opcode::Sub: - case Opcode::Mul: { + case Opcode::Mul: + case Opcode::Div: + case Opcode::Mod: { auto* bin = static_cast(inst); os << " " << bin->GetName() << " = " << OpcodeToString(bin->GetOpcode()) << " " diff --git a/src/ir/Instruction.cpp b/src/ir/Instruction.cpp index 7928716..5abab19 100644 --- a/src/ir/Instruction.cpp +++ b/src/ir/Instruction.cpp @@ -61,8 +61,9 @@ void Instruction::SetParent(BasicBlock* parent) { parent_ = parent; } BinaryInst::BinaryInst(Opcode op, std::shared_ptr ty, Value* lhs, Value* rhs, std::string name) : Instruction(op, std::move(ty), std::move(name)) { - if (op != Opcode::Add) { - throw std::runtime_error(FormatError("ir", "BinaryInst 当前只支持 Add")); + if (op != Opcode::Add && op != Opcode::Sub && op != Opcode::Mul && + op != Opcode::Div && op != Opcode::Mod) { + throw std::runtime_error(FormatError("ir", "BinaryInst 不支持的操作码")); } if (!lhs || !rhs) { throw std::runtime_error(FormatError("ir", "BinaryInst 缺少操作数")); diff --git a/src/irgen/IRGenDecl.cpp b/src/irgen/IRGenDecl.cpp index 0eb62ae..df7ccf9 100644 --- a/src/irgen/IRGenDecl.cpp +++ b/src/irgen/IRGenDecl.cpp @@ -6,18 +6,7 @@ #include "ir/IR.h" #include "utils/Log.h" -namespace { - -std::string GetLValueName(SysYParser::LValueContext& lvalue) { - if (!lvalue.ID()) { - throw std::runtime_error(FormatError("irgen", "非法左值")); - } - return lvalue.ID()->getText(); -} - -} // namespace - -std::any IRGenImpl::visitBlockStmt(SysYParser::BlockStmtContext* ctx) { +std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少语句块")); } @@ -63,14 +52,20 @@ std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少变量声明")); } - if (!ctx->btype() || !ctx->btype()->INT()) { + // 当前语法中 decl 包含 constDecl 或 varDecl,这里只支持 varDecl + auto* var_decl = ctx->varDecl(); + if (!var_decl) { + throw std::runtime_error(FormatError("irgen", "当前仅支持变量声明")); + } + if (!var_decl->bType() || !var_decl->bType()->INT()) { throw std::runtime_error(FormatError("irgen", "当前仅支持局部 int 变量声明")); } - auto* var_def = ctx->varDef(); - if (!var_def) { - throw std::runtime_error(FormatError("irgen", "非法变量声明")); + // 遍历所有 varDef + for (auto* var_def : var_decl->varDef()) { + if (var_def) { + var_def->accept(this); + } } - var_def->accept(this); return {}; } @@ -83,22 +78,26 @@ std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少变量定义")); } - if (!ctx->lValue()) { + if (!ctx->ID()) { throw std::runtime_error(FormatError("irgen", "变量声明缺少名称")); } - GetLValueName(*ctx->lValue()); - if (storage_map_.find(ctx) != storage_map_.end()) { + // 暂不支持数组声明(constIndex) + if (!ctx->constIndex().empty()) { + throw std::runtime_error(FormatError("irgen", "暂不支持数组声明")); + } + std::string var_name = ctx->ID()->getText(); + if (storage_map_.find(var_name) != storage_map_.end()) { throw std::runtime_error(FormatError("irgen", "声明重复生成存储槽位")); } auto* slot = builder_.CreateAllocaI32(module_.GetContext().NextTemp()); - storage_map_[ctx] = slot; + storage_map_[var_name] = slot; ir::Value* init = nullptr; - if (auto* init_value = ctx->initValue()) { - if (!init_value->exp()) { + if (auto* init_val = ctx->initVal()) { + if (!init_val->exp()) { throw std::runtime_error(FormatError("irgen", "当前不支持聚合初始化")); } - init = EvalExpr(*init_value->exp()); + init = EvalExpr(*init_val->exp()); } else { init = builder_.CreateConstInt(0); } diff --git a/src/irgen/IRGenExp.cpp b/src/irgen/IRGenExp.cpp index f20609e..7b25d4a 100644 --- a/src/irgen/IRGenExp.cpp +++ b/src/irgen/IRGenExp.cpp @@ -25,20 +25,51 @@ ir::Value* IRGenImpl::EvalExpr(SysYParser::ExpContext& expr) { } -std::any IRGenImpl::visitParenExp(SysYParser::ParenExpContext* ctx) { - if (!ctx || !ctx->exp()) { - throw std::runtime_error(FormatError("irgen", "非法括号表达式")); +std::any IRGenImpl::visitPrimaryExp(SysYParser::PrimaryExpContext* ctx) { + if (!ctx) { + throw std::runtime_error(FormatError("irgen", "非法基本表达式")); + } + // 处理括号表达式:LPAREN exp RPAREN + if (ctx->exp()) { + return EvalExpr(*ctx->exp()); + } + // 处理 lVal(变量使用)- 交给 visitLVal 处理 + if (ctx->lVal()) { + // 直接在这里处理变量读取,避免 accept 调用可能导致的问题 + auto* lval_ctx = ctx->lVal(); + if (!lval_ctx || !lval_ctx->ID()) { + throw std::runtime_error(FormatError("irgen", "当前仅支持普通整型变量")); + } + const auto* decl = sema_.ResolveObjectUse(lval_ctx); + if (!decl) { + throw std::runtime_error( + FormatError("irgen", + "变量使用缺少语义绑定:" + lval_ctx->ID()->getText())); + } + std::string var_name = lval_ctx->ID()->getText(); + auto it = storage_map_.find(var_name); + if (it == storage_map_.end()) { + throw std::runtime_error( + FormatError("irgen", + "变量声明缺少存储槽位:" + var_name)); + } + return static_cast( + builder_.CreateLoad(it->second, module_.GetContext().NextTemp())); } - return EvalExpr(*ctx->exp()); + // 处理 number + if (ctx->number()) { + return ctx->number()->accept(this); + } + throw std::runtime_error(FormatError("irgen", "不支持的基本表达式类型")); } -std::any IRGenImpl::visitNumberExp(SysYParser::NumberExpContext* ctx) { - if (!ctx || !ctx->number() || !ctx->number()->ILITERAL()) { +std::any IRGenImpl::visitNumber(SysYParser::NumberContext* ctx) { + if (!ctx || !ctx->intConst()) { throw std::runtime_error(FormatError("irgen", "当前仅支持整数字面量")); } return static_cast( - builder_.CreateConstInt(std::stoi(ctx->number()->getText()))); + builder_.CreateConstInt(std::stoi(ctx->intConst()->getText()))); } // 变量使用的处理流程: @@ -47,33 +78,46 @@ std::any IRGenImpl::visitNumberExp(SysYParser::NumberExpContext* ctx) { // 3. 最后生成 load,把内存中的值读出来。 // // 因此当前 IRGen 自己不再做名字查找,而是直接消费 Sema 的绑定结果。 -std::any IRGenImpl::visitVarExp(SysYParser::VarExpContext* ctx) { - if (!ctx || !ctx->var() || !ctx->var()->ID()) { +std::any IRGenImpl::visitLVal(SysYParser::LValContext* ctx) { + if (!ctx || !ctx->ID()) { throw std::runtime_error(FormatError("irgen", "当前仅支持普通整型变量")); } - auto* decl = sema_.ResolveVarUse(ctx->var()); + const auto* decl = sema_.ResolveObjectUse(ctx); if (!decl) { throw std::runtime_error( FormatError("irgen", - "变量使用缺少语义绑定: " + ctx->var()->ID()->getText())); + "变量使用缺少语义绑定:" + ctx->ID()->getText())); } - auto it = storage_map_.find(decl); + // 使用变量名查找存储槽位 + std::string var_name = ctx->ID()->getText(); + auto it = storage_map_.find(var_name); if (it == storage_map_.end()) { throw std::runtime_error( FormatError("irgen", - "变量声明缺少存储槽位: " + ctx->var()->ID()->getText())); + "变量声明缺少存储槽位:" + var_name)); } return static_cast( builder_.CreateLoad(it->second, module_.GetContext().NextTemp())); } -std::any IRGenImpl::visitAdditiveExp(SysYParser::AdditiveExpContext* ctx) { - if (!ctx || !ctx->exp(0) || !ctx->exp(1)) { +std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) { + if (!ctx) { throw std::runtime_error(FormatError("irgen", "非法加减法表达式")); } - ir::Value* lhs = EvalExpr(*ctx->exp(0)); - ir::Value* rhs = EvalExpr(*ctx->exp(1)); + + // 如果是 mulExp 直接返回(addExp : mulExp) + if (ctx->mulExp() && ctx->addExp() == nullptr) { + return ctx->mulExp()->accept(this); + } + + // 处理 addExp op mulExp 的递归形式 + if (!ctx->addExp() || !ctx->mulExp()) { + throw std::runtime_error(FormatError("irgen", "非法加减法表达式结构")); + } + + ir::Value* lhs = std::any_cast(ctx->addExp()->accept(this)); + ir::Value* rhs = std::any_cast(ctx->mulExp()->accept(this)); ir::Opcode op = ir::Opcode::Add; if (ctx->ADD()) { @@ -93,18 +137,18 @@ std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) { throw std::runtime_error(FormatError("irgen", "非法乘除法表达式")); } - // 如果是 unaryExp 直接返回 - if (ctx->unaryExp()) { + // 如果是 unaryExp 直接返回(mulExp : unaryExp) + if (ctx->unaryExp() && ctx->mulExp() == nullptr) { return ctx->unaryExp()->accept(this); } - // 处理 MulExp op unaryExp 的递归形式 - if (!ctx->exp(0) || !ctx->unaryExp(0)) { + // 处理 mulExp op unaryExp 的递归形式 + if (!ctx->mulExp() || !ctx->unaryExp()) { throw std::runtime_error(FormatError("irgen", "非法乘除法表达式结构")); } - ir::Value* lhs = std::any_cast(ctx->exp(0)->accept(this)); - ir::Value* rhs = std::any_cast(ctx->unaryExp(0)->accept(this)); + ir::Value* lhs = std::any_cast(ctx->mulExp()->accept(this)); + ir::Value* rhs = std::any_cast(ctx->unaryExp()->accept(this)); ir::Opcode op = ir::Opcode::Mul; if (ctx->MUL()) { diff --git a/src/irgen/IRGenFunc.cpp b/src/irgen/IRGenFunc.cpp index 4912d03..4ee5b3e 100644 --- a/src/irgen/IRGenFunc.cpp +++ b/src/irgen/IRGenFunc.cpp @@ -29,7 +29,7 @@ IRGenImpl::IRGenImpl(ir::Module& module, const SemanticContext& sema) // 编译单元的 IR 生成当前只实现了最小功能: // - Module 已在 GenerateIR 中创建,这里只负责继续生成其中的内容; -// - 当前会读取编译单元中的函数定义,并交给 visitFuncDef 生成函数 IR; +// - 当前会读取编译单元中的 topLevelItem,找到 funcDef 后生成函数 IR; // // 当前还没有实现: // - 多个函数定义的遍历与生成; @@ -38,12 +38,15 @@ std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少编译单元")); } - auto* func = ctx->funcDef(); - if (!func) { - throw std::runtime_error(FormatError("irgen", "缺少函数定义")); + // 遍历所有 topLevelItem,找到 funcDef + for (auto* item : ctx->topLevelItem()) { + if (item && item->funcDef()) { + item->funcDef()->accept(this); + // 当前只支持单个函数,找到第一个后就返回 + return {}; + } } - func->accept(this); - return {}; + throw std::runtime_error(FormatError("irgen", "缺少函数定义")); } // 函数 IR 生成当前实现了: @@ -61,12 +64,11 @@ std::any IRGenImpl::visitCompUnit(SysYParser::CompUnitContext* ctx) { // - 入口块中的参数初始化逻辑。 // ... -// 因此这里目前只支持最小的“无参 int 函数”生成。 std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少函数定义")); } - if (!ctx->blockStmt()) { + if (!ctx->block()) { throw std::runtime_error(FormatError("irgen", "函数体为空")); } if (!ctx->ID()) { @@ -80,7 +82,7 @@ std::any IRGenImpl::visitFuncDef(SysYParser::FuncDefContext* ctx) { builder_.SetInsertPoint(func_->GetEntry()); storage_map_.clear(); - ctx->blockStmt()->accept(this); + ctx->block()->accept(this); // 语义正确性主要由 sema 保证,这里只兜底检查 IR 结构是否合法。 VerifyFunctionStructure(*func_); return {}; diff --git a/src/irgen/IRGenStmt.cpp b/src/irgen/IRGenStmt.cpp index 751550c..8f7a2a5 100644 --- a/src/irgen/IRGenStmt.cpp +++ b/src/irgen/IRGenStmt.cpp @@ -19,21 +19,14 @@ std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少语句")); } - if (ctx->returnStmt()) { - return ctx->returnStmt()->accept(this); + // 检查是否是 return 语句:RETURN exp? SEMICOLON + if (ctx->RETURN()) { + if (!ctx->exp()) { + throw std::runtime_error(FormatError("irgen", "return 缺少表达式")); + } + ir::Value* v = EvalExpr(*ctx->exp()); + builder_.CreateRet(v); + return BlockFlow::Terminated; } throw std::runtime_error(FormatError("irgen", "暂不支持的语句类型")); } - - -std::any IRGenImpl::visitReturnStmt(SysYParser::ReturnStmtContext* ctx) { - if (!ctx) { - throw std::runtime_error(FormatError("irgen", "缺少 return 语句")); - } - if (!ctx->exp()) { - throw std::runtime_error(FormatError("irgen", "return 缺少表达式")); - } - ir::Value* v = EvalExpr(*ctx->exp()); - builder_.CreateRet(v); - return BlockFlow::Terminated; -} diff --git a/src/sem/Sema.cpp b/src/sem/Sema.cpp index f0b49e5..fc73f9d 100644 --- a/src/sem/Sema.cpp +++ b/src/sem/Sema.cpp @@ -434,9 +434,11 @@ class SemaVisitor final : public SysYBaseVisitor { if (!ctx) { ThrowSemaError(ctx, "非法乘法表达式"); } - if (ctx->unaryExp()) { + // 如果是 mulExp : unaryExp 形式(没有 MUL/DIV/MOD token),直接处理 unaryExp + if (!ctx->MUL() && !ctx->DIV() && !ctx->MOD()) { return EvalExpr(*ctx->unaryExp()); } + // 否则是 mulExp MUL/DIV/MOD unaryExp 形式 ExprInfo lhs = EvalExpr(*ctx->mulExp()); ExprInfo rhs = EvalExpr(*ctx->unaryExp()); return EvalArithmetic(*ctx, lhs, rhs, ctx->MUL() ? '*' : (ctx->DIV() ? '/' : '%')); @@ -446,9 +448,11 @@ class SemaVisitor final : public SysYBaseVisitor { if (!ctx) { ThrowSemaError(ctx, "非法加法表达式"); } - if (ctx->mulExp()) { + // 如果是 addExp : mulExp 形式(没有 ADD/SUB token),直接处理 mulExp + if (!ctx->ADD() && !ctx->SUB()) { return EvalExpr(*ctx->mulExp()); } + // 否则是 addExp ADD/SUB mulExp 形式 ExprInfo lhs = EvalExpr(*ctx->addExp()); ExprInfo rhs = EvalExpr(*ctx->mulExp()); return EvalArithmetic(*ctx, lhs, rhs, ctx->ADD() ? '+' : '-'); @@ -544,7 +548,7 @@ class SemaVisitor final : public SysYBaseVisitor { const std::string name = ctx.ID()->getText(); const ObjectBinding* symbol = symbols_.Lookup(name); if (!symbol) { - ThrowSemaError(&ctx, "使用了未声明的标识符: " + name); + ThrowSemaError(&ctx, "使用了未声明的标识符:" + name); } sema_.BindObjectUse(&ctx, *symbol); From b1477851c666cd72aafdc4a832daaff48f581417 Mon Sep 17 00:00:00 2001 From: lc <18783417278@163.com> Date: Mon, 30 Mar 2026 20:31:28 +0800 Subject: [PATCH 07/11] =?UTF-8?q?=E2=80=9CIRGen=E9=83=A8=E5=88=86=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=EF=BC=9A=E6=94=AF=E6=8C=81=E4=B8=80=E5=85=83=E8=BF=90?= =?UTF-8?q?=E7=AE=97=E7=AC=A6=EF=BC=88=E6=AD=A3=E8=B4=9F=E5=8F=B7=EF=BC=89?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/ir/IR.h | 12 ++++++++++-- include/irgen/IRGen.h | 1 + src/ir/IRBuilder.cpp | 10 ++++++++++ src/ir/IRPrinter.cpp | 10 ++++++++++ src/ir/Instruction.cpp | 23 +++++++++++++++++++++++ src/irgen/IRGenExp.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 92 insertions(+), 2 deletions(-) diff --git a/include/ir/IR.h b/include/ir/IR.h index ed38827..6af2d96 100644 --- a/include/ir/IR.h +++ b/include/ir/IR.h @@ -153,7 +153,7 @@ class ConstantInt : public ConstantValue { // 后续还需要扩展更多指令类型。 // enum class Opcode { Add, Sub, Mul, Alloca, Load, Store, Ret }; -enum class Opcode { Add, Sub, Mul, Div, Mod, Alloca, Load, Store, Ret }; +enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret }; // User 是所有“会使用其他 Value 作为输入”的 IR 对象的抽象基类。 // 当前实现中只有 Instruction 继承自 User。 @@ -197,7 +197,14 @@ class BinaryInst : public Instruction { BinaryInst(Opcode op, std::shared_ptr ty, Value* lhs, Value* rhs, std::string name); Value* GetLhs() const; - Value* GetRhs() const; + Value* GetRhs() const; +}; + +class UnaryInst : public Instruction { + public: + UnaryInst(Opcode op, std::shared_ptr ty, Value* operand, + std::string name); + Value* GetUnaryOperand() const; }; class ReturnInst : public Instruction { @@ -303,6 +310,7 @@ class IRBuilder { BinaryInst* CreateAdd(Value* lhs, Value* rhs, const std::string& name); BinaryInst* CreateSub(Value* lhs, Value* rhs, const std::string& name); BinaryInst* CreateMul(Value* lhs, Value* rhs, const std::string& name); + UnaryInst* CreateNeg(Value* operand, const std::string& name); AllocaInst* CreateAllocaI32(const std::string& name); LoadInst* CreateLoad(Value* ptr, const std::string& name); StoreInst* CreateStore(Value* val, Value* ptr); diff --git a/include/irgen/IRGen.h b/include/irgen/IRGen.h index 24d0b3b..2ed1c85 100644 --- a/include/irgen/IRGen.h +++ b/include/irgen/IRGen.h @@ -36,6 +36,7 @@ class IRGenImpl final : public SysYBaseVisitor { std::any visitLVal(SysYParser::LValContext* ctx) override; std::any visitAddExp(SysYParser::AddExpContext* ctx) override; std::any visitMulExp(SysYParser::MulExpContext* ctx) override; + std::any visitUnaryExp(SysYParser::UnaryExpContext* ctx) override; private: enum class BlockFlow { diff --git a/src/ir/IRBuilder.cpp b/src/ir/IRBuilder.cpp index 37861c8..54cc5d2 100644 --- a/src/ir/IRBuilder.cpp +++ b/src/ir/IRBuilder.cpp @@ -94,4 +94,14 @@ BinaryInst* IRBuilder::CreateMul(Value* lhs, Value* rhs, const std::string& name return CreateBinary(Opcode::Mul, lhs, rhs, name); } +UnaryInst* IRBuilder::CreateNeg(Value* operand, const std::string& name) { + if (!insert_block_) { + throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点")); + } + if (!operand) { + throw std::runtime_error(FormatError("ir", "IRBuilder::CreateNeg 缺少操作数")); + } + return insert_block_->Append(Opcode::Neg, Type::GetInt32Type(), operand, name); +} + } // namespace ir diff --git a/src/ir/IRPrinter.cpp b/src/ir/IRPrinter.cpp index 6d7f486..3716751 100644 --- a/src/ir/IRPrinter.cpp +++ b/src/ir/IRPrinter.cpp @@ -36,6 +36,8 @@ static const char* OpcodeToString(Opcode op) { return "sdiv"; case Opcode::Mod: return "srem"; + case Opcode::Neg: + return "neg"; case Opcode::Alloca: return "alloca"; case Opcode::Load: @@ -80,6 +82,14 @@ void IRPrinter::Print(const Module& module, std::ostream& os) { << ValueToString(bin->GetRhs()) << "\n"; break; } + case Opcode::Neg: { + auto* unary = static_cast(inst); + os << " " << unary->GetName() << " = " + << OpcodeToString(unary->GetOpcode()) << " " + << TypeToString(*unary->GetUnaryOperand()->GetType()) << " " + << ValueToString(unary->GetUnaryOperand()) << "\n"; + break; + } case Opcode::Alloca: { auto* alloca = static_cast(inst); os << " " << alloca->GetName() << " = alloca i32\n"; diff --git a/src/ir/Instruction.cpp b/src/ir/Instruction.cpp index 5abab19..199b123 100644 --- a/src/ir/Instruction.cpp +++ b/src/ir/Instruction.cpp @@ -86,6 +86,29 @@ Value* BinaryInst::GetLhs() const { return GetOperand(0); } Value* BinaryInst::GetRhs() const { return GetOperand(1); } +UnaryInst::UnaryInst(Opcode op, std::shared_ptr ty, Value* operand, + std::string name) + : Instruction(op, std::move(ty), std::move(name)) { + if (op != Opcode::Neg) { + throw std::runtime_error(FormatError("ir", "UnaryInst 不支持的操作码")); + } + if (!operand) { + throw std::runtime_error(FormatError("ir", "UnaryInst 缺少操作数")); + } + if (!type_ || !operand->GetType()) { + throw std::runtime_error(FormatError("ir", "UnaryInst 缺少类型信息")); + } + if (type_->GetKind() != operand->GetType()->GetKind()) { + throw std::runtime_error(FormatError("ir", "UnaryInst 类型不匹配")); + } + if (!type_->IsInt32()) { + throw std::runtime_error(FormatError("ir", "UnaryInst 当前只支持 i32")); + } + AddOperand(operand); +} + +Value* UnaryInst::GetUnaryOperand() const { return GetOperand(0); } + ReturnInst::ReturnInst(std::shared_ptr void_ty, Value* val) : Instruction(Opcode::Ret, std::move(void_ty), "") { if (!val) { diff --git a/src/irgen/IRGenExp.cpp b/src/irgen/IRGenExp.cpp index 7b25d4a..55c3cc2 100644 --- a/src/irgen/IRGenExp.cpp +++ b/src/irgen/IRGenExp.cpp @@ -132,6 +132,44 @@ std::any IRGenImpl::visitAddExp(SysYParser::AddExpContext* ctx) { builder_.CreateBinary(op, lhs, rhs, module_.GetContext().NextTemp())); } + +std::any IRGenImpl::visitUnaryExp(SysYParser::UnaryExpContext* ctx) { + if (!ctx) { + throw std::runtime_error(FormatError("irgen", "非法一元表达式")); + } + + // 如果是 primaryExp 直接返回(unaryExp : primaryExp) + if (ctx->primaryExp()) { + return ctx->primaryExp()->accept(this); + } + + // 处理函数调用(unaryExp : ID LPAREN funcRParams? RPAREN) + // 当前暂不支持,留给后续扩展 + if (ctx->ID()) { + throw std::runtime_error(FormatError("irgen", "暂不支持函数调用")); + } + + // 处理一元运算符(unaryExp : addUnaryOp unaryExp) + if (ctx->addUnaryOp() && ctx->unaryExp()) { + ir::Value* operand = std::any_cast(ctx->unaryExp()->accept(this)); + + // 判断是正号还是负号 + if (ctx->addUnaryOp()->SUB()) { + // 负号:生成 sub 0, operand(LLVM IR 中没有 neg 指令) + ir::Value* zero = builder_.CreateConstInt(0); + return static_cast( + builder_.CreateSub(zero, operand, module_.GetContext().NextTemp())); + } else if (ctx->addUnaryOp()->ADD()) { + // 正号:直接返回操作数(+x 等价于 x) + return operand; + } else { + throw std::runtime_error(FormatError("irgen", "未知的一元运算符")); + } + } + + throw std::runtime_error(FormatError("irgen", "不支持的一元表达式类型")); +} + std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "非法乘除法表达式")); From 8297700496bcd894f8454637e909ba98cb867e63 Mon Sep 17 00:00:00 2001 From: lc <18783417278@163.com> Date: Mon, 30 Mar 2026 20:36:21 +0800 Subject: [PATCH 08/11] =?UTF-8?q?IRGen=E9=83=A8=E5=88=86=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=EF=BC=9A=E6=94=AF=E6=8C=81=E8=B5=8B=E5=80=BC=E8=A1=A8=E8=BE=BE?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/irgen/IRGenStmt.cpp | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/irgen/IRGenStmt.cpp b/src/irgen/IRGenStmt.cpp index 8f7a2a5..de6a857 100644 --- a/src/irgen/IRGenStmt.cpp +++ b/src/irgen/IRGenStmt.cpp @@ -9,9 +9,9 @@ // 语句生成当前只实现了最小子集。 // 目前支持: // - return ; +// - 赋值语句:lVal = exp; // // 还未支持: -// - 赋值语句 // - if / while 等控制流 // - 空语句、块语句嵌套分发之外的更多语句形态 @@ -19,6 +19,42 @@ std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少语句")); } + + // 检查是否是赋值语句:lVal ASSIGN exp SEMICOLON + if (ctx->lVal() && ctx->ASSIGN()) { + if (!ctx->exp()) { + throw std::runtime_error(FormatError("irgen", "赋值语句缺少表达式")); + } + + // 1. 计算右值表达式的值 + ir::Value* rhs = EvalExpr(*ctx->exp()); + + // 2. 找到左值变量对应的存储槽位 + auto* lval_ctx = ctx->lVal(); + if (!lval_ctx || !lval_ctx->ID()) { + throw std::runtime_error(FormatError("irgen", "当前仅支持普通整型变量赋值")); + } + + const auto* decl = sema_.ResolveObjectUse(lval_ctx); + if (!decl) { + throw std::runtime_error( + FormatError("irgen", + "变量使用缺少语义绑定:" + lval_ctx->ID()->getText())); + } + + std::string var_name = lval_ctx->ID()->getText(); + auto it = storage_map_.find(var_name); + if (it == storage_map_.end()) { + throw std::runtime_error( + FormatError("irgen", + "变量声明缺少存储槽位:" + var_name)); + } + + // 3. 生成 store 指令 + builder_.CreateStore(rhs, it->second); + return BlockFlow::Continue; + } + // 检查是否是 return 语句:RETURN exp? SEMICOLON if (ctx->RETURN()) { if (!ctx->exp()) { @@ -28,5 +64,6 @@ std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) { builder_.CreateRet(v); return BlockFlow::Terminated; } + throw std::runtime_error(FormatError("irgen", "暂不支持的语句类型")); } From 8ba3b01271da0e62110b2c7ce713aca555a80f91 Mon Sep 17 00:00:00 2001 From: lc <18783417278@163.com> Date: Mon, 30 Mar 2026 20:57:41 +0800 Subject: [PATCH 09/11] =?UTF-8?q?"IRGen=E9=83=A8=E5=88=86=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=EF=BC=8C=E4=BB=BB=E5=8A=A11=E5=AE=8C=E6=88=90"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/lab2剩余任务分工.md | 51 +++++- scripts/test_lab2_ir1.sh | 157 ++++++++++++++++++ scripts/test_lab2_sema.sh | 0 test/test_case/irgen_lab1_4/01_simple_add.out | 1 + test/test_case/irgen_lab1_4/01_simple_add.sy | 6 + test/test_case/irgen_lab1_4/02_sub_mul.out | 1 + test/test_case/irgen_lab1_4/02_sub_mul.sy | 8 + test/test_case/irgen_lab1_4/03_div_mod.out | 1 + test/test_case/irgen_lab1_4/03_div_mod.sy | 8 + test/test_case/irgen_lab1_4/04_unary.out | 1 + test/test_case/irgen_lab1_4/04_unary.sy | 7 + test/test_case/irgen_lab1_4/05_assign.out | 1 + test/test_case/irgen_lab1_4/05_assign.sy | 7 + test/test_case/irgen_lab1_4/06_multi_decl.out | 1 + test/test_case/irgen_lab1_4/06_multi_decl.sy | 5 + .../irgen_lab1_4/07_comprehensive.out | 1 + .../irgen_lab1_4/07_comprehensive.sy | 14 ++ 17 files changed, 269 insertions(+), 1 deletion(-) create mode 100755 scripts/test_lab2_ir1.sh mode change 100644 => 100755 scripts/test_lab2_sema.sh create mode 100644 test/test_case/irgen_lab1_4/01_simple_add.out create mode 100644 test/test_case/irgen_lab1_4/01_simple_add.sy create mode 100644 test/test_case/irgen_lab1_4/02_sub_mul.out create mode 100644 test/test_case/irgen_lab1_4/02_sub_mul.sy create mode 100644 test/test_case/irgen_lab1_4/03_div_mod.out create mode 100644 test/test_case/irgen_lab1_4/03_div_mod.sy create mode 100644 test/test_case/irgen_lab1_4/04_unary.out create mode 100644 test/test_case/irgen_lab1_4/04_unary.sy create mode 100644 test/test_case/irgen_lab1_4/05_assign.out create mode 100644 test/test_case/irgen_lab1_4/05_assign.sy create mode 100644 test/test_case/irgen_lab1_4/06_multi_decl.out create mode 100644 test/test_case/irgen_lab1_4/06_multi_decl.sy create mode 100644 test/test_case/irgen_lab1_4/07_comprehensive.out create mode 100644 test/test_case/irgen_lab1_4/07_comprehensive.sy diff --git a/doc/lab2剩余任务分工.md b/doc/lab2剩余任务分工.md index 9ba8abb..70e63de 100644 --- a/doc/lab2剩余任务分工.md +++ b/doc/lab2剩余任务分工.md @@ -1,4 +1,4 @@ -### 人员 1:基础表达式与赋值支持(lc) +### 人员 1:基础表达式与赋值支持(lc,已完成) - 任务 1.1:支持更多二元运算符(Sub, Mul, Div, Mod) - 任务 1.2:支持一元运算符(正负号) @@ -19,3 +19,52 @@ - 任务 3.3:支持函数调用生成 - 任务 3.4:支持 const 常量声明 +
+ +
+ +## 人员 1 完成情况详细说明(更新于 2026-03-30) + +### ✅ 已完成任务 + +人员 1 已完整实现 Lab2 IR 生成的基础功能模块,包括: + +1. **二元运算符**(任务 1.1) + - 实现 `Sub`, `Mul`, `Div`, `Mod` 四种运算符 + - 修改文件:`include/ir/IR.h`, `src/ir/IRBuilder.cpp`, `src/ir/IRPrinter.cpp`, `src/irgen/IRGenExp.cpp` +2. **一元运算符**(任务 1.2) + - 实现正负号运算符(`+`, `-`) + - 新增 `UnaryInst` 类支持一元指令 + - 负号生成 `sub 0, x` 指令(LLVM IR 标准形式) +3. **赋值表达式**(任务 1.3) + - 实现变量赋值语句的 IR 生成 + - 修改文件:`src/irgen/IRGenStmt.cpp` +4. **多变量声明**(任务 1.4) + - 支持逗号分隔的变量声明(如 `int a, b, c;`) + - 支持带初始化的多变量声明(如 `int a = 1, b = 2;`) + +### 🧪 测试验证 + +- **Lab1 语法分析**:✅ 通过(10/11 functional 测试,1 个数组测试超出范围) +- **Lab2 语义分析**:✅ 通过(6 正例 + 4 反例) +- **IR 生成测试**:✅ 通过(7/7 自定义测试用例) + - 测试脚本:`./scripts/test_lab2_ir1.sh` + - 测试用例目录:`test/test_case/irgen_lab1_4/` + +### 📝 代码质量 + +- 所有修改已通过编译测试 +- 未影响原有 Lab1 和 Lab2 Sema 功能 +- 代码风格与项目保持一致 +- 关键函数添加了注释说明 + +### 🔄 协作接口 + +人员 1 的实现为后续任务提供了以下接口: + +- **表达式生成**:`visitAddExp`, `visitMulExp`, `visitUnaryExp` +- **语句生成**:`visitStmt`(支持赋值和 return) +- **变量管理**:`storage_map_` 维护变量名到栈槽位的映射 +- **IR 构建**:`IRBuilder::CreateBinary`, `IRBuilder::CreateNeg`, `IRBuilder::CreateStore` + +后续人员可以在此基础上扩展更复杂的功能(控制流、函数调用等)。 diff --git a/scripts/test_lab2_ir1.sh b/scripts/test_lab2_ir1.sh new file mode 100755 index 0000000..65f9c3f --- /dev/null +++ b/scripts/test_lab2_ir1.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +# 测试 Lab2 IR 生成 - 人员 1 的任务 +# 测试内容: +# - 任务 1.1: 支持更多二元运算符(Sub, Mul, Div, Mod) +# - 任务 1.2: 支持一元运算符(正负号) +# - 任务 1.3: 支持赋值表达式 +# - 任务 1.4: 支持逗号分隔的多个变量声明 + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" +COMPILER="$PROJECT_ROOT/build/bin/compiler" +TEST_DIR="$PROJECT_ROOT/test/test_case/irgen_lab1_4" +RESULT_DIR="$PROJECT_ROOT/test/test_result/lab2_ir1" + +# 颜色输出 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +echo "=========================================" +echo "Lab2 IR 生成测试 - 部分任务验证" +echo "=========================================" +echo "" + +# 检查编译器是否存在 +if [[ ! -x "$COMPILER" ]]; then + echo -e "${RED}错误:编译器不存在或不可执行:$COMPILER${NC}" + echo "请先运行:cmake --build build" + exit 1 +fi + +# 检查测试目录是否存在 +if [[ ! -d "$TEST_DIR" ]]; then + echo -e "${RED}错误:测试目录不存在:$TEST_DIR${NC}" + exit 1 +fi + +# 创建结果目录 +mkdir -p "$RESULT_DIR" + +# 统计 +total=0 +passed=0 +failed=0 + +# 测试函数 +run_test() { + local input=$1 + local basename=$(basename "$input" .sy) + local expected_out="$TEST_DIR/$basename.out" + local actual_out="$RESULT_DIR/$basename.actual.out" + local ll_file="$RESULT_DIR/$basename.ll" + + ((total++)) || true + + echo -n "测试 $basename ... " + + # 生成 IR + if ! "$COMPILER" --emit-ir "$input" > "$ll_file" 2>&1; then + echo -e "${RED}IR 生成失败${NC}" + ((failed++)) || true + return 1 + fi + + # 如果需要运行并比对输出 + if [[ -f "$expected_out" ]]; then + # 编译并运行 + local exe_file="$RESULT_DIR/$basename" + if ! llc -O0 -filetype=obj "$ll_file" -o "$RESULT_DIR/$basename.o" 2>/dev/null; then + echo -e "${YELLOW}LLVM 编译失败 (llc)${NC}" + cat "$ll_file" + ((failed++)) || true + return 1 + fi + + if ! clang "$RESULT_DIR/$basename.o" -o "$exe_file" 2>/dev/null; then + echo -e "${YELLOW}链接失败 (clang)${NC}" + ((failed++)) || true + return 1 + fi + + # 运行程序,捕获返回值(低 8 位) + local exit_code=0 + "$exe_file" > "$actual_out" 2>&1 || exit_code=$? + + # 处理返回值(LLVM/AArch64 返回的是 8 位无符号整数) + if [[ $exit_code -gt 127 ]]; then + # 转换为有符号整数 + exit_code=$((exit_code - 256)) + fi + echo "$exit_code" > "$actual_out" + + # 比对输出 + if diff -q "$expected_out" "$actual_out" > /dev/null 2>&1; then + echo -e "${GREEN}✓ 通过${NC}" + ((passed++)) || true + return 0 + else + echo -e "${RED}✗ 输出不匹配${NC}" + echo " 期望:$(cat "$expected_out")" + echo " 实际:$(cat "$actual_out")" + ((failed++)) || true + return 1 + fi + else + # 没有期望输出,只检查 IR 生成 + echo -e "${GREEN}✓ IR 生成成功${NC}" + ((passed++)) || true + return 0 + fi +} + +# 查找所有测试用例 +test_files=() +while IFS= read -r -d '' file; do + test_files+=("$file") +done < <(find "$TEST_DIR" -name "*.sy" -type f -print0 | sort -z) + +if [[ ${#test_files[@]} -eq 0 ]]; then + echo -e "${RED}未找到测试用例:$TEST_DIR${NC}" + exit 1 +fi + +echo "找到 ${#test_files[@]} 个测试用例" +echo "" + +# 运行所有测试 +for test_file in "${test_files[@]}"; do + run_test "$test_file" || true +done + +# 输出统计 +echo "" +echo "=========================================" +echo "测试结果统计" +echo "=========================================" +echo -e "总数:$total" +echo -e "通过:${GREEN}$passed${NC}" +echo -e "失败:${RED}$failed${NC}" +echo "" + +if [[ $failed -eq 0 ]]; then + echo -e "${GREEN}✓ 所有测试通过!${NC}" + echo "" + echo "测试覆盖:" + echo " ✓ 任务 1.1: 二元运算符(Sub, Mul, Div, Mod)" + echo " ✓ 任务 1.2: 一元运算符(正负号)" + echo " ✓ 任务 1.3: 赋值表达式" + echo " ✓ 任务 1.4: 逗号分隔的多变量声明" + exit 0 +else + echo -e "${RED}✗ 有 $failed 个测试失败${NC}" + exit 1 +fi diff --git a/scripts/test_lab2_sema.sh b/scripts/test_lab2_sema.sh old mode 100644 new mode 100755 diff --git a/test/test_case/irgen_lab1_4/01_simple_add.out b/test/test_case/irgen_lab1_4/01_simple_add.out new file mode 100644 index 0000000..00750ed --- /dev/null +++ b/test/test_case/irgen_lab1_4/01_simple_add.out @@ -0,0 +1 @@ +3 diff --git a/test/test_case/irgen_lab1_4/01_simple_add.sy b/test/test_case/irgen_lab1_4/01_simple_add.sy new file mode 100644 index 0000000..8b5f091 --- /dev/null +++ b/test/test_case/irgen_lab1_4/01_simple_add.sy @@ -0,0 +1,6 @@ +// 测试:简单加法 +int main() { + int a = 1; + int b = 2; + return a + b; +} diff --git a/test/test_case/irgen_lab1_4/02_sub_mul.out b/test/test_case/irgen_lab1_4/02_sub_mul.out new file mode 100644 index 0000000..81b5c5d --- /dev/null +++ b/test/test_case/irgen_lab1_4/02_sub_mul.out @@ -0,0 +1 @@ +37 diff --git a/test/test_case/irgen_lab1_4/02_sub_mul.sy b/test/test_case/irgen_lab1_4/02_sub_mul.sy new file mode 100644 index 0000000..8ddeca9 --- /dev/null +++ b/test/test_case/irgen_lab1_4/02_sub_mul.sy @@ -0,0 +1,8 @@ +// 测试:减法和乘法 +int main() { + int a = 10; + int b = 3; + int c = a - b; + int d = a * b; + return c + d; +} diff --git a/test/test_case/irgen_lab1_4/03_div_mod.out b/test/test_case/irgen_lab1_4/03_div_mod.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/test/test_case/irgen_lab1_4/03_div_mod.out @@ -0,0 +1 @@ +5 diff --git a/test/test_case/irgen_lab1_4/03_div_mod.sy b/test/test_case/irgen_lab1_4/03_div_mod.sy new file mode 100644 index 0000000..beefc9e --- /dev/null +++ b/test/test_case/irgen_lab1_4/03_div_mod.sy @@ -0,0 +1,8 @@ +// 测试:除法和取模 +int main() { + int a = 20; + int b = 6; + int c = a / b; + int d = a % b; + return c + d; +} diff --git a/test/test_case/irgen_lab1_4/04_unary.out b/test/test_case/irgen_lab1_4/04_unary.out new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/test/test_case/irgen_lab1_4/04_unary.out @@ -0,0 +1 @@ +5 diff --git a/test/test_case/irgen_lab1_4/04_unary.sy b/test/test_case/irgen_lab1_4/04_unary.sy new file mode 100644 index 0000000..c36c5e1 --- /dev/null +++ b/test/test_case/irgen_lab1_4/04_unary.sy @@ -0,0 +1,7 @@ +// 测试:一元运算符(正负号) +int main() { + int a = 5; + int b = -a; + int c = +10; + return b + c; +} diff --git a/test/test_case/irgen_lab1_4/05_assign.out b/test/test_case/irgen_lab1_4/05_assign.out new file mode 100644 index 0000000..209e3ef --- /dev/null +++ b/test/test_case/irgen_lab1_4/05_assign.out @@ -0,0 +1 @@ +20 diff --git a/test/test_case/irgen_lab1_4/05_assign.sy b/test/test_case/irgen_lab1_4/05_assign.sy new file mode 100644 index 0000000..5e1eae2 --- /dev/null +++ b/test/test_case/irgen_lab1_4/05_assign.sy @@ -0,0 +1,7 @@ +// 测试:赋值表达式 +int main() { + int a = 10; + int b = 20; + a = b; + return a; +} diff --git a/test/test_case/irgen_lab1_4/06_multi_decl.out b/test/test_case/irgen_lab1_4/06_multi_decl.out new file mode 100644 index 0000000..1e8b314 --- /dev/null +++ b/test/test_case/irgen_lab1_4/06_multi_decl.out @@ -0,0 +1 @@ +6 diff --git a/test/test_case/irgen_lab1_4/06_multi_decl.sy b/test/test_case/irgen_lab1_4/06_multi_decl.sy new file mode 100644 index 0000000..fa95159 --- /dev/null +++ b/test/test_case/irgen_lab1_4/06_multi_decl.sy @@ -0,0 +1,5 @@ +// 测试:逗号分隔的多变量声明 +int main() { + int a = 1, b = 2, c = 3; + return a + b + c; +} diff --git a/test/test_case/irgen_lab1_4/07_comprehensive.out b/test/test_case/irgen_lab1_4/07_comprehensive.out new file mode 100644 index 0000000..81b5c5d --- /dev/null +++ b/test/test_case/irgen_lab1_4/07_comprehensive.out @@ -0,0 +1 @@ +37 diff --git a/test/test_case/irgen_lab1_4/07_comprehensive.sy b/test/test_case/irgen_lab1_4/07_comprehensive.sy new file mode 100644 index 0000000..753aeae --- /dev/null +++ b/test/test_case/irgen_lab1_4/07_comprehensive.sy @@ -0,0 +1,14 @@ +// 测试:综合测试(所有功能) +int main() { + int a = 10, b = 5; + int c = a + b; + int d = a - b; + int e = a * 2; + int f = a / b; + int g = a % b; + int h = -c; + int i = +d; + a = b + c; + b = d + e; + return a + b + f + g + h + i; +} From d2f49b71c5f5601460a8cf9b5e17286b9d1cdd00 Mon Sep 17 00:00:00 2001 From: Oliveira <1350121858@qq.com> Date: Tue, 31 Mar 2026 13:26:26 +0800 Subject: [PATCH 10/11] gitignore add --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1ee33a1..51f5f27 100644 --- a/.gitignore +++ b/.gitignore @@ -68,3 +68,4 @@ Thumbs.db # Project outputs # ========================= test/test_result/ +sema_check \ No newline at end of file From 2de1561210d63e86bfe09679ac7ed13febb4c136 Mon Sep 17 00:00:00 2001 From: Oliveira <1350121858@qq.com> Date: Tue, 31 Mar 2026 13:56:52 +0800 Subject: [PATCH 11/11] =?UTF-8?q?feat(irgen):=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E6=B5=81=E4=B8=8E=E9=80=BB=E8=BE=91=E8=A1=A8?= =?UTF-8?q?=E8=BE=BE=E5=BC=8F=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90=20-=20?= =?UTF-8?q?=E6=A0=B8=E5=BF=83=E5=8A=9F=E8=83=BD=E6=94=AF=E6=8C=81=EF=BC=9A?= =?UTF-8?q?=E5=AE=8C=E6=95=B4=E5=AE=9E=E7=8E=B0=20if-else,=20while,=20brea?= =?UTF-8?q?k,=20continue=20=E8=AF=AD=E5=8F=A5=E7=9A=84=20IR=20=E7=94=9F?= =?UTF-8?q?=E6=88=90=E5=8F=8A=E8=B7=B3=E5=87=BA=E5=9D=97=E7=BB=B4=E6=8A=A4?= =?UTF-8?q?=20-=20=E6=89=A9=E5=B1=95=E6=8C=87=E4=BB=A4=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=EF=BC=9A=E6=96=B0=E5=A2=9E=20Cmp,=20Zext,=20Br,=20CondBr=20?= =?UTF-8?q?=E6=8C=87=E4=BB=A4=EF=BC=8C=E8=A1=A5=E9=BD=90=20Builder/Printer?= =?UTF-8?q?=20=E6=8E=A5=E5=8F=A3=20-=20=E6=94=AF=E6=8C=81=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E8=A1=A8=E8=BE=BE=E5=BC=8F=EF=BC=9A=E5=AE=8C=E6=88=90?= =?UTF-8?q?=20RelExp,=20EqExp,=20=E9=80=BB=E8=BE=91=E7=9F=AD=E8=B7=AF?= =?UTF-8?q?=E6=B1=82=E5=80=BC=20(LAndExp,=20LOrExp)=20=E5=8F=8A=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E9=9D=9E=E7=9A=84=E7=BF=BB=E8=AF=91=20-=20=E6=9E=B6?= =?UTF-8?q?=E6=9E=84=E8=B0=83=E6=95=B4=E6=9C=BA=E5=88=B6=20BUG=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=EF=BC=9A=20=20=201.=20=E4=BF=AE=E5=A4=8D=20Sema.cpp?= =?UTF-8?q?=20=E5=85=B3=E7=B3=BB=E8=A1=A8=E8=BE=BE=E5=BC=8F=20AST=20?= =?UTF-8?q?=E4=B8=A2=E5=A4=B1=E9=83=A8=E5=88=86=E5=88=86=E6=94=AF=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E8=BF=BD=E8=B8=AA=E7=9A=84=E8=A7=A3=E6=9E=90=20Bug=20?= =?UTF-8?q?=20=202.=20=E4=BF=AE=E5=A4=8D=20IRGenDecl=20=E4=B8=AD=E6=89=93?= =?UTF-8?q?=E6=96=AD=E5=88=A4=E5=AE=9A=E7=BC=BA=E5=A4=B1=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E7=94=9F=E6=88=90=E5=86=97=E4=BD=99=E6=AD=BB=E5=9D=97=E7=BB=88?= =?UTF-8?q?=E6=AD=A2=E7=AC=A6=E7=9A=84=E9=97=AE=E9=A2=98=20=20=203.=20?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=B8=B4=E6=97=B6=E5=8F=98=E9=87=8F=E5=90=8D?= =?UTF-8?q?=E4=B8=BA=20%tN=EF=BC=8C=E8=A7=A3=E5=86=B3=E7=BA=AF=E6=95=B0?= =?UTF-8?q?=E5=80=BC=E6=A0=87=E5=8F=B7=E5=BC=95=E5=8F=91=E7=9A=84=20llc=20?= =?UTF-8?q?=E5=91=BD=E5=90=8D=E5=BA=8F=E5=88=97=E6=A3=80=E6=9F=A5=E6=8A=A5?= =?UTF-8?q?=E9=94=99=20-=20=E6=96=87=E6=A1=A3=E6=9B=B4=E6=96=B0=EF=BC=9A?= =?UTF-8?q?=E4=BA=8E=20lab2=E5=89=A9=E4=BD=99=E4=BB=BB=E5=8A=A1=E5=88=86?= =?UTF-8?q?=E5=B7=A5.md=20=E4=B8=AD=E6=A0=87=E8=AE=B0=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E8=BF=9B=E5=BA=A6=E4=B8=BA=E5=B7=B2=E5=AE=8C=E6=88=90=E5=B9=B6?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E6=B5=8B=E8=AF=95=E8=BF=90=E8=A1=8C=E8=AF=B4?= =?UTF-8?q?=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- doc/lab2剩余任务分工.md | 42 ++++++++++-- include/ir/IR.h | 44 +++++++++++- include/irgen/IRGen.h | 15 ++++ patch_IR_h.patch | 83 ++++++++++++++++++++++ src/ir/Context.cpp | 2 +- src/ir/IRBuilder.cpp | 40 +++++++++++ src/ir/IRPrinter.cpp | 73 +++++++++++++++++++- src/ir/Instruction.cpp | 61 ++++++++++++++++- src/ir/Type.cpp | 7 ++ src/ir/Value.cpp | 2 + src/irgen/IRGenDecl.cpp | 9 +-- src/irgen/IRGenExp.cpp | 125 ++++++++++++++++++++++++++++++++++ src/irgen/IRGenStmt.cpp | 119 +++++++++++++++++++++++++++----- src/sem/Sema.cpp | 8 +-- 14 files changed, 594 insertions(+), 36 deletions(-) create mode 100644 patch_IR_h.patch diff --git a/doc/lab2剩余任务分工.md b/doc/lab2剩余任务分工.md index 70e63de..8969726 100644 --- a/doc/lab2剩余任务分工.md +++ b/doc/lab2剩余任务分工.md @@ -5,7 +5,7 @@ - 任务 1.3:支持赋值表达式 - 任务 1.4:支持逗号分隔的多个变量声明 -### 人员 2:控制流支持 +### 人员 2:控制流支持(lyy,已完成) - 任务 2.1:支持 if-else 条件语句 - 任务 2.2:支持 while 循环语句 @@ -19,10 +19,6 @@ - 任务 3.3:支持函数调用生成 - 任务 3.4:支持 const 常量声明 -
- -
- ## 人员 1 完成情况详细说明(更新于 2026-03-30) ### ✅ 已完成任务 @@ -68,3 +64,39 @@ - **IR 构建**:`IRBuilder::CreateBinary`, `IRBuilder::CreateNeg`, `IRBuilder::CreateStore` 后续人员可以在此基础上扩展更复杂的功能(控制流、函数调用等)。 + +## 人员 2 完成情况详细说明(更新于 2026-03-31) + +### ✅ 已完成任务 + +人员 2 已完整实现 Lab2 IR 生成中涉及的控制流支持,包括: + +1. **IR 结构与底层辅助拓展** + - 补充 `Int1` 基础类型以及 `Value::IsInt1()`。 + - 新增 `CmpInst`, `ZextInst`, `BranchInst` 以及 `CondBranchInst` 以支持关系计算和跳转逻辑。 + - 在 `IRBuilder` 中补齐创建此类指令的便捷接口与 `IRPrinter` 适配,并修复了 `IRPrinter` 存在的块命名 `%%` 重复问题。 + - 优化 `Context::NextTemp` 分配命名使用 `%t` 前缀,解决非线性顺序下纯数字临时变量引发 `llc` 后端词法顺序验证失败问题。 +2. **比较和逻辑表达式**(任务 2.4) + - 新增实现 `visitRelExp`、`visitEqExp`。 + - 实现条件二元表达式全链路短路求值 (`visitLAndExp`、`visitLOrExp`)。短路时通过控制流跳转+利用局部栈变量分配并多次赋值记录实现栈传递,规避了 `phi` 的麻烦。 + - 利用 `visitCondUnaryExp` 增加逻辑非 `!` 判定。 +3. **控制流框架支持**(任务 2.1 - 2.3) + - 在 `visitStmt` 中完美实现了 `if-else` 条件语句(自动插入无条件跳合块)、`while` 循环语句。 + - 在 `IRGen` 实例中通过 `current_loop_cond_bb_` 等维护循环栈,实现了 `break` 与 `continue`。 + - 修复了此前框架在 `IRGenDecl.cpp` 的 `visitBlock` 中缺少终结向上传递导致的 `break` 生成不匹配死块 BUG 及重复 `Branch` 问题。 +4. **关键前序 Bug 修复** + - 发现了在原框架里 `src/sem/Sema.cpp` 进行 AST 解析时 `RelExp` 和 `EqExp` 对于非原生底层变量追踪由于左偏漏调规则导致 `null_ptr` (`变量使用缺少语义绑定:a`) 报错的问题,并做出了精修复。 + +### 🧪 测试验证 + +- **Lab2 语义分析**:修复后所有已有的语义正例验证正常。 +- **IR 生成与后端执行**:✅ 自建嵌套含复合逻辑循环脚本测试通过。 +- **验证命令**(运行含 break 和 while 的范例文件): + ```bash + cd build && make -j$(nproc) && cd .. && ./scripts/verify_ir.sh test/test_case/functional/29_break.sy --run + ``` + + **完整测试脚本** + ```bash + for f in test/test_case/functional/*.sy; do echo "Testing $f..."; ./scripts/verify_ir.sh "$f" --run > /dev/null || echo "FAILED $f"; done + ``` \ No newline at end of file diff --git a/include/ir/IR.h b/include/ir/IR.h index 6af2d96..06f837f 100644 --- a/include/ir/IR.h +++ b/include/ir/IR.h @@ -93,16 +93,18 @@ class Context { class Type { public: - enum class Kind { Void, Int32, PtrInt32 }; + enum class Kind { Void, Int1, Int32, PtrInt32 }; explicit Type(Kind k); // 使用静态共享对象获取类型。 // 同一类型可直接比较返回值是否相等,例如: // Type::GetInt32Type() == Type::GetInt32Type() static const std::shared_ptr& GetVoidType(); + static const std::shared_ptr& GetInt1Type(); static const std::shared_ptr& GetInt32Type(); static const std::shared_ptr& GetPtrInt32Type(); Kind GetKind() const; bool IsVoid() const; + bool IsInt1() const; bool IsInt32() const; bool IsPtrInt32() const; @@ -118,6 +120,7 @@ class Value { const std::string& GetName() const; void SetName(std::string n); bool IsVoid() const; + bool IsInt1() const; bool IsInt32() const; bool IsPtrInt32() const; bool IsConstant() const; @@ -153,7 +156,9 @@ class ConstantInt : public ConstantValue { // 后续还需要扩展更多指令类型。 // enum class Opcode { Add, Sub, Mul, Alloca, Load, Store, Ret }; -enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret }; +enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret, Cmp, Zext, Br, CondBr }; + +enum class CmpOp { Eq, Ne, Lt, Gt, Le, Ge }; // User 是所有“会使用其他 Value 作为输入”的 IR 对象的抽象基类。 // 当前实现中只有 Instruction 继承自 User。 @@ -231,6 +236,37 @@ class StoreInst : public Instruction { Value* GetPtr() const; }; +class CmpInst : public Instruction { + public: + CmpInst(CmpOp cmp_op, Value* lhs, Value* rhs, std::string name); + CmpOp GetCmpOp() const; + Value* GetLhs() const; + Value* GetRhs() const; + + private: + CmpOp cmp_op_; +}; + +class ZextInst : public Instruction { + public: + ZextInst(std::shared_ptr dest_ty, Value* val, std::string name); + Value* GetValue() const; +}; + +class BranchInst : public Instruction { + public: + BranchInst(BasicBlock* dest); + BasicBlock* GetDest() const; +}; + +class CondBranchInst : public Instruction { + public: + CondBranchInst(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb); + Value* GetCond() const; + BasicBlock* GetTrueBlock() const; + BasicBlock* GetFalseBlock() const; +}; + // BasicBlock 已纳入 Value 体系,便于后续向更完整 IR 类图靠拢。 // 当前其类型仍使用 void 作为占位,后续可替换为专门的 label type。 class BasicBlock : public Value { @@ -315,6 +351,10 @@ class IRBuilder { LoadInst* CreateLoad(Value* ptr, const std::string& name); StoreInst* CreateStore(Value* val, Value* ptr); ReturnInst* CreateRet(Value* v); + CmpInst* CreateCmp(CmpOp op, Value* lhs, Value* rhs, const std::string& name); + ZextInst* CreateZext(Value* val, const std::string& name); + BranchInst* CreateBr(BasicBlock* dest); + CondBranchInst* CreateCondBr(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb); private: Context& ctx_; diff --git a/include/irgen/IRGen.h b/include/irgen/IRGen.h index 2ed1c85..fec791a 100644 --- a/include/irgen/IRGen.h +++ b/include/irgen/IRGen.h @@ -37,6 +37,12 @@ class IRGenImpl final : public SysYBaseVisitor { std::any visitAddExp(SysYParser::AddExpContext* ctx) override; std::any visitMulExp(SysYParser::MulExpContext* ctx) override; std::any visitUnaryExp(SysYParser::UnaryExpContext* ctx) override; + std::any visitRelExp(SysYParser::RelExpContext* ctx) override; + std::any visitEqExp(SysYParser::EqExpContext* ctx) override; + std::any visitLAndExp(SysYParser::LAndExpContext* ctx) override; + std::any visitLOrExp(SysYParser::LOrExpContext* ctx) override; + std::any visitCondUnaryExp(SysYParser::CondUnaryExpContext* ctx) override; + std::any visitCond(SysYParser::CondContext* ctx) override; private: enum class BlockFlow { @@ -53,6 +59,15 @@ class IRGenImpl final : public SysYBaseVisitor { ir::IRBuilder builder_; // 名称绑定由 Sema 负责;IRGen 只维护"变量名 -> 存储槽位"的代码生成状态。 std::unordered_map storage_map_; + + // 用于 break 和 continue 跳转的目标位置 + ir::BasicBlock* current_loop_cond_bb_ = nullptr; + ir::BasicBlock* current_loop_exit_bb_ = nullptr; + + int bb_cnt_ = 0; + std::string NextBlockName(const std::string& prefix = "bb") { + return prefix + "_" + std::to_string(++bb_cnt_); + } }; std::unique_ptr GenerateIR(SysYParser::CompUnitContext& tree, diff --git a/patch_IR_h.patch b/patch_IR_h.patch new file mode 100644 index 0000000..c1a32ce --- /dev/null +++ b/patch_IR_h.patch @@ -0,0 +1,83 @@ +--- include/ir/IR.h ++++ include/ir/IR.h +@@ -93,6 +93,7 @@ + class Type { + public: +- enum class Kind { Void, Int32, PtrInt32 }; ++ enum class Kind { Void, Int1, Int32, PtrInt32 }; + explicit Type(Kind k); + // 使用静态共享对象获取类型。 + // 同一类型可直接比较返回值是否相等,例如: + // Type::GetInt32Type() == Type::GetInt32Type() + static const std::shared_ptr& GetVoidType(); ++ static const std::shared_ptr& GetInt1Type(); + static const std::shared_ptr& GetInt32Type(); + static const std::shared_ptr& GetPtrInt32Type(); + Kind GetKind() const; + bool IsVoid() const; ++ bool IsInt1() const; + bool IsInt32() const; + bool IsPtrInt32() const; +@@ -118,6 +119,7 @@ + const std::string& GetName() const; + void SetName(std::string n); + bool IsVoid() const; ++ bool IsInt1() const; + bool IsInt32() const; + bool IsPtrInt32() const; + bool IsConstant() const; +@@ -153,7 +155,9 @@ + + // 后续还需要扩展更多指令类型。 +-// enum class Opcode { Add, Sub, Mul, Alloca, Load, Store, Ret }; +-enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret }; ++enum class Opcode { Add, Sub, Mul, Div, Mod, Neg, Alloca, Load, Store, Ret, Cmp, Zext, Br, CondBr }; ++ ++enum class CmpOp { Eq, Ne, Lt, Gt, Le, Ge }; + + // User 是所有“会使用其他 Value 作为输入”的 IR 对象的抽象基类。 +@@ -231,6 +235,33 @@ + Value* GetPtr() const; + }; + ++class CmpInst : public Instruction { ++ public: ++ CmpInst(CmpOp cmp_op, Value* lhs, Value* rhs, std::string name); ++ CmpOp GetCmpOp() const; ++ Value* GetLhs() const; ++ Value* GetRhs() const; ++ private: ++ CmpOp cmp_op_; ++}; ++ ++class ZextInst : public Instruction { ++ public: ++ ZextInst(std::shared_ptr dest_ty, Value* val, std::string name); ++ Value* GetValue() const; ++}; ++ ++class BranchInst : public Instruction { ++ public: ++ BranchInst(BasicBlock* dest); ++ BasicBlock* GetDest() const; ++}; ++ ++class CondBranchInst : public Instruction { ++ public: ++ CondBranchInst(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb); ++ Value* GetCond() const; ++ BasicBlock* GetTrueBlock() const; ++ BasicBlock* GetFalseBlock() const; ++}; ++ + // BasicBlock 已纳入 Value 体系,便于后续向更完整 IR 类图靠拢。 +@@ -315,6 +346,10 @@ + LoadInst* CreateLoad(Value* ptr, const std::string& name); + StoreInst* CreateStore(Value* val, Value* ptr); + ReturnInst* CreateRet(Value* v); ++ CmpInst* CreateCmp(CmpOp op, Value* lhs, Value* rhs, const std::string& name); ++ ZextInst* CreateZext(Value* val, const std::string& name); ++ BranchInst* CreateBr(BasicBlock* dest); ++ CondBranchInst* CreateCondBr(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb); + + private: diff --git a/src/ir/Context.cpp b/src/ir/Context.cpp index 16c982c..5f32c65 100644 --- a/src/ir/Context.cpp +++ b/src/ir/Context.cpp @@ -17,7 +17,7 @@ ConstantInt* Context::GetConstInt(int v) { std::string Context::NextTemp() { std::ostringstream oss; - oss << "%" << ++temp_index_; + oss << "%t" << ++temp_index_; return oss.str(); } diff --git a/src/ir/IRBuilder.cpp b/src/ir/IRBuilder.cpp index 54cc5d2..3569ab6 100644 --- a/src/ir/IRBuilder.cpp +++ b/src/ir/IRBuilder.cpp @@ -104,4 +104,44 @@ UnaryInst* IRBuilder::CreateNeg(Value* operand, const std::string& name) { return insert_block_->Append(Opcode::Neg, Type::GetInt32Type(), operand, name); } +CmpInst* IRBuilder::CreateCmp(CmpOp op, Value* lhs, Value* rhs, const std::string& name) { + if (!insert_block_) { + throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点")); + } + if (!lhs || !rhs) { + throw std::runtime_error(FormatError("ir", "IRBuilder::CreateCmp 缺少操作数")); + } + return insert_block_->Append(op, lhs, rhs, name); +} + +ZextInst* IRBuilder::CreateZext(Value* val, const std::string& name) { + if (!insert_block_) { + throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点")); + } + if (!val) { + throw std::runtime_error(FormatError("ir", "IRBuilder::CreateZext 缺少操作数")); + } + return insert_block_->Append(Type::GetInt32Type(), val, name); +} + +BranchInst* IRBuilder::CreateBr(BasicBlock* dest) { + if (!insert_block_) { + throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点")); + } + if (!dest) { + throw std::runtime_error(FormatError("ir", "IRBuilder::CreateBr 缺少操作数")); + } + return insert_block_->Append(dest); +} + +CondBranchInst* IRBuilder::CreateCondBr(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb) { + if (!insert_block_) { + throw std::runtime_error(FormatError("ir", "IRBuilder 未设置插入点")); + } + if (!cond || !true_bb || !false_bb) { + throw std::runtime_error(FormatError("ir", "IRBuilder::CreateCondBr 缺少操作数")); + } + return insert_block_->Append(cond, true_bb, false_bb); +} + } // namespace ir diff --git a/src/ir/IRPrinter.cpp b/src/ir/IRPrinter.cpp index 3716751..40cfc77 100644 --- a/src/ir/IRPrinter.cpp +++ b/src/ir/IRPrinter.cpp @@ -16,6 +16,8 @@ static const char* TypeToString(const Type& ty) { switch (ty.GetKind()) { case Type::Kind::Void: return "void"; + case Type::Kind::Int1: + return "i1"; case Type::Kind::Int32: return "i32"; case Type::Kind::PtrInt32: @@ -46,6 +48,31 @@ static const char* OpcodeToString(Opcode op) { return "store"; case Opcode::Ret: return "ret"; + case Opcode::Cmp: + return "icmp"; + case Opcode::Zext: + return "zext"; + case Opcode::Br: + case Opcode::CondBr: + return "br"; + } + return "?"; +} + +static const char* CmpOpToString(CmpOp op) { + switch (op) { + case CmpOp::Eq: + return "eq"; + case CmpOp::Ne: + return "ne"; + case CmpOp::Lt: + return "slt"; + case CmpOp::Gt: + return "sgt"; + case CmpOp::Le: + return "sle"; + case CmpOp::Ge: + return "sge"; } return "?"; } @@ -57,6 +84,21 @@ static std::string ValueToString(const Value* v) { return v ? v->GetName() : ""; } +static std::string PrintLabel(const Value* bb) { + if (!bb) return ""; + std::string name = bb->GetName(); + if (name.empty()) return ""; + if (name[0] == '%') return name; + return "%" + name; +} + +static std::string PrintLabelDef(const Value* bb) { + if (!bb) return ""; + std::string name = bb->GetName(); + if (!name.empty() && name[0] == '%') return name.substr(1); + return name; +} + void IRPrinter::Print(const Module& module, std::ostream& os) { for (const auto& func : module.GetFunctions()) { os << "define " << TypeToString(*func->GetType()) << " @" << func->GetName() @@ -65,7 +107,7 @@ void IRPrinter::Print(const Module& module, std::ostream& os) { if (!bb) { continue; } - os << bb->GetName() << ":\n"; + os << PrintLabelDef(bb.get()) << ":\n"; for (const auto& instPtr : bb->GetInstructions()) { const auto* inst = instPtr.get(); switch (inst->GetOpcode()) { @@ -113,6 +155,35 @@ void IRPrinter::Print(const Module& module, std::ostream& os) { << ValueToString(ret->GetValue()) << "\n"; break; } + case Opcode::Cmp: { + auto* cmp = static_cast(inst); + os << " " << cmp->GetName() << " = icmp " + << CmpOpToString(cmp->GetCmpOp()) << " " + << TypeToString(*cmp->GetLhs()->GetType()) << " " + << ValueToString(cmp->GetLhs()) << ", " + << ValueToString(cmp->GetRhs()) << "\n"; + break; + } + case Opcode::Zext: { + auto* zext = static_cast(inst); + os << " " << zext->GetName() << " = zext " + << TypeToString(*zext->GetOperand(0)->GetType()) << " " + << ValueToString(zext->GetOperand(0)) << " to " + << TypeToString(*zext->GetType()) << "\n"; + break; + } + case Opcode::Br: { + auto* br = static_cast(inst); + os << " br label " << PrintLabel(br->GetDest()) << "\n"; + break; + } + case Opcode::CondBr: { + auto* cbr = static_cast(inst); + os << " br i1 " << ValueToString(cbr->GetCond()) + << ", label " << PrintLabel(cbr->GetTrueBlock()) + << ", label " << PrintLabel(cbr->GetFalseBlock()) << "\n"; + break; + } } } } diff --git a/src/ir/Instruction.cpp b/src/ir/Instruction.cpp index 199b123..9ae696c 100644 --- a/src/ir/Instruction.cpp +++ b/src/ir/Instruction.cpp @@ -52,7 +52,7 @@ Instruction::Instruction(Opcode op, std::shared_ptr ty, std::string name) Opcode Instruction::GetOpcode() const { return opcode_; } -bool Instruction::IsTerminator() const { return opcode_ == Opcode::Ret; } +bool Instruction::IsTerminator() const { return opcode_ == Opcode::Ret || opcode_ == Opcode::Br || opcode_ == Opcode::CondBr; } BasicBlock* Instruction::GetParent() const { return parent_; } @@ -172,4 +172,63 @@ Value* StoreInst::GetValue() const { return GetOperand(0); } Value* StoreInst::GetPtr() const { return GetOperand(1); } +CmpInst::CmpInst(CmpOp cmp_op, Value* lhs, Value* rhs, std::string name) + : Instruction(Opcode::Cmp, Type::GetInt1Type(), std::move(name)), cmp_op_(cmp_op) { + if (!lhs || !rhs) { + throw std::runtime_error(FormatError("ir", "CmpInst 缺少操作数")); + } + if (!lhs->GetType() || !rhs->GetType()) { + throw std::runtime_error(FormatError("ir", "CmpInst 缺少操作数类型信息")); + } + if (lhs->GetType()->GetKind() != rhs->GetType()->GetKind()) { + throw std::runtime_error(FormatError("ir", "CmpInst 操作数类型不匹配")); + } + AddOperand(lhs); + AddOperand(rhs); +} + +CmpOp CmpInst::GetCmpOp() const { return cmp_op_; } +Value* CmpInst::GetLhs() const { return GetOperand(0); } +Value* CmpInst::GetRhs() const { return GetOperand(1); } + +ZextInst::ZextInst(std::shared_ptr dest_ty, Value* val, std::string name) + : Instruction(Opcode::Zext, std::move(dest_ty), std::move(name)) { + if (!val) { + throw std::runtime_error(FormatError("ir", "ZextInst 缺少操作数")); + } + if (!type_->IsInt32() || !val->GetType()->IsInt1()) { + throw std::runtime_error(FormatError("ir", "ZextInst 当前只支持 i1 到 i32")); + } + AddOperand(val); +} + +Value* ZextInst::GetValue() const { return GetOperand(0); } + +BranchInst::BranchInst(BasicBlock* dest) + : Instruction(Opcode::Br, Type::GetVoidType(), "") { + if (!dest) { + throw std::runtime_error(FormatError("ir", "BranchInst 缺少目的块")); + } + AddOperand(dest); +} + +BasicBlock* BranchInst::GetDest() const { return static_cast(GetOperand(0)); } + +CondBranchInst::CondBranchInst(Value* cond, BasicBlock* true_bb, BasicBlock* false_bb) + : Instruction(Opcode::CondBr, Type::GetVoidType(), "") { + if (!cond || !true_bb || !false_bb) { + throw std::runtime_error(FormatError("ir", "CondBranchInst 缺少连边操作数")); + } + if (!cond->GetType()->IsInt1()) { + throw std::runtime_error(FormatError("ir", "CondBranchInst 必须使用 i1 作为条件")); + } + AddOperand(cond); + AddOperand(true_bb); + AddOperand(false_bb); +} + +Value* CondBranchInst::GetCond() const { return GetOperand(0); } +BasicBlock* CondBranchInst::GetTrueBlock() const { return static_cast(GetOperand(1)); } +BasicBlock* CondBranchInst::GetFalseBlock() const { return static_cast(GetOperand(2)); } + } // namespace ir diff --git a/src/ir/Type.cpp b/src/ir/Type.cpp index 3e1684d..c32d640 100644 --- a/src/ir/Type.cpp +++ b/src/ir/Type.cpp @@ -10,6 +10,11 @@ const std::shared_ptr& Type::GetVoidType() { return type; } +const std::shared_ptr& Type::GetInt1Type() { + static const std::shared_ptr type = std::make_shared(Kind::Int1); + return type; +} + const std::shared_ptr& Type::GetInt32Type() { static const std::shared_ptr type = std::make_shared(Kind::Int32); return type; @@ -24,6 +29,8 @@ Type::Kind Type::GetKind() const { return kind_; } bool Type::IsVoid() const { return kind_ == Kind::Void; } +bool Type::IsInt1() const { return kind_ == Kind::Int1; } + bool Type::IsInt32() const { return kind_ == Kind::Int32; } bool Type::IsPtrInt32() const { return kind_ == Kind::PtrInt32; } diff --git a/src/ir/Value.cpp b/src/ir/Value.cpp index 2e9f4c1..12a06b4 100644 --- a/src/ir/Value.cpp +++ b/src/ir/Value.cpp @@ -18,6 +18,8 @@ void Value::SetName(std::string n) { name_ = std::move(n); } bool Value::IsVoid() const { return type_ && type_->IsVoid(); } +bool Value::IsInt1() const { return type_ && type_->IsInt1(); } + bool Value::IsInt32() const { return type_ && type_->IsInt32(); } bool Value::IsPtrInt32() const { return type_ && type_->IsPtrInt32(); } diff --git a/src/irgen/IRGenDecl.cpp b/src/irgen/IRGenDecl.cpp index df7ccf9..1cd0db8 100644 --- a/src/irgen/IRGenDecl.cpp +++ b/src/irgen/IRGenDecl.cpp @@ -10,15 +10,16 @@ std::any IRGenImpl::visitBlock(SysYParser::BlockContext* ctx) { if (!ctx) { throw std::runtime_error(FormatError("irgen", "缺少语句块")); } + bool terminated = false; for (auto* item : ctx->blockItem()) { if (item) { if (VisitBlockItemResult(*item) == BlockFlow::Terminated) { - // 当前语法要求 return 为块内最后一条语句;命中后可停止生成。 + terminated = true; break; } } } - return {}; + return terminated ? BlockFlow::Terminated : BlockFlow::Continue; } IRGenImpl::BlockFlow IRGenImpl::VisitBlockItemResult( @@ -66,7 +67,7 @@ std::any IRGenImpl::visitDecl(SysYParser::DeclContext* ctx) { var_def->accept(this); } } - return {}; + return BlockFlow::Continue; } @@ -102,5 +103,5 @@ std::any IRGenImpl::visitVarDef(SysYParser::VarDefContext* ctx) { init = builder_.CreateConstInt(0); } builder_.CreateStore(init, slot); - return {}; + return BlockFlow::Continue; } diff --git a/src/irgen/IRGenExp.cpp b/src/irgen/IRGenExp.cpp index 55c3cc2..4565c6e 100644 --- a/src/irgen/IRGenExp.cpp +++ b/src/irgen/IRGenExp.cpp @@ -201,4 +201,129 @@ std::any IRGenImpl::visitMulExp(SysYParser::MulExpContext* ctx) { return static_cast( builder_.CreateBinary(op, lhs, rhs, module_.GetContext().NextTemp())); +} + +std::any IRGenImpl::visitRelExp(SysYParser::RelExpContext* ctx) { + if (ctx->addExp() && ctx->relExp() == nullptr) { + return ctx->addExp()->accept(this); + } + ir::Value* lhs = std::any_cast(ctx->relExp()->accept(this)); + ir::Value* rhs = std::any_cast(ctx->addExp()->accept(this)); + if (lhs->GetType()->IsInt1()) lhs = builder_.CreateZext(lhs, module_.GetContext().NextTemp()); + if (rhs->GetType()->IsInt1()) rhs = builder_.CreateZext(rhs, module_.GetContext().NextTemp()); + + ir::CmpOp op; + if (ctx->LT()) op = ir::CmpOp::Lt; + else if (ctx->GT()) op = ir::CmpOp::Gt; + else if (ctx->LE()) op = ir::CmpOp::Le; + else if (ctx->GE()) op = ir::CmpOp::Ge; + else throw std::runtime_error(FormatError("irgen", "未知的关系运算符")); + + return static_cast(builder_.CreateCmp(op, lhs, rhs, module_.GetContext().NextTemp())); +} + +std::any IRGenImpl::visitEqExp(SysYParser::EqExpContext* ctx) { + if (ctx->relExp() && ctx->eqExp() == nullptr) { + return ctx->relExp()->accept(this); + } + ir::Value* lhs = std::any_cast(ctx->eqExp()->accept(this)); + ir::Value* rhs = std::any_cast(ctx->relExp()->accept(this)); + if (lhs->GetType()->IsInt1()) lhs = builder_.CreateZext(lhs, module_.GetContext().NextTemp()); + if (rhs->GetType()->IsInt1()) rhs = builder_.CreateZext(rhs, module_.GetContext().NextTemp()); + + ir::CmpOp op; + if (ctx->EQ()) op = ir::CmpOp::Eq; + else if (ctx->NE()) op = ir::CmpOp::Ne; + else throw std::runtime_error(FormatError("irgen", "未知的相等运算符")); + + return static_cast(builder_.CreateCmp(op, lhs, rhs, module_.GetContext().NextTemp())); +} + +std::any IRGenImpl::visitCondUnaryExp(SysYParser::CondUnaryExpContext* ctx) { + if (ctx->eqExp()) { + return ctx->eqExp()->accept(this); + } + if (ctx->NOT()) { + ir::Value* operand = std::any_cast(ctx->condUnaryExp()->accept(this)); + if (operand->GetType()->IsInt1()) { + operand = builder_.CreateZext(operand, module_.GetContext().NextTemp()); + } + ir::Value* zero = builder_.CreateConstInt(0); + return static_cast(builder_.CreateCmp(ir::CmpOp::Eq, operand, zero, module_.GetContext().NextTemp())); + } + throw std::runtime_error(FormatError("irgen", "非法条件一元表达式")); +} + +std::any IRGenImpl::visitLAndExp(SysYParser::LAndExpContext* ctx) { + if (ctx->condUnaryExp() && ctx->lAndExp() == nullptr) { + return ctx->condUnaryExp()->accept(this); + } + + ir::AllocaInst* res_ptr = builder_.CreateAllocaI32(module_.GetContext().NextTemp()); + ir::Value* zero = builder_.CreateConstInt(0); + builder_.CreateStore(zero, res_ptr); + + ir::BasicBlock* rhs_bb = func_->CreateBlock(NextBlockName("land_rhs")); + ir::BasicBlock* end_bb = func_->CreateBlock(NextBlockName("land_end")); + + ir::Value* lhs = std::any_cast(ctx->lAndExp()->accept(this)); + if (lhs->GetType()->IsInt1()) { + lhs = builder_.CreateZext(lhs, module_.GetContext().NextTemp()); + } + ir::Value* lhs_cond = builder_.CreateCmp(ir::CmpOp::Ne, lhs, zero, module_.GetContext().NextTemp()); + builder_.CreateCondBr(lhs_cond, rhs_bb, end_bb); + + builder_.SetInsertPoint(rhs_bb); + ir::Value* rhs = std::any_cast(ctx->condUnaryExp()->accept(this)); + if (rhs->GetType()->IsInt1()) { + rhs = builder_.CreateZext(rhs, module_.GetContext().NextTemp()); + } + ir::Value* rhs_cond = builder_.CreateCmp(ir::CmpOp::Ne, rhs, zero, module_.GetContext().NextTemp()); + ir::Value* rhs_res = builder_.CreateZext(rhs_cond, module_.GetContext().NextTemp()); + builder_.CreateStore(rhs_res, res_ptr); + builder_.CreateBr(end_bb); + + builder_.SetInsertPoint(end_bb); + return static_cast(builder_.CreateLoad(res_ptr, module_.GetContext().NextTemp())); +} + +std::any IRGenImpl::visitLOrExp(SysYParser::LOrExpContext* ctx) { + if (ctx->lAndExp() && ctx->lOrExp() == nullptr) { + return ctx->lAndExp()->accept(this); + } + + ir::AllocaInst* res_ptr = builder_.CreateAllocaI32(module_.GetContext().NextTemp()); + ir::Value* one = builder_.CreateConstInt(1); + builder_.CreateStore(one, res_ptr); + + ir::BasicBlock* rhs_bb = func_->CreateBlock(NextBlockName("lor_rhs")); + ir::BasicBlock* end_bb = func_->CreateBlock(NextBlockName("lor_end")); + + ir::Value* lhs = std::any_cast(ctx->lOrExp()->accept(this)); + ir::Value* zero = builder_.CreateConstInt(0); + if (lhs->GetType()->IsInt1()) { + lhs = builder_.CreateZext(lhs, module_.GetContext().NextTemp()); + } + ir::Value* lhs_cond = builder_.CreateCmp(ir::CmpOp::Eq, lhs, zero, module_.GetContext().NextTemp()); + builder_.CreateCondBr(lhs_cond, rhs_bb, end_bb); + + builder_.SetInsertPoint(rhs_bb); + ir::Value* rhs = std::any_cast(ctx->lAndExp()->accept(this)); + if (rhs->GetType()->IsInt1()) { + rhs = builder_.CreateZext(rhs, module_.GetContext().NextTemp()); + } + ir::Value* rhs_cond = builder_.CreateCmp(ir::CmpOp::Ne, rhs, zero, module_.GetContext().NextTemp()); + ir::Value* rhs_res = builder_.CreateZext(rhs_cond, module_.GetContext().NextTemp()); + builder_.CreateStore(rhs_res, res_ptr); + builder_.CreateBr(end_bb); + + builder_.SetInsertPoint(end_bb); + return static_cast(builder_.CreateLoad(res_ptr, module_.GetContext().NextTemp())); +} + +std::any IRGenImpl::visitCond(SysYParser::CondContext* ctx) { + if (!ctx || !ctx->lOrExp()) { + throw std::runtime_error(FormatError("irgen", "非法条件表达式")); + } + return ctx->lOrExp()->accept(this); } \ No newline at end of file diff --git a/src/irgen/IRGenStmt.cpp b/src/irgen/IRGenStmt.cpp index de6a857..e44bd0a 100644 --- a/src/irgen/IRGenStmt.cpp +++ b/src/irgen/IRGenStmt.cpp @@ -20,50 +20,133 @@ std::any IRGenImpl::visitStmt(SysYParser::StmtContext* ctx) { throw std::runtime_error(FormatError("irgen", "缺少语句")); } - // 检查是否是赋值语句:lVal ASSIGN exp SEMICOLON if (ctx->lVal() && ctx->ASSIGN()) { if (!ctx->exp()) { throw std::runtime_error(FormatError("irgen", "赋值语句缺少表达式")); } - - // 1. 计算右值表达式的值 ir::Value* rhs = EvalExpr(*ctx->exp()); - - // 2. 找到左值变量对应的存储槽位 auto* lval_ctx = ctx->lVal(); if (!lval_ctx || !lval_ctx->ID()) { throw std::runtime_error(FormatError("irgen", "当前仅支持普通整型变量赋值")); } - const auto* decl = sema_.ResolveObjectUse(lval_ctx); if (!decl) { throw std::runtime_error( - FormatError("irgen", - "变量使用缺少语义绑定:" + lval_ctx->ID()->getText())); + FormatError("irgen", "变量使用缺少语义绑定:" + lval_ctx->ID()->getText())); } - std::string var_name = lval_ctx->ID()->getText(); auto it = storage_map_.find(var_name); if (it == storage_map_.end()) { throw std::runtime_error( - FormatError("irgen", - "变量声明缺少存储槽位:" + var_name)); + FormatError("irgen", "变量声明缺少存储槽位:" + var_name)); } - - // 3. 生成 store 指令 builder_.CreateStore(rhs, it->second); return BlockFlow::Continue; } - // 检查是否是 return 语句:RETURN exp? SEMICOLON + if (ctx->IF()) { + ir::Value* cond_val = std::any_cast(ctx->cond()->accept(this)); + // cond_val must be i1, if it's not we need to check if it's != 0 + if (cond_val->GetType()->IsInt32()) { + ir::Value* zero = builder_.CreateConstInt(0); + cond_val = builder_.CreateCmp(ir::CmpOp::Ne, cond_val, zero, module_.GetContext().NextTemp()); + } + + ir::BasicBlock* then_bb = func_->CreateBlock(NextBlockName("if_then")); + ir::BasicBlock* else_bb = ctx->ELSE() ? func_->CreateBlock(NextBlockName("if_else")) : nullptr; + ir::BasicBlock* merge_bb = func_->CreateBlock(NextBlockName("if_merge")); + + builder_.CreateCondBr(cond_val, then_bb, else_bb ? else_bb : merge_bb); + + builder_.SetInsertPoint(then_bb); + auto then_flow = std::any_cast(ctx->stmt(0)->accept(this)); + if (then_flow == BlockFlow::Continue) { + builder_.CreateBr(merge_bb); + } + + if (ctx->ELSE()) { + builder_.SetInsertPoint(else_bb); + auto else_flow = std::any_cast(ctx->stmt(1)->accept(this)); + if (else_flow == BlockFlow::Continue) { + builder_.CreateBr(merge_bb); + } + } + + builder_.SetInsertPoint(merge_bb); + return BlockFlow::Continue; + } + + if (ctx->WHILE()) { + ir::BasicBlock* cond_bb = func_->CreateBlock(NextBlockName("while_cond")); + ir::BasicBlock* body_bb = func_->CreateBlock(NextBlockName("while_body")); + ir::BasicBlock* exit_bb = func_->CreateBlock(NextBlockName("while_exit")); + + builder_.CreateBr(cond_bb); + builder_.SetInsertPoint(cond_bb); + + ir::Value* cond_val = std::any_cast(ctx->cond()->accept(this)); + if (cond_val->GetType()->IsInt32()) { + ir::Value* zero = builder_.CreateConstInt(0); + cond_val = builder_.CreateCmp(ir::CmpOp::Ne, cond_val, zero, module_.GetContext().NextTemp()); + } + builder_.CreateCondBr(cond_val, body_bb, exit_bb); + + builder_.SetInsertPoint(body_bb); + ir::BasicBlock* old_cond = current_loop_cond_bb_; + ir::BasicBlock* old_exit = current_loop_exit_bb_; + current_loop_cond_bb_ = cond_bb; + current_loop_exit_bb_ = exit_bb; + + auto body_flow = std::any_cast(ctx->stmt(0)->accept(this)); + if (body_flow == BlockFlow::Continue) { + builder_.CreateBr(cond_bb); + } + + current_loop_cond_bb_ = old_cond; + current_loop_exit_bb_ = old_exit; + + builder_.SetInsertPoint(exit_bb); + return BlockFlow::Continue; + } + + if (ctx->BREAK()) { + if (!current_loop_exit_bb_) { + throw std::runtime_error(FormatError("irgen", "break 必须在循环内")); + } + builder_.CreateBr(current_loop_exit_bb_); + return BlockFlow::Terminated; + } + + if (ctx->CONTINUE()) { + if (!current_loop_cond_bb_) { + throw std::runtime_error(FormatError("irgen", "continue 必须在循环内")); + } + builder_.CreateBr(current_loop_cond_bb_); + return BlockFlow::Terminated; + } + if (ctx->RETURN()) { - if (!ctx->exp()) { - throw std::runtime_error(FormatError("irgen", "return 缺少表达式")); + if (ctx->exp()) { + ir::Value* v = EvalExpr(*ctx->exp()); + builder_.CreateRet(v); + } else { + throw std::runtime_error(FormatError("irgen", "暂不支持 void return")); } - ir::Value* v = EvalExpr(*ctx->exp()); - builder_.CreateRet(v); return BlockFlow::Terminated; } + if (ctx->block()) { + return ctx->block()->accept(this); + } + + if (ctx->exp()) { + EvalExpr(*ctx->exp()); + return BlockFlow::Continue; + } + + if (ctx->SEMICOLON()) { + return BlockFlow::Continue; + } + throw std::runtime_error(FormatError("irgen", "暂不支持的语句类型")); } diff --git a/src/sem/Sema.cpp b/src/sem/Sema.cpp index fc73f9d..95f0629 100644 --- a/src/sem/Sema.cpp +++ b/src/sem/Sema.cpp @@ -462,7 +462,7 @@ class SemaVisitor final : public SysYBaseVisitor { if (!ctx) { ThrowSemaError(ctx, "非法关系表达式"); } - if (ctx->addExp()) { + if (ctx->relExp() == nullptr) { return EvalExpr(*ctx->addExp()); } ExprInfo lhs = EvalExpr(*ctx->relExp()); @@ -474,7 +474,7 @@ class SemaVisitor final : public SysYBaseVisitor { if (!ctx) { ThrowSemaError(ctx, "非法相等表达式"); } - if (ctx->relExp()) { + if (ctx->eqExp() == nullptr) { return EvalExpr(*ctx->relExp()); } ExprInfo lhs = EvalExpr(*ctx->eqExp()); @@ -504,7 +504,7 @@ class SemaVisitor final : public SysYBaseVisitor { if (!ctx) { ThrowSemaError(ctx, "非法逻辑与表达式"); } - if (ctx->condUnaryExp()) { + if (ctx->lAndExp() == nullptr) { return EvalExpr(*ctx->condUnaryExp()); } ExprInfo lhs = EvalExpr(*ctx->lAndExp()); @@ -516,7 +516,7 @@ class SemaVisitor final : public SysYBaseVisitor { if (!ctx) { ThrowSemaError(ctx, "非法逻辑或表达式"); } - if (ctx->lAndExp()) { + if (ctx->lOrExp() == nullptr) { return EvalExpr(*ctx->lAndExp()); } ExprInfo lhs = EvalExpr(*ctx->lOrExp());