Skip to content

Commit a9cf0f5

Browse files
committed
Feature: Allocate and store value in local variable on stack
1 parent 30ab82f commit a9cf0f5

2 files changed

Lines changed: 24 additions & 7 deletions

File tree

src/Backend/LLVM/index.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,14 @@ export function passReturnStatement(parent: ReturnStatement, ctx: Context, build
3333
);
3434
}
3535

36+
if (parent.argument.type === 'BinaryExpression') {
37+
return builder.createRet(
38+
buildFromBinaryExpression(ctx, parent.argument, builder)
39+
);
40+
}
41+
3642
throw new Error(
37-
`Unsupported ReturnStatement, only return without value is supported`
43+
`Unsupported ReturnStatement, unexpected: "${parent.argument.type}"`
3844
);
3945
}
4046

@@ -55,7 +61,7 @@ export function passFunctionDeclaration(parent: FunctionDeclaration, ctx: Contex
5561

5662
switch (parent.returnType.typeAnnotation.type) {
5763
case 'TSNumberKeyword':
58-
returnType = llvm.Type.getInt32Ty(ctx.llvmContext);
64+
returnType = llvm.Type.getInt32PtrTy(ctx.llvmContext);
5965
break;
6066
default:
6167
throw Error(
@@ -157,10 +163,22 @@ export function passVariableDeclaration(block: VariableDeclaration, ctx: Context
157163
const declaration = block.declarations[0];
158164

159165
if (declaration.init) {
160-
const right = buildFromExpression(declaration.init, ctx, builder);
166+
const defaultValue = buildFromExpression(declaration.init, ctx, builder);
161167

162168
if (declaration.id.type === 'Identifier') {
163-
ctx.variables.set(declaration.id.name, right);
169+
const allocate = builder.createAlloca(
170+
llvm.Type.getInt32Ty(ctx.llvmContext),
171+
undefined,
172+
declaration.id.name
173+
);
174+
175+
builder.createStore(
176+
defaultValue,
177+
allocate,
178+
false
179+
);
180+
181+
ctx.variables.set(declaration.id.name, allocate);
164182
}
165183

166184
return;

src/Frontend/TypeScript/index.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@ const example = `
55
function doMath(): number {
66
const a = 1;
77
const b = 2;
8-
const c = a + b;
9-
10-
return c;
8+
9+
return a;
1110
}
1211
1312
doMath();

0 commit comments

Comments
 (0)