1439 lines
49 KiB
C#
1439 lines
49 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Text;
|
|
using NubLang.Tokenization;
|
|
using NubLang.TypeChecking;
|
|
using NubLang.TypeChecking.Node;
|
|
|
|
namespace NubLang.Generation.QBE;
|
|
|
|
public class QBEGenerator
|
|
{
|
|
private readonly QBEWriter _writer;
|
|
private readonly TypedModule _module;
|
|
private readonly IReadOnlyDictionary<string, ModuleSignature> _moduleSignatures;
|
|
|
|
private readonly List<CStringLiteral> _cStringLiterals = [];
|
|
private readonly List<StringLiteral> _stringLiterals = [];
|
|
private readonly Stack<string> _breakLabels = [];
|
|
private readonly Stack<string> _continueLabels = [];
|
|
private int _tmpIndex;
|
|
private int _labelIndex;
|
|
private int _cStringLiteralIndex;
|
|
private int _stringLiteralIndex;
|
|
private bool _codeIsReachable = true;
|
|
|
|
public QBEGenerator(TypedModule module, IReadOnlyDictionary<string, ModuleSignature> moduleSignatures)
|
|
{
|
|
_module = module;
|
|
_moduleSignatures = moduleSignatures;
|
|
_writer = new QBEWriter();
|
|
}
|
|
|
|
public string Emit()
|
|
{
|
|
_cStringLiterals.Clear();
|
|
_stringLiterals.Clear();
|
|
_breakLabels.Clear();
|
|
_continueLabels.Clear();
|
|
_tmpIndex = 0;
|
|
_labelIndex = 0;
|
|
_cStringLiteralIndex = 0;
|
|
_stringLiteralIndex = 0;
|
|
_codeIsReachable = true;
|
|
|
|
foreach (var (module, signature) in _moduleSignatures)
|
|
{
|
|
foreach (var structType in signature.StructTypes)
|
|
{
|
|
EmitStructType(module, structType);
|
|
_writer.NewLine();
|
|
}
|
|
}
|
|
|
|
foreach (var structDef in _module.Definitions.OfType<StructNode>())
|
|
{
|
|
EmitStructDefinition(structDef);
|
|
_writer.NewLine();
|
|
}
|
|
|
|
foreach (var funcDef in _module.Definitions.OfType<FuncNode>())
|
|
{
|
|
EmitFuncDefinition(funcDef);
|
|
_writer.NewLine();
|
|
}
|
|
|
|
// foreach (var structDef in _module.Definitions.OfType<StructNode>().Where(x => x.InterfaceImplementations.Count > 0))
|
|
// {
|
|
// _writer.Write($"data {StructVtableName(_module.Name, structDef.Name)} = {{ ");
|
|
//
|
|
// foreach (var interfaceImplementation in structDef.InterfaceImplementations)
|
|
// {
|
|
// var interfaceDef = _definitionTable.LookupInterface(interfaceImplementation.Name);
|
|
// foreach (var func in interfaceDef.Functions)
|
|
// {
|
|
// _writer.Write($"l {StructFuncName(_module.Name, structDef.Name, func.Name)}, ");
|
|
// }
|
|
// }
|
|
//
|
|
// _writer.WriteLine("}");
|
|
// }
|
|
|
|
foreach (var cStringLiteral in _cStringLiterals)
|
|
{
|
|
_writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}");
|
|
}
|
|
|
|
foreach (var stringLiteral in _stringLiterals)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes(stringLiteral.Value).Select(b => $"b {b}");
|
|
_writer.WriteLine($"data {stringLiteral.Name} = {{ l {stringLiteral.Value.Length}, {string.Join(", ", bytes)} }}");
|
|
}
|
|
|
|
return _writer.ToString();
|
|
}
|
|
|
|
private static string QBEAssign(TypeNode type)
|
|
{
|
|
if (type.IsSimpleType(out var simpleType, out _))
|
|
{
|
|
return simpleType.StorageSize switch
|
|
{
|
|
StorageSize.I8 or StorageSize.U8 or StorageSize.I16 or StorageSize.U16 or StorageSize.I32 or StorageSize.U32 => "=w",
|
|
StorageSize.I64 or StorageSize.U64 => "=l",
|
|
StorageSize.F32 => "=s",
|
|
StorageSize.F64 => "=d",
|
|
_ => throw new ArgumentOutOfRangeException(nameof(simpleType.StorageSize))
|
|
};
|
|
}
|
|
|
|
return "=l";
|
|
}
|
|
|
|
private void EmitStore(TypeNode type, string value, string destination)
|
|
{
|
|
string store;
|
|
|
|
if (type.IsSimpleType(out var simpleType, out _))
|
|
{
|
|
store = simpleType.StorageSize switch
|
|
{
|
|
StorageSize.I8 or StorageSize.U8 => "storeb",
|
|
StorageSize.I16 or StorageSize.U16 => "storeh",
|
|
StorageSize.I32 or StorageSize.U32 => "storew",
|
|
StorageSize.I64 or StorageSize.U64 => "storel",
|
|
StorageSize.F32 => "stores",
|
|
StorageSize.F64 => "stored",
|
|
_ => throw new ArgumentOutOfRangeException(nameof(simpleType.StorageSize))
|
|
};
|
|
}
|
|
else
|
|
{
|
|
store = "storel";
|
|
}
|
|
|
|
_writer.Indented($"{store} {value}, {destination}");
|
|
}
|
|
|
|
private string EmitLoad(TypeNode type, string from)
|
|
{
|
|
string load;
|
|
|
|
if (type.IsSimpleType(out var simpleType, out _))
|
|
{
|
|
load = simpleType.StorageSize switch
|
|
{
|
|
StorageSize.I64 or StorageSize.U64 => "loadl",
|
|
StorageSize.I32 or StorageSize.U32 => "loadw",
|
|
StorageSize.I16 => "loadsh",
|
|
StorageSize.I8 => "loadsb",
|
|
StorageSize.U16 => "loaduh",
|
|
StorageSize.U8 => "loadub",
|
|
StorageSize.F64 => "loadd",
|
|
StorageSize.F32 => "loads",
|
|
_ => throw new ArgumentOutOfRangeException(nameof(simpleType.StorageSize))
|
|
};
|
|
}
|
|
else
|
|
{
|
|
load = "loadl";
|
|
}
|
|
|
|
var into = TmpName();
|
|
|
|
_writer.Indented($"{into} {QBEAssign(type)} {load} {from}");
|
|
|
|
return into;
|
|
}
|
|
|
|
private void EmitMemset(string destination, int value, string length)
|
|
{
|
|
var count = TmpName();
|
|
_writer.Indented($"{count} =l copy 0");
|
|
|
|
var loopLabel = LabelName();
|
|
_writer.WriteLine(loopLabel);
|
|
|
|
var continueLabel = LabelName();
|
|
var doneLabel = LabelName();
|
|
var condition = TmpName();
|
|
_writer.Indented($"{condition} =w cultl {count}, {length}");
|
|
_writer.Indented($"jnz {condition}, {continueLabel}, {doneLabel}");
|
|
|
|
_writer.WriteLine(continueLabel);
|
|
|
|
var destinationAddress = TmpName();
|
|
_writer.Indented($"{destinationAddress} =l add {destination}, {count}");
|
|
|
|
_writer.Indented($"storeb {value}, {destinationAddress}");
|
|
|
|
_writer.Indented($"{count} =l add {count}, 1");
|
|
_writer.Indented($"jmp {loopLabel}");
|
|
|
|
_writer.WriteLine(doneLabel);
|
|
}
|
|
|
|
private void EmitMemcpy(string source, string destination, string length)
|
|
{
|
|
var count = TmpName();
|
|
_writer.Indented($"{count} =l copy 0");
|
|
|
|
var loopLabel = LabelName();
|
|
_writer.WriteLine(loopLabel);
|
|
|
|
var continueLabel = LabelName();
|
|
var doneLabel = LabelName();
|
|
var condition = TmpName();
|
|
_writer.Indented($"{condition} =w cultl {count}, {length}");
|
|
_writer.Indented($"jnz {condition}, {continueLabel}, {doneLabel}");
|
|
|
|
_writer.WriteLine(continueLabel);
|
|
|
|
var sourceAddress = TmpName();
|
|
_writer.Indented($"{sourceAddress} =l add {source}, {count}");
|
|
|
|
var destinationAddress = TmpName();
|
|
_writer.Indented($"{destinationAddress} =l add {destination}, {count}");
|
|
|
|
var value = TmpName();
|
|
_writer.Indented($"{value} =w loadub {sourceAddress}");
|
|
_writer.Indented($"storeb {value}, {destinationAddress}");
|
|
|
|
_writer.Indented($"{count} =l add {count}, 1");
|
|
_writer.Indented($"jmp {loopLabel}");
|
|
|
|
_writer.WriteLine(doneLabel);
|
|
}
|
|
|
|
private string EmitArraySizeInBytes(ArrayTypeNode type, string array)
|
|
{
|
|
var size = TmpName();
|
|
_writer.Indented($"{size} =l loadl {array}");
|
|
_writer.Indented($"{size} =l mul {size}, {SizeOf(type.ElementType)}");
|
|
_writer.Indented($"{size} =l add {size}, 8");
|
|
return size;
|
|
}
|
|
|
|
private string EmitCStringSizeInBytes(string cstring)
|
|
{
|
|
var count = TmpName();
|
|
_writer.Indented($"{count} =l copy 0");
|
|
|
|
var loopLabel = LabelName();
|
|
_writer.WriteLine(loopLabel);
|
|
|
|
var address = TmpName();
|
|
_writer.Indented($"{address} =l add {cstring}, {count}");
|
|
|
|
var value = TmpName();
|
|
_writer.Indented($"{value} =w loadub {address}");
|
|
|
|
var notZeroLabel = LabelName();
|
|
var zeroLabel = LabelName();
|
|
_writer.Indented($"jnz {value}, {notZeroLabel}, {zeroLabel}");
|
|
_writer.WriteLine(notZeroLabel);
|
|
_writer.Indented($"{count} =l add {count}, 1");
|
|
_writer.Indented($"jmp {loopLabel}");
|
|
_writer.WriteLine(zeroLabel);
|
|
|
|
return count;
|
|
}
|
|
|
|
private string EmitStringSizeInBytes(string nubstring)
|
|
{
|
|
var size = TmpName();
|
|
_writer.Indented($"{size} =l loadl {nubstring}");
|
|
_writer.Indented($"{size} =l add {size}, 8");
|
|
return size;
|
|
}
|
|
|
|
private void EmitCopyInto(ExpressionNode source, string destination)
|
|
{
|
|
// Simple types are passed in registers and can therefore just be stored
|
|
if (source.Type.IsSimpleType(out var simpleType, out var complexType))
|
|
{
|
|
var value = EmitExpression(source);
|
|
EmitStore(simpleType, value, destination);
|
|
return;
|
|
}
|
|
|
|
// Structs and interfaces has known sizes at compile time
|
|
if (complexType is StructTypeNode or InterfaceTypeNode)
|
|
{
|
|
var value = EmitExpression(source);
|
|
_writer.Indented($"blit {value}, {destination}, {SizeOf(complexType)}");
|
|
}
|
|
// The rest of the complex types has unknown sizes
|
|
else
|
|
{
|
|
var value = EmitExpression(source);
|
|
var size = complexType switch
|
|
{
|
|
ArrayTypeNode arrayType => EmitArraySizeInBytes(arrayType, value),
|
|
CStringTypeNode => EmitCStringSizeInBytes(value),
|
|
StringTypeNode => EmitStringSizeInBytes(value),
|
|
_ => throw new ArgumentOutOfRangeException(nameof(source.Type))
|
|
};
|
|
|
|
var buffer = TmpName();
|
|
_writer.Indented($"{buffer} =l alloc8 {size}");
|
|
EmitMemcpy(value, buffer, size);
|
|
EmitStore(complexType, buffer, destination);
|
|
}
|
|
}
|
|
|
|
private string EmitCopy(ExpressionNode source)
|
|
{
|
|
// Allowlist for types which are safe to not copy
|
|
if (source is ArrayInitializerNode or StructInitializerNode or ConvertToInterfaceNode or LiteralNode)
|
|
{
|
|
return EmitExpression(source);
|
|
}
|
|
|
|
// Simple types are passed in registers and therefore always copied
|
|
if (source.Type.IsSimpleType(out _, out var complexType))
|
|
{
|
|
return EmitExpression(source);
|
|
}
|
|
|
|
// For the rest, we figure out the size of the type and shallow copy them
|
|
var value = EmitExpression(source);
|
|
var destination = TmpName();
|
|
|
|
// Structs and interfaces has known sizes at compile time
|
|
if (complexType is StructTypeNode or InterfaceTypeNode)
|
|
{
|
|
var size = SizeOf(complexType);
|
|
_writer.Indented($"{destination} =l alloc8 {size}");
|
|
_writer.Indented($"blit {value}, {destination}, {size}");
|
|
}
|
|
// The rest of the complex types has unknown sizes
|
|
else
|
|
{
|
|
var size = complexType switch
|
|
{
|
|
ArrayTypeNode arrayType => EmitArraySizeInBytes(arrayType, value),
|
|
CStringTypeNode => EmitCStringSizeInBytes(value),
|
|
StringTypeNode => EmitStringSizeInBytes(value),
|
|
_ => throw new ArgumentOutOfRangeException(nameof(source.Type))
|
|
};
|
|
|
|
_writer.Indented($"{destination} =l alloc8 {size}");
|
|
EmitMemcpy(value, destination, size);
|
|
}
|
|
|
|
return destination;
|
|
}
|
|
|
|
// Utility to create QBE type names for function parameters and return types
|
|
private string FuncQBETypeName(TypeNode type)
|
|
{
|
|
if (type.IsSimpleType(out var simpleType, out var complexType))
|
|
{
|
|
return simpleType.StorageSize switch
|
|
{
|
|
StorageSize.I64 or StorageSize.U64 => "l",
|
|
StorageSize.I32 or StorageSize.U32 => "w",
|
|
StorageSize.I16 => "sh",
|
|
StorageSize.I8 => "sb",
|
|
StorageSize.U16 => "uh",
|
|
StorageSize.U8 => "ub",
|
|
StorageSize.F64 => "d",
|
|
StorageSize.F32 => "s",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
};
|
|
}
|
|
|
|
if (complexType is StructTypeNode structType)
|
|
{
|
|
return StructTypeName(structType.Module, structType.Name);
|
|
}
|
|
|
|
return "l";
|
|
}
|
|
|
|
private void EmitFuncDefinition(FuncNode funcDef)
|
|
{
|
|
if (funcDef.Body == null) return;
|
|
|
|
_labelIndex = 0;
|
|
_tmpIndex = 0;
|
|
|
|
_writer.Write("export function ");
|
|
|
|
if (funcDef.Signature.ReturnType is not VoidTypeNode)
|
|
{
|
|
_writer.Write(FuncQBETypeName(funcDef.Signature.ReturnType) + ' ');
|
|
}
|
|
|
|
_writer.Write(FuncName(_module.Name, funcDef.Name));
|
|
|
|
_writer.Write("(");
|
|
foreach (var parameter in funcDef.Signature.Parameters)
|
|
{
|
|
_writer.Write(FuncQBETypeName(parameter.Type) + $" %{parameter.Name}");
|
|
}
|
|
|
|
_writer.WriteLine(") {");
|
|
_writer.WriteLine("@start");
|
|
|
|
EmitBlock(funcDef.Body);
|
|
|
|
// Implicit return for void functions if no explicit return has been set
|
|
if (funcDef.Signature.ReturnType is VoidTypeNode && funcDef.Body.Statements.LastOrDefault() is not ReturnNode)
|
|
{
|
|
_writer.Indented("ret");
|
|
}
|
|
|
|
_writer.WriteLine("}");
|
|
}
|
|
|
|
private void EmitStructDefinition(StructNode structDef)
|
|
{
|
|
var type = TypeResolver.ResolveStructType(_module.Name, structDef.Name, _moduleSignatures);
|
|
|
|
// _writer.WriteLine($"export function {StructCtorName(_module.Name, structDef.Name)}() {{");
|
|
// _writer.WriteLine("@start");
|
|
// _writer.Indented($"%struct =l alloc8 {SizeOf(type)}");
|
|
// // todo(nub31): Finish constructor
|
|
// _writer.Indented("ret %struct");
|
|
// _writer.WriteLine("}");
|
|
|
|
foreach (var function in structDef.Functions)
|
|
{
|
|
_labelIndex = 0;
|
|
_tmpIndex = 0;
|
|
|
|
_writer.NewLine();
|
|
_writer.Write("export function ");
|
|
|
|
if (function.Signature.ReturnType is not VoidTypeNode)
|
|
{
|
|
_writer.Write(FuncQBETypeName(function.Signature.ReturnType) + ' ');
|
|
}
|
|
|
|
_writer.Write(StructFuncName(_module.Name, structDef.Name, function.Name));
|
|
|
|
_writer.Write("(l %this, ");
|
|
foreach (var parameter in function.Signature.Parameters)
|
|
{
|
|
_writer.Write(FuncQBETypeName(parameter.Type) + $" %{parameter.Name}, ");
|
|
}
|
|
|
|
_writer.WriteLine(") {");
|
|
_writer.WriteLine("@start");
|
|
|
|
EmitBlock(function.Body);
|
|
|
|
// Implicit return for void functions if no explicit return has been set
|
|
if (function.Signature.ReturnType is VoidTypeNode && function.Body.Statements.LastOrDefault() is not ReturnNode)
|
|
{
|
|
_writer.Indented("ret");
|
|
}
|
|
|
|
_writer.WriteLine("}");
|
|
}
|
|
}
|
|
|
|
private void EmitStructType(string module, StructTypeNode structType)
|
|
{
|
|
_writer.WriteLine($"type {StructTypeName(module, structType.Name)} = {{ ");
|
|
|
|
foreach (var field in structType.Fields)
|
|
{
|
|
_writer.Indented($"{StructDefQBEType(field.Type)},");
|
|
}
|
|
|
|
_writer.WriteLine("}");
|
|
return;
|
|
|
|
string StructDefQBEType(TypeNode type)
|
|
{
|
|
if (type.IsSimpleType(out var simpleType, out var complexType))
|
|
{
|
|
return simpleType.StorageSize switch
|
|
{
|
|
StorageSize.I64 or StorageSize.U64 => "l",
|
|
StorageSize.I32 or StorageSize.U32 => "w",
|
|
StorageSize.I16 or StorageSize.U16 => "h",
|
|
StorageSize.I8 or StorageSize.U8 => "b",
|
|
StorageSize.F64 => "d",
|
|
StorageSize.F32 => "s",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
};
|
|
}
|
|
|
|
if (complexType is StructTypeNode childStructType)
|
|
{
|
|
return StructTypeName(childStructType.Module, childStructType.Name);
|
|
}
|
|
|
|
return "l";
|
|
}
|
|
}
|
|
|
|
private void EmitBlock(BlockNode block)
|
|
{
|
|
foreach (var statement in block.Statements)
|
|
{
|
|
if (_codeIsReachable)
|
|
{
|
|
EmitStatement(statement);
|
|
}
|
|
}
|
|
|
|
_codeIsReachable = true;
|
|
}
|
|
|
|
private void EmitStatement(StatementNode statement)
|
|
{
|
|
// var tokens = statement.Tokens.ToArray();
|
|
// if (tokens.Length != 0)
|
|
// {
|
|
// _writer.WriteLine($"dbgloc {tokens[0].FileSpan.Span.Start.Line}");
|
|
// }
|
|
|
|
switch (statement)
|
|
{
|
|
case AssignmentNode assignment:
|
|
EmitAssignment(assignment);
|
|
break;
|
|
case BreakNode:
|
|
EmitBreak();
|
|
break;
|
|
case ContinueNode:
|
|
EmitContinue();
|
|
break;
|
|
case IfNode ifStatement:
|
|
EmitIf(ifStatement);
|
|
break;
|
|
case ReturnNode @return:
|
|
EmitReturn(@return);
|
|
break;
|
|
case StatementExpressionNode statementExpression:
|
|
EmitExpression(statementExpression.Expression);
|
|
break;
|
|
case VariableDeclarationNode variableDeclaration:
|
|
EmitVariableDeclaration(variableDeclaration);
|
|
break;
|
|
case WhileNode whileStatement:
|
|
EmitWhile(whileStatement);
|
|
break;
|
|
default:
|
|
throw new ArgumentOutOfRangeException(nameof(statement));
|
|
}
|
|
}
|
|
|
|
private void EmitAssignment(AssignmentNode assignment)
|
|
{
|
|
EmitCopyInto(assignment.Value, EmitAddressOfLValue(assignment.Target));
|
|
}
|
|
|
|
private void EmitBreak()
|
|
{
|
|
_writer.Indented($"jmp {_breakLabels.Peek()}");
|
|
_codeIsReachable = false;
|
|
}
|
|
|
|
private void EmitContinue()
|
|
{
|
|
_writer.Indented($"jmp {_continueLabels.Peek()}");
|
|
_codeIsReachable = false;
|
|
}
|
|
|
|
private void EmitIf(IfNode ifStatement)
|
|
{
|
|
var trueLabel = LabelName();
|
|
var falseLabel = LabelName();
|
|
var endLabel = LabelName();
|
|
|
|
var result = EmitExpression(ifStatement.Condition);
|
|
_writer.Indented($"jnz {result}, {trueLabel}, {falseLabel}");
|
|
_writer.WriteLine(trueLabel);
|
|
EmitBlock(ifStatement.Body);
|
|
_writer.Indented($"jmp {endLabel}");
|
|
_writer.WriteLine(falseLabel);
|
|
if (ifStatement.Else.HasValue)
|
|
{
|
|
ifStatement.Else.Value.Match(EmitIf, EmitBlock);
|
|
}
|
|
|
|
_writer.WriteLine(endLabel);
|
|
}
|
|
|
|
private void EmitReturn(ReturnNode @return)
|
|
{
|
|
if (@return.Value.HasValue)
|
|
{
|
|
var result = EmitExpression(@return.Value.Value);
|
|
_writer.Indented($"ret {result}");
|
|
}
|
|
else
|
|
{
|
|
_writer.Indented("ret");
|
|
}
|
|
}
|
|
|
|
private void EmitVariableDeclaration(VariableDeclarationNode variableDeclaration)
|
|
{
|
|
var name = $"%{variableDeclaration.Name}";
|
|
_writer.Indented($"{name} =l alloc8 {SizeOf(variableDeclaration.Type)}");
|
|
|
|
if (variableDeclaration.Assignment.HasValue)
|
|
{
|
|
EmitCopyInto(variableDeclaration.Assignment.Value, name);
|
|
}
|
|
}
|
|
|
|
private void EmitWhile(WhileNode whileStatement)
|
|
{
|
|
var conditionLabel = LabelName();
|
|
var iterationLabel = LabelName();
|
|
var endLabel = LabelName();
|
|
|
|
_breakLabels.Push(endLabel);
|
|
_continueLabels.Push(conditionLabel);
|
|
|
|
_writer.Indented($"jmp {conditionLabel}");
|
|
_writer.WriteLine(iterationLabel);
|
|
EmitBlock(whileStatement.Body);
|
|
_writer.WriteLine(conditionLabel);
|
|
var result = EmitExpression(whileStatement.Condition);
|
|
_writer.Indented($"jnz {result}, {iterationLabel}, {endLabel}");
|
|
_writer.WriteLine(endLabel);
|
|
|
|
_continueLabels.Pop();
|
|
_breakLabels.Pop();
|
|
}
|
|
|
|
private string EmitExpression(ExpressionNode expression)
|
|
{
|
|
// var tokens = expression.Tokens.ToArray();
|
|
// if (tokens.Length != 0)
|
|
// {
|
|
// _writer.WriteLine($"dbgloc {tokens[0].FileSpan.Span.Start.Line}");
|
|
// }
|
|
|
|
return expression switch
|
|
{
|
|
ArrayInitializerNode arrayInitializer => EmitArrayInitializer(arrayInitializer),
|
|
StructInitializerNode structInitializer => EmitStructInitializer(structInitializer),
|
|
AddressOfNode addressOf => EmitAddressOf(addressOf),
|
|
DereferenceNode dereference => EmitDereference(dereference),
|
|
BinaryExpressionNode binary => EmitBinaryExpression(binary),
|
|
FuncCallNode funcCall => EmitFuncCall(funcCall),
|
|
InterfaceFuncCallNode interfaceFuncCall => EmitInterfaceFuncCall(interfaceFuncCall),
|
|
ConvertToInterfaceNode convertToInterface => EmitConvertToInterface(convertToInterface),
|
|
ConvertIntNode convertInt => EmitConvertInt(convertInt),
|
|
ConvertFloatNode convertFloat => EmitConvertFloat(convertFloat),
|
|
VariableIdentifierNode identifier => EmitVariableIdentifier(identifier),
|
|
FuncIdentifierNode funcIdentifier => EmitFuncIdentifier(funcIdentifier),
|
|
FuncParameterIdentifierNode funcParameterIdentifier => EmitParameterFuncIdentifier(funcParameterIdentifier),
|
|
LiteralNode literal => EmitLiteral(literal),
|
|
UnaryExpressionNode unaryExpression => EmitUnaryExpression(unaryExpression),
|
|
StructFieldAccessNode structFieldAccess => EmitStructFieldAccess(structFieldAccess),
|
|
StructFuncCallNode structFuncCall => EmitStructFuncCall(structFuncCall),
|
|
ArrayIndexAccessNode arrayIndex => EmitArrayIndexAccess(arrayIndex),
|
|
_ => throw new ArgumentOutOfRangeException(nameof(expression))
|
|
};
|
|
}
|
|
|
|
private string EmitFuncIdentifier(FuncIdentifierNode funcIdent)
|
|
{
|
|
// todo(nub31): Support for extern funcs
|
|
return FuncName(funcIdent.Module, funcIdent.Name);
|
|
}
|
|
|
|
private string EmitVariableIdentifier(VariableIdentifierNode variableIdent)
|
|
{
|
|
var address = EmitAddressOfVariableIdent(variableIdent);
|
|
|
|
return variableIdent.Type.IsSimpleType(out _, out _)
|
|
? EmitLoad(variableIdent.Type, address)
|
|
: address;
|
|
}
|
|
|
|
private string EmitParameterFuncIdentifier(FuncParameterIdentifierNode funcParameterIdent)
|
|
{
|
|
return "%" + funcParameterIdent.Name;
|
|
}
|
|
|
|
private string EmitArrayIndexAccess(ArrayIndexAccessNode arrayIndexAccess)
|
|
{
|
|
// var address = EmitAddressOfArrayIndexAccess(arrayIndexAccess);
|
|
// if (arrayIndexAccess.Type is StructTypeNode)
|
|
// {
|
|
// return address;
|
|
// }
|
|
//
|
|
// return EmitLoad(arrayIndexAccess.Type, address);
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
private string EmitArrayInitializer(ArrayInitializerNode arrayInitializer)
|
|
{
|
|
var capacity = EmitExpression(arrayInitializer.Capacity);
|
|
var elementSize = SizeOf(arrayInitializer.ElementType);
|
|
|
|
var capacityInBytes = TmpName();
|
|
_writer.Indented($"{capacityInBytes} =l mul {capacity}, {elementSize}");
|
|
var totalSize = TmpName();
|
|
_writer.Indented($"{totalSize} =l add {capacityInBytes}, 8");
|
|
|
|
var arrayPointer = TmpName();
|
|
_writer.Indented($"{arrayPointer} =l alloc8 {totalSize}");
|
|
_writer.Indented($"storel {capacity}, {arrayPointer}");
|
|
|
|
var dataPointer = TmpName();
|
|
_writer.Indented($"{dataPointer} =l add {arrayPointer}, 8");
|
|
EmitMemset(dataPointer, 0, capacityInBytes);
|
|
|
|
return arrayPointer;
|
|
}
|
|
|
|
private string EmitDereference(DereferenceNode dereference)
|
|
{
|
|
var address = EmitExpression(dereference.Expression);
|
|
if (dereference.Type is StructTypeNode)
|
|
{
|
|
return address;
|
|
}
|
|
|
|
return EmitLoad(dereference.Type, address);
|
|
}
|
|
|
|
private string EmitAddressOf(AddressOfNode addressOf)
|
|
{
|
|
return EmitAddressOfLValue(addressOf.LValue);
|
|
}
|
|
|
|
private string EmitAddressOfLValue(LValueExpressionNode addressOf)
|
|
{
|
|
return addressOf switch
|
|
{
|
|
ArrayIndexAccessNode arrayIndexAccess => EmitAddressOfArrayIndexAccess(arrayIndexAccess),
|
|
StructFieldAccessNode structFieldAccess => EmitAddressOfStructFieldAccess(structFieldAccess),
|
|
VariableIdentifierNode variableIdent => EmitAddressOfVariableIdent(variableIdent),
|
|
_ => throw new ArgumentOutOfRangeException(nameof(addressOf))
|
|
};
|
|
}
|
|
|
|
private string EmitAddressOfArrayIndexAccess(ArrayIndexAccessNode arrayIndexAccess)
|
|
{
|
|
var array = EmitExpression(arrayIndexAccess.Target);
|
|
var index = EmitExpression(arrayIndexAccess.Index);
|
|
|
|
var elementType = ((ArrayTypeNode)arrayIndexAccess.Target.Type).ElementType;
|
|
|
|
var offset = TmpName();
|
|
_writer.Indented($"{offset} =l mul {index}, {SizeOf(elementType)}");
|
|
_writer.Indented($"{offset} =l add {offset}, 8");
|
|
_writer.Indented($"{offset} =l add {array}, {offset}");
|
|
return offset;
|
|
}
|
|
|
|
private string EmitAddressOfStructFieldAccess(StructFieldAccessNode structFieldAccess)
|
|
{
|
|
var target = EmitExpression(structFieldAccess.Target);
|
|
|
|
var structType = TypeResolver.ResolveStructType(structFieldAccess.StructType.Module, structFieldAccess.StructType.Name, _moduleSignatures);
|
|
var offset = OffsetOf(structType, structFieldAccess.Field);
|
|
|
|
var address = TmpName();
|
|
_writer.Indented($"{address} =l add {target}, {offset}");
|
|
return address;
|
|
}
|
|
|
|
private string EmitAddressOfVariableIdent(VariableIdentifierNode variableIdent)
|
|
{
|
|
return "%" + variableIdent.Name;
|
|
}
|
|
|
|
private string EmitBinaryExpression(BinaryExpressionNode binaryExpression)
|
|
{
|
|
var left = EmitExpression(binaryExpression.Left);
|
|
var right = EmitExpression(binaryExpression.Right);
|
|
|
|
var outputName = TmpName();
|
|
|
|
var instruction = EmitBinaryInstructionForOperator(binaryExpression.Operator, binaryExpression.Left.Type);
|
|
|
|
_writer.Indented($"{outputName} {QBEAssign(binaryExpression.Left.Type)} {instruction} {left}, {right}");
|
|
return outputName;
|
|
}
|
|
|
|
private static string EmitBinaryInstructionForOperator(BinaryOperator op, TypeNode type)
|
|
{
|
|
return op switch
|
|
{
|
|
BinaryOperator.RightShift => type switch
|
|
{
|
|
IntTypeNode { Signed: true } => "sar",
|
|
IntTypeNode { Signed: false } => "shr",
|
|
_ => throw new NotSupportedException($"Right shift not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.BitwiseAnd => "and",
|
|
BinaryOperator.BitwiseOr => "or",
|
|
BinaryOperator.BitwiseXor => "xor",
|
|
BinaryOperator.LeftShift => "shl",
|
|
BinaryOperator.Divide => type switch
|
|
{
|
|
IntTypeNode { Signed: true } => "div",
|
|
IntTypeNode { Signed: false } => "udiv",
|
|
FloatTypeNode => "div",
|
|
_ => throw new NotSupportedException($"Division not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.Modulo => type switch
|
|
{
|
|
IntTypeNode { Signed: true } => "rem",
|
|
IntTypeNode { Signed: false } => "urem",
|
|
_ => throw new NotSupportedException($"Modulo not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.Plus => "add",
|
|
BinaryOperator.Minus => "sub",
|
|
BinaryOperator.Multiply => "mul",
|
|
BinaryOperator.Equal => type switch
|
|
{
|
|
IntTypeNode intType => intType.Width switch
|
|
{
|
|
<= 32 => "ceqw",
|
|
64 => "ceql",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
FloatTypeNode floatType => floatType.Width switch
|
|
{
|
|
32 => "ceqs",
|
|
64 => "ceqd",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
_ => throw new NotSupportedException($"Equality comparison not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.NotEqual => type switch
|
|
{
|
|
IntTypeNode intType => intType.Width switch
|
|
{
|
|
<= 32 => "cnew",
|
|
64 => "cnel",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
FloatTypeNode floatType => floatType.Width switch
|
|
{
|
|
32 => "cnes",
|
|
64 => "cned",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
_ => throw new NotSupportedException($"Inequality comparison not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.LessThan => type switch
|
|
{
|
|
IntTypeNode { Signed: true } intType => intType.Width switch
|
|
{
|
|
<= 32 => "csltw",
|
|
64 => "csltl",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
IntTypeNode { Signed: false } intType => intType.Width switch
|
|
{
|
|
<= 32 => "cultw",
|
|
64 => "cultl",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
FloatTypeNode floatType => floatType.Width switch
|
|
{
|
|
32 => "clts",
|
|
64 => "cltd",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
_ => throw new NotSupportedException($"Less than comparison not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.LessThanOrEqual => type switch
|
|
{
|
|
IntTypeNode { Signed: true } intType => intType.Width switch
|
|
{
|
|
<= 32 => "cslew",
|
|
64 => "cslel",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
IntTypeNode { Signed: false } intType => intType.Width switch
|
|
{
|
|
<= 32 => "culew",
|
|
64 => "culel",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
FloatTypeNode floatType => floatType.Width switch
|
|
{
|
|
32 => "cles",
|
|
64 => "cled",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
_ => throw new NotSupportedException($"Less than or equal comparison not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.GreaterThan => type switch
|
|
{
|
|
IntTypeNode { Signed: true } intType => intType.Width switch
|
|
{
|
|
<= 32 => "csgtw",
|
|
64 => "csgtl",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
IntTypeNode { Signed: false } intType => intType.Width switch
|
|
{
|
|
<= 32 => "cugtw",
|
|
64 => "cugtl",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
FloatTypeNode floatType => floatType.Width switch
|
|
{
|
|
32 => "cgts",
|
|
64 => "cgtd",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
_ => throw new NotSupportedException($"Greater than comparison not supported for type '{type}'")
|
|
},
|
|
BinaryOperator.GreaterThanOrEqual => type switch
|
|
{
|
|
IntTypeNode { Signed: true } intType => intType.Width switch
|
|
{
|
|
<= 32 => "csgew",
|
|
64 => "csgel",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
IntTypeNode { Signed: false } intType => intType.Width switch
|
|
{
|
|
<= 32 => "cugew",
|
|
64 => "cugel",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
FloatTypeNode floatType => floatType.Width switch
|
|
{
|
|
32 => "cges",
|
|
64 => "cged",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
_ => throw new NotSupportedException($"Greater than or equal comparison not supported for type '{type}'")
|
|
},
|
|
// todo(nub31): Implement short circuiting
|
|
BinaryOperator.LogicalAnd => "and",
|
|
BinaryOperator.LogicalOr => "or",
|
|
_ => throw new ArgumentOutOfRangeException(nameof(op))
|
|
};
|
|
}
|
|
|
|
private string EmitLiteral(LiteralNode literal)
|
|
{
|
|
switch (literal.Kind)
|
|
{
|
|
case LiteralKind.Integer:
|
|
{
|
|
if (literal.Type is FloatTypeNode { Width: 32 })
|
|
{
|
|
var value = float.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.SingleToInt32Bits(value);
|
|
return bits.ToString();
|
|
}
|
|
|
|
if (literal.Type is FloatTypeNode { Width: 64 })
|
|
{
|
|
var value = double.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.DoubleToInt64Bits(value);
|
|
return bits.ToString();
|
|
}
|
|
|
|
if (literal.Type is IntTypeNode)
|
|
{
|
|
return literal.Value;
|
|
}
|
|
|
|
break;
|
|
}
|
|
case LiteralKind.Float:
|
|
{
|
|
if (literal.Type is IntTypeNode)
|
|
{
|
|
return literal.Value.Split(".").First();
|
|
}
|
|
|
|
if (literal.Type is FloatTypeNode { Width: 32 })
|
|
{
|
|
var value = float.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.SingleToInt32Bits(value);
|
|
return bits.ToString();
|
|
}
|
|
|
|
if (literal.Type is FloatTypeNode { Width: 64 })
|
|
{
|
|
var value = double.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.DoubleToInt64Bits(value);
|
|
return bits.ToString();
|
|
}
|
|
|
|
break;
|
|
}
|
|
case LiteralKind.String:
|
|
{
|
|
if (literal.Type is StringTypeNode)
|
|
{
|
|
var stringLiteral = new StringLiteral(literal.Value, StringName());
|
|
_stringLiterals.Add(stringLiteral);
|
|
return stringLiteral.Name;
|
|
}
|
|
|
|
if (literal.Type is CStringTypeNode)
|
|
{
|
|
var cStringLiteral = new CStringLiteral(literal.Value, CStringName());
|
|
_cStringLiterals.Add(cStringLiteral);
|
|
return cStringLiteral.Name;
|
|
}
|
|
|
|
break;
|
|
}
|
|
case LiteralKind.Bool:
|
|
{
|
|
if (literal.Type is BoolTypeNode)
|
|
{
|
|
return bool.Parse(literal.Value) ? "1" : "0";
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
throw new NotSupportedException($"Cannot create literal of kind '{literal.Kind}' for type {literal.Type}");
|
|
}
|
|
|
|
private string EmitStructInitializer(StructInitializerNode structInitializer)
|
|
{
|
|
var destination = TmpName();
|
|
var size = SizeOf(structInitializer.StructType);
|
|
_writer.Indented($"{destination} =l alloc8 {size}");
|
|
|
|
foreach (var (field, value) in structInitializer.Initializers)
|
|
{
|
|
var offset = TmpName();
|
|
_writer.Indented($"{offset} =l add {destination}, {OffsetOf(structInitializer.StructType, field)}");
|
|
EmitCopyInto(value, offset);
|
|
}
|
|
|
|
return destination;
|
|
}
|
|
|
|
private string EmitUnaryExpression(UnaryExpressionNode unaryExpression)
|
|
{
|
|
var operand = EmitExpression(unaryExpression.Operand);
|
|
var outputName = TmpName();
|
|
|
|
switch (unaryExpression.Operator)
|
|
{
|
|
case UnaryOperator.Negate:
|
|
{
|
|
switch (unaryExpression.Operand.Type)
|
|
{
|
|
case IntTypeNode { Signed: true, Width: 64 }:
|
|
_writer.Indented($"{outputName} =l neg {operand}");
|
|
return outputName;
|
|
case IntTypeNode { Signed: true, Width: 8 or 16 or 32 }:
|
|
_writer.Indented($"{outputName} =w neg {operand}");
|
|
return outputName;
|
|
case FloatTypeNode { Width: 64 }:
|
|
_writer.Indented($"{outputName} =d neg {operand}");
|
|
return outputName;
|
|
case FloatTypeNode { Width: 32 }:
|
|
_writer.Indented($"{outputName} =s neg {operand}");
|
|
return outputName;
|
|
}
|
|
|
|
break;
|
|
}
|
|
case UnaryOperator.Invert:
|
|
{
|
|
switch (unaryExpression.Operand.Type)
|
|
{
|
|
case BoolTypeNode:
|
|
_writer.Indented($"{outputName} =w xor {operand}, 1");
|
|
return outputName;
|
|
}
|
|
|
|
break;
|
|
}
|
|
default:
|
|
{
|
|
throw new ArgumentOutOfRangeException();
|
|
}
|
|
}
|
|
|
|
throw new NotSupportedException($"Unary operator {unaryExpression.Operator} for type {unaryExpression.Operand.Type} not supported");
|
|
}
|
|
|
|
private string EmitStructFieldAccess(StructFieldAccessNode structFieldAccess)
|
|
{
|
|
var address = EmitAddressOfStructFieldAccess(structFieldAccess);
|
|
if (structFieldAccess.Type is StructTypeNode)
|
|
{
|
|
return address;
|
|
}
|
|
|
|
return EmitLoad(structFieldAccess.Type, address);
|
|
}
|
|
|
|
private string EmitStructFuncCall(StructFuncCallNode structFuncCall)
|
|
{
|
|
var func = StructFuncName(structFuncCall.StructType.Module, structFuncCall.StructType.Name, structFuncCall.Name);
|
|
|
|
var thisParameter = EmitExpression(structFuncCall.StructExpression);
|
|
|
|
List<string> parameterStrings = [$"l {thisParameter}"];
|
|
|
|
foreach (var parameter in structFuncCall.Parameters)
|
|
{
|
|
var copy = EmitCopy(parameter);
|
|
parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}");
|
|
}
|
|
|
|
if (structFuncCall.Type is VoidTypeNode)
|
|
{
|
|
_writer.Indented($"call {func}({string.Join(", ", parameterStrings)})");
|
|
return string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var outputName = TmpName();
|
|
_writer.Indented($"{outputName} {QBEAssign(structFuncCall.Type)} call {func}({string.Join(", ", parameterStrings)})");
|
|
return outputName;
|
|
}
|
|
}
|
|
|
|
private string EmitInterfaceFuncCall(InterfaceFuncCallNode interfaceFuncCall)
|
|
{
|
|
var target = EmitExpression(interfaceFuncCall.InterfaceExpression);
|
|
|
|
var functionIndex = interfaceFuncCall.InterfaceType.Functions.ToList().FindIndex(x => x.Name == interfaceFuncCall.Name);
|
|
var offset = functionIndex * 8;
|
|
|
|
var vtable = TmpName();
|
|
_writer.Indented($"{vtable} =l loadl {target}");
|
|
|
|
var funcOffset = TmpName();
|
|
_writer.Indented($"{funcOffset} =l add {vtable}, {offset}");
|
|
|
|
var func = TmpName();
|
|
_writer.Indented($"{func} =l loadl {funcOffset}");
|
|
|
|
var data = TmpName();
|
|
_writer.Indented($"{data} =l add {target}, 8");
|
|
_writer.Indented($"{data} =l loadl {data}");
|
|
|
|
List<string> parameterStrings = [$"l {data}"];
|
|
|
|
foreach (var parameter in interfaceFuncCall.Parameters)
|
|
{
|
|
var copy = EmitCopy(parameter);
|
|
parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}");
|
|
}
|
|
|
|
if (interfaceFuncCall.Type is VoidTypeNode)
|
|
{
|
|
_writer.Indented($"call {func}({string.Join(", ", parameterStrings)})");
|
|
return string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var outputName = TmpName();
|
|
_writer.Indented($"{outputName} {QBEAssign(interfaceFuncCall.Type)} call {func}({string.Join(", ", parameterStrings)})");
|
|
return outputName;
|
|
}
|
|
}
|
|
|
|
private string EmitConvertToInterface(ConvertToInterfaceNode convertToInterface)
|
|
{
|
|
var implementation = EmitExpression(convertToInterface.Implementation);
|
|
|
|
var vtableOffset = 0;
|
|
foreach (var interfaceImplementation in convertToInterface.StructType.InterfaceImplementations)
|
|
{
|
|
if (interfaceImplementation == convertToInterface.InterfaceType)
|
|
{
|
|
break;
|
|
}
|
|
|
|
vtableOffset += interfaceImplementation.Functions.Count * 8;
|
|
}
|
|
|
|
var destination = TmpName();
|
|
_writer.Indented($"{destination} =l alloc8 {SizeOf(convertToInterface.InterfaceType)}");
|
|
|
|
var interfaceVtablePointer = TmpName();
|
|
_writer.Indented($"{interfaceVtablePointer} =l add {StructVtableName(convertToInterface.StructType.Module, convertToInterface.StructType.Name)}, {vtableOffset}");
|
|
_writer.Indented($"storel {interfaceVtablePointer}, {destination}");
|
|
|
|
var objectPointer = TmpName();
|
|
_writer.Indented($"{objectPointer} =l add {destination}, 8");
|
|
_writer.Indented($"storel {implementation}, {objectPointer}");
|
|
|
|
return destination;
|
|
}
|
|
|
|
private string EmitConvertInt(ConvertIntNode convertInt)
|
|
{
|
|
var value = EmitExpression(convertInt.Value);
|
|
|
|
if (convertInt.ValueType.Width >= convertInt.TargetType.Width)
|
|
{
|
|
return value;
|
|
}
|
|
|
|
var method = convertInt.ValueType.Signed switch
|
|
{
|
|
true => convertInt.ValueType.Width switch
|
|
{
|
|
8 => "extsb",
|
|
16 => "extsh",
|
|
32 => "extsw",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
},
|
|
false => convertInt.ValueType.Width switch
|
|
{
|
|
8 => "extub",
|
|
16 => "extuh",
|
|
32 => "extuw",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
}
|
|
};
|
|
|
|
var result = TmpName();
|
|
_writer.Indented($"{result} {QBEAssign(convertInt.TargetType)} {method} {value}");
|
|
return result;
|
|
}
|
|
|
|
private string EmitConvertFloat(ConvertFloatNode convertFloat)
|
|
{
|
|
var value = EmitExpression(convertFloat.Value);
|
|
|
|
if (convertFloat.ValueType.Width == convertFloat.TargetType.Width)
|
|
{
|
|
return value;
|
|
}
|
|
|
|
var method = convertFloat.ValueType.Width switch
|
|
{
|
|
32 => "exts",
|
|
64 => "truncd",
|
|
_ => throw new ArgumentOutOfRangeException()
|
|
};
|
|
|
|
var result = TmpName();
|
|
_writer.Indented($"{result} {QBEAssign(convertFloat.TargetType)} {method} {value}");
|
|
return result;
|
|
}
|
|
|
|
private string EmitFuncCall(FuncCallNode funcCall)
|
|
{
|
|
var funcPointer = EmitExpression(funcCall.Expression);
|
|
|
|
var parameterStrings = new List<string>();
|
|
|
|
foreach (var parameter in funcCall.Parameters)
|
|
{
|
|
var copy = EmitCopy(parameter);
|
|
parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}");
|
|
}
|
|
|
|
if (funcCall.Type is VoidTypeNode)
|
|
{
|
|
_writer.Indented($"call {funcPointer}({string.Join(", ", parameterStrings)})");
|
|
return string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var outputName = TmpName();
|
|
_writer.Indented($"{outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})");
|
|
return outputName;
|
|
}
|
|
}
|
|
|
|
private static int SizeOf(TypeNode type)
|
|
{
|
|
return type switch
|
|
{
|
|
SimpleTypeNode simple => simple.StorageSize switch
|
|
{
|
|
StorageSize.Void => 0,
|
|
StorageSize.I8 or StorageSize.U8 => 1,
|
|
StorageSize.I16 or StorageSize.U16 => 2,
|
|
StorageSize.I32 or StorageSize.U32 or StorageSize.F32 => 4,
|
|
StorageSize.I64 or StorageSize.U64 or StorageSize.F64 => 8,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(type), $"Unknown storage size: {simple.StorageSize}")
|
|
},
|
|
CStringTypeNode => 8,
|
|
StringTypeNode => 8,
|
|
ArrayTypeNode => 8,
|
|
StructTypeNode structType => CalculateStructSize(structType),
|
|
InterfaceTypeNode => 16,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(type), $"Unknown type: {type.GetType()}")
|
|
};
|
|
}
|
|
|
|
private static int CalculateStructSize(StructTypeNode structType)
|
|
{
|
|
var offset = 0;
|
|
|
|
var fields = new List<TypeNode>(structType.Fields.Count);
|
|
|
|
foreach (var field in structType.Fields)
|
|
{
|
|
var fieldAlignment = AlignmentOf(field.Type);
|
|
offset = AlignTo(offset, fieldAlignment);
|
|
offset += SizeOf(field.Type);
|
|
}
|
|
|
|
var structAlignment = CalculateStructAlignment(structType);
|
|
return AlignTo(offset, structAlignment);
|
|
}
|
|
|
|
private static int AlignmentOf(TypeNode type)
|
|
{
|
|
return type switch
|
|
{
|
|
SimpleTypeNode simple => simple.StorageSize switch
|
|
{
|
|
StorageSize.Void => 1,
|
|
StorageSize.I8 or StorageSize.U8 => 1,
|
|
StorageSize.I16 or StorageSize.U16 => 2,
|
|
StorageSize.I32 or StorageSize.U32 or StorageSize.F32 => 4,
|
|
StorageSize.I64 or StorageSize.U64 or StorageSize.F64 => 8,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(type), $"Unknown storage size: {simple.StorageSize}")
|
|
},
|
|
CStringTypeNode => 8,
|
|
StringTypeNode => 8,
|
|
ArrayTypeNode => 8,
|
|
StructTypeNode structType => CalculateStructAlignment(structType),
|
|
InterfaceTypeNode => 8,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(type), $"Unknown type: {type.GetType()}")
|
|
};
|
|
}
|
|
|
|
private static int CalculateStructAlignment(StructTypeNode structType)
|
|
{
|
|
var maxAlignment = 1;
|
|
|
|
if (structType.InterfaceImplementations.Any())
|
|
{
|
|
maxAlignment = Math.Max(maxAlignment, 8);
|
|
}
|
|
|
|
foreach (var field in structType.Fields)
|
|
{
|
|
var fieldAlignment = AlignmentOf(field.Type);
|
|
maxAlignment = Math.Max(maxAlignment, fieldAlignment);
|
|
}
|
|
|
|
return maxAlignment;
|
|
}
|
|
|
|
private static int AlignTo(int offset, int alignment)
|
|
{
|
|
return (offset + alignment - 1) & ~(alignment - 1);
|
|
}
|
|
|
|
private static int OffsetOf(StructTypeNode structDef, string member)
|
|
{
|
|
var offset = 0;
|
|
|
|
foreach (var field in structDef.Fields)
|
|
{
|
|
if (field.Name == member)
|
|
{
|
|
return offset;
|
|
}
|
|
|
|
var fieldAlignment = AlignmentOf(field.Type);
|
|
|
|
offset = AlignTo(offset, fieldAlignment);
|
|
offset += SizeOf(field.Type);
|
|
}
|
|
|
|
throw new UnreachableException($"Member '{member}' not found in struct");
|
|
}
|
|
|
|
#region Naming utilities
|
|
|
|
private string TmpName()
|
|
{
|
|
return $"%t{++_tmpIndex}";
|
|
}
|
|
|
|
private string LabelName()
|
|
{
|
|
return $"@l{++_labelIndex}";
|
|
}
|
|
|
|
private string CStringName()
|
|
{
|
|
return $"$cstring{++_cStringLiteralIndex}";
|
|
}
|
|
|
|
private string StringName()
|
|
{
|
|
return $"$string{++_stringLiteralIndex}";
|
|
}
|
|
|
|
private string FuncName(string module, string name)
|
|
{
|
|
var type = TypeResolver.ResolveFunctionType(module, name, _moduleSignatures);
|
|
var symbol = type.ExternSymbol ?? $"{module}.{name}";
|
|
return "$" + symbol;
|
|
}
|
|
|
|
private string StructTypeName(string module, string name)
|
|
{
|
|
return $":{module}.{name}";
|
|
}
|
|
|
|
private string StructFuncName(string module, string structName, string funcName)
|
|
{
|
|
return $"${module}.{structName}_func.{funcName}";
|
|
}
|
|
|
|
private string StructCtorName(string module, string structName)
|
|
{
|
|
return $"${module}.{structName}_ctor";
|
|
}
|
|
|
|
private string StructVtableName(string module, string structName)
|
|
{
|
|
return $"${module}.{structName}_vtable";
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
|
|
public class StringLiteral(string value, string name)
|
|
{
|
|
public string Value { get; } = value;
|
|
public string Name { get; } = name;
|
|
}
|
|
|
|
public class CStringLiteral(string value, string name)
|
|
{
|
|
public string Value { get; } = value;
|
|
public string Name { get; } = name;
|
|
} |