using System.Diagnostics; using System.Globalization; using System.Text; using NubLang.Tokenization; using NubLang.TypeChecking.Node; namespace NubLang.Generation.QBE; public class QBEGenerator { private readonly QBEWriter _writer; private readonly List _definitions; private readonly HashSet _structTypes; private readonly List _cStringLiterals = []; private readonly List _stringLiterals = []; private readonly Stack _breakLabels = []; private readonly Stack _continueLabels = []; private int _tmpIndex; private int _labelIndex; private int _cStringLiteralIndex; private int _stringLiteralIndex; private bool _codeIsReachable = true; public QBEGenerator(List definitions, HashSet structTypes) { _definitions = definitions; _structTypes = structTypes; _writer = new QBEWriter(); } public string Emit() { _cStringLiterals.Clear(); _stringLiterals.Clear(); _breakLabels.Clear(); _continueLabels.Clear(); _tmpIndex = 0; _labelIndex = 0; _cStringLiteralIndex = 0; _stringLiteralIndex = 0; _codeIsReachable = true; _writer.Comment("========== Builtin functions =========="); _writer.WriteLine(""" function l $.cstring_len(l %str) { @start %count =l copy 0 @loop %address =l add %str, %count %value =w loadub %address jnz %value, @continue, @end @continue %count =l add %count, 1 jmp @loop @end ret %count } function $.memcpy(l %source, l %destination, l %length) { @start %count =l copy 0 @loop %condition =w cultl %count, %length jnz %condition, @continue, @end @continue %source_address =l add %source, %count %destination_address =l add %destination, %count %value =w loadub %source_address storeb %value, %destination_address %count =l add %count, 1 jmp @loop @end ret } function $.memset(l %destination, l %value, l %length) { @start %count =l copy 0 @loop %condition =w cultl %count, %length jnz %condition, @continue, @end @continue %destination_address =l add %destination, %count storeb %value, %destination_address %count =l add %count, 1 jmp @loop @end ret } function l $.array_size(l %array) { @start %size =l loadl %array ret %size } """); _writer.Comment("========== Referenced structs =========="); foreach (var structType in _structTypes) { EmitStructType(structType); } _writer.NewLine(); _writer.Comment("========== Struct definitions =========="); foreach (var structDef in _definitions.OfType()) { EmitStructDefinition(structDef); } _writer.NewLine(); _writer.Comment("========== Function definitions =========="); foreach (var funcDef in _definitions.OfType()) { EmitFuncDefinition(funcDef); } _writer.NewLine(); _writer.Comment("========== cstring literals =========="); foreach (var cStringLiteral in _cStringLiterals) { _writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}"); } _writer.NewLine(); _writer.Comment("========== string literals =========="); 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) { _writer.Indented($"call $.memset(l {destination}, l {value}, l {length})"); } private void EmitMemcpy(string source, string destination, string length) { _writer.Indented($"call $.memcpy(l {source}, l {destination}, l {length})"); } private string EmitArraySizeInBytes(ArrayTypeNode type, string array) { var size = TmpName(); _writer.Indented($"{size} =l call $.array_size(l {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 result = TmpName(); _writer.Indented($"{result} =l call $.cstring_len(l {cstring})"); _writer.Indented($"{result} =l add {result}, 1"); return result; } 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 has known sizes at compile time if (complexType is StructTypeNode) { 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 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 has known sizes at compile time if (complexType is StructTypeNode) { 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 EmitStructType(StructTypeNode structType) { _writer.Write($"type {StructTypeName(structType.Module, structType.Name)} = {{ "); foreach (var field in structType.Fields) { _writer.Write($"{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 EmitStructDefinition(StructNode structDef) { _writer.Comment($" ===== {structDef.Module}::{structDef.Name} ====="); _writer.WriteLine($"export function {StructCtorName(structDef.Module, structDef.Name)}(l %struct) {{"); _writer.WriteLine("@start"); foreach (var field in structDef.Fields) { if (field.Value.TryGetValue(out var value)) { var offset = OffsetOf(structDef.StructType, field.Name); var destination = TmpName(); _writer.Indented($"{destination} =l add %struct, {offset}"); EmitCopyInto(value, destination); } } _writer.Indented("ret"); _writer.WriteLine("}"); foreach (var function in structDef.Functions) { _writer.Comment($" ===== {structDef.Module}::{structDef.Name}.{function.Name} ====="); _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(structDef.Module, 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 EmitFuncDefinition(FuncNode funcDef) { if (funcDef.Body == null) return; _labelIndex = 0; _tmpIndex = 0; _writer.Write(funcDef.ExternSymbol != null ? "export function " : "function "); if (funcDef.Signature.ReturnType is not VoidTypeNode) { _writer.Write(FuncQBETypeName(funcDef.Signature.ReturnType) + ' '); } _writer.Write(FuncName(funcDef.Module, funcDef.Name, funcDef.ExternSymbol)); _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 EmitBlock(BlockNode block) { foreach (var statement in block.Statements) { if (_codeIsReachable) { EmitStatement(statement); } } _codeIsReachable = true; } private void EmitStatement(StatementNode statement) { 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) { 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), 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) { return FuncName(funcIdent.Module, funcIdent.Name, funcIdent.ExternSymbol); } 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); } 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 offset = OffsetOf(structFieldAccess.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}"); _writer.Indented($"call {StructCtorName(structInitializer.StructType.Module, structInitializer.StructType.Name)}(l {destination})"); 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 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 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(); 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), _ => throw new ArgumentOutOfRangeException(nameof(type), $"Unknown type: {type.GetType()}") }; } private static int CalculateStructSize(StructTypeNode structType) { var offset = 0; 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), _ => throw new ArgumentOutOfRangeException(nameof(type), $"Unknown type: {type.GetType()}") }; } private static int CalculateStructAlignment(StructTypeNode structType) { var maxAlignment = 1; 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"); } private string TmpName() { return $"%.t{++_tmpIndex}"; } private string LabelName() { return $"@.l{++_labelIndex}"; } private string CStringName() { return $"$.cstr{++_cStringLiteralIndex}"; } private string StringName() { return $"$.str{++_stringLiteralIndex}"; } private static string FuncName(string module, string name, string? externSymbol) { return $"${externSymbol ?? $".{module}.{name}"}"; } private static string StructTypeName(string module, string name) { return $":{module}.{name}"; } private static string StructCtorName(string module, string name) { return $"$.{module}.{name}.ctor"; } private static string StructFuncName(string module, string structName, string funcName) { return $"$.{module}.{structName}.func.{funcName}"; } } 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; }