diff --git a/examples/ir_test.psl b/examples/ir_test.psl index 95af5b4..0780ec9 100644 --- a/examples/ir_test.psl +++ b/examples/ir_test.psl @@ -1,7 +1,8 @@ -func test(x: f32) -> f32: - foreign func sin(x: f32) -> f32 - let pi = 3.1415926535 - return sin(pi * x) +func print(c: u8): + foreign func putchar(c: i32) -> i32 + putchar(c as i32) -let myfunc = test -let x = myfunc(7.5) +mut a = 10ub +let b = a +a = 11ub +print(b) diff --git a/libs/ir/include/pslang/ir/node.hpp b/libs/ir/include/pslang/ir/node.hpp index 0ab7071..ec999cb 100644 --- a/libs/ir/include/pslang/ir/node.hpp +++ b/libs/ir/include/pslang/ir/node.hpp @@ -20,6 +20,11 @@ namespace pslang::ir ast::literal value; }; + struct copy + { + node_ref source; + }; + struct unary_operation { ast::unary_operation_type type; @@ -94,6 +99,7 @@ namespace pslang::ir using instruction = std::variant< nop, literal, + copy, unary_operation, binary_operation, cast_operation, diff --git a/libs/ir/source/compiler.cpp b/libs/ir/source/compiler.cpp index 0660438..04f92cc 100644 --- a/libs/ir/source/compiler.cpp +++ b/libs/ir/source/compiler.cpp @@ -225,8 +225,7 @@ namespace pslang::ir node_ref apply(ast::expression_ptr const & node) { - apply(*node); - return last(); + return apply(*node); } node_ref apply(ast::assignment const & node) @@ -239,9 +238,18 @@ namespace pslang::ir node_ref apply(ast::variable_declaration const & node) { - apply(*node.initializer); - lcontext.scopes.back().variables[node.name] = last(); - return last(); + auto before = last(); + auto result = apply(*node.initializer); + if (result == before) + { + // Evaluating variable initializer didn't produce any nodes + // It must have been just a reference to another variable or smth like that + // Introduce a copy node to prevent accidental variable coalescing + mcontext.nodes.emplace_back(copy{result}); + result = last(); + } + lcontext.scopes.back().variables[node.name] = result; + return result; } node_ref apply(ast::if_chain const & node) diff --git a/libs/ir/source/print.cpp b/libs/ir/source/print.cpp index c338303..665febc 100644 --- a/libs/ir/source/print.cpp +++ b/libs/ir/source/print.cpp @@ -190,6 +190,11 @@ namespace pslang::ir std::visit(print_literal_visitor{out}, instruction.value); } + void operator()(copy const & instruction) + { + out << "copy $" << get_index(instruction.source); + } + void operator()(unary_operation const & instruction) { print(out, instruction.type);