448 lines
17 KiB
C#
448 lines
17 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using NubLang.Tokenization;
|
|
using NubLang.TypeChecking;
|
|
using NubLang.TypeChecking.Node;
|
|
|
|
namespace NubLang.Generation.QBE;
|
|
|
|
public partial class QBEGenerator
|
|
{
|
|
private Val EmitExpression(Expression expression)
|
|
{
|
|
return expression switch
|
|
{
|
|
ArrayInitializer arrayInitializer => EmitArrayInitializer(arrayInitializer),
|
|
StructInitializer structInitializer => EmitStructInitializer(structInitializer),
|
|
AddressOf addressOf => EmitAddressOf(addressOf),
|
|
Dereference dereference => EmitDereference(dereference),
|
|
ArrowFunc arrowFunc => EmitArrowFunc(arrowFunc),
|
|
BinaryExpression binaryExpression => EmitBinaryExpression(binaryExpression),
|
|
FuncCall funcCallExpression => EmitFuncCall(funcCallExpression),
|
|
ExternFuncIdent externFuncIdent => EmitExternFuncIdent(externFuncIdent),
|
|
LocalFuncIdent localFuncIdent => EmitLocalFuncIdent(localFuncIdent),
|
|
VariableIdent variableIdent => EmitVariableIdent(variableIdent),
|
|
Literal literal => EmitLiteral(literal),
|
|
UnaryExpression unaryExpression => EmitUnaryExpression(unaryExpression),
|
|
StructFieldAccess structFieldAccess => EmitStructFieldAccess(structFieldAccess),
|
|
InterfaceFuncAccess traitFuncAccess => EmitTraitFuncAccess(traitFuncAccess),
|
|
ArrayIndexAccess arrayIndex => EmitArrayIndexAccess(arrayIndex),
|
|
_ => throw new ArgumentOutOfRangeException(nameof(expression))
|
|
};
|
|
}
|
|
|
|
private Val EmitArrowFunc(ArrowFunc arrowFunc)
|
|
{
|
|
var name = $"$arrow_func{++_arrowFuncIndex}";
|
|
_arrowFunctions.Enqueue((arrowFunc, name));
|
|
return new Val(name, arrowFunc.Type, ValKind.Direct);
|
|
}
|
|
|
|
private Val EmitArrayIndexAccess(ArrayIndexAccess arrayIndexAccess)
|
|
{
|
|
var array = EmitUnwrap(EmitExpression(arrayIndexAccess.Target));
|
|
var index = EmitUnwrap(EmitExpression(arrayIndexAccess.Index));
|
|
|
|
EmitArraysCheck(array, index);
|
|
|
|
var elementType = ((NubArrayType)arrayIndexAccess.Target.Type).ElementType;
|
|
|
|
var pointer = TmpName();
|
|
_writer.Indented($"{pointer} =l mul {index}, {elementType.Size(_definitionTable)}");
|
|
_writer.Indented($"{pointer} =l add {pointer}, 8");
|
|
_writer.Indented($"{pointer} =l add {array}, {pointer}");
|
|
return new Val(pointer, arrayIndexAccess.Type, ValKind.Pointer);
|
|
}
|
|
|
|
private void EmitArraysCheck(string array, string index)
|
|
{
|
|
var count = TmpName();
|
|
_writer.Indented($"{count} =l loadl {array}");
|
|
|
|
var isNegative = TmpName();
|
|
_writer.Indented($"{isNegative} =w csltl {index}, 0");
|
|
|
|
var isOob = TmpName();
|
|
_writer.Indented($"{isOob} =w csgel {index}, {count}");
|
|
|
|
var anyOob = TmpName();
|
|
_writer.Indented($"{anyOob} =w or {isNegative}, {isOob}");
|
|
|
|
var oobLabel = LabelName();
|
|
var notOobLabel = LabelName();
|
|
_writer.Indented($"jnz {anyOob}, {oobLabel}, {notOobLabel}");
|
|
|
|
_writer.Indented(oobLabel);
|
|
_writer.Indented($"call $nub_panic_array_oob()");
|
|
|
|
_writer.Indented(notOobLabel);
|
|
}
|
|
|
|
private Val EmitArrayInitializer(ArrayInitializer arrayInitializer)
|
|
{
|
|
var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity));
|
|
var elementSize = arrayInitializer.ElementType.Size(_definitionTable);
|
|
|
|
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");
|
|
_writer.Indented($"call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})");
|
|
|
|
return new Val(arrayPointer, arrayInitializer.Type, ValKind.Direct);
|
|
}
|
|
|
|
private Val EmitDereference(Dereference dereference)
|
|
{
|
|
return EmitLoad(dereference.Type, EmitUnwrap(EmitExpression(dereference.Expression)));
|
|
}
|
|
|
|
private Val EmitAddressOf(AddressOf addressOf)
|
|
{
|
|
var value = EmitExpression(addressOf.Expression);
|
|
if (value.Kind != ValKind.Pointer)
|
|
{
|
|
throw new UnreachableException("Tried to take address of non-pointer type. This should have been causht in the type checker");
|
|
}
|
|
|
|
return new Val(value.Name, addressOf.Type, ValKind.Direct);
|
|
}
|
|
|
|
private Val EmitBinaryExpression(BinaryExpression binaryExpression)
|
|
{
|
|
var left = EmitUnwrap(EmitExpression(binaryExpression.Left));
|
|
var right = EmitUnwrap(EmitExpression(binaryExpression.Right));
|
|
|
|
var outputName = TmpName();
|
|
|
|
var instruction = EmitBinaryInstructionFor(binaryExpression.Operator, binaryExpression.Left.Type, left, right);
|
|
|
|
_writer.Indented($"{outputName} {QBEAssign(binaryExpression.Left.Type)} {instruction} {left}, {right}");
|
|
return new Val(outputName, binaryExpression.Type, ValKind.Direct);
|
|
}
|
|
|
|
private string EmitBinaryInstructionFor(BinaryOperator op, NubType type, string left, string right)
|
|
{
|
|
if (op is
|
|
BinaryOperator.Equal or
|
|
BinaryOperator.NotEqual or
|
|
BinaryOperator.GreaterThan or
|
|
BinaryOperator.GreaterThanOrEqual or
|
|
BinaryOperator.LessThan or
|
|
BinaryOperator.LessThanOrEqual)
|
|
{
|
|
char suffix;
|
|
|
|
if (!type.IsSimpleType(out var simpleType, out _))
|
|
{
|
|
throw new NotSupportedException("Binary operations is only supported for simple types.");
|
|
}
|
|
|
|
switch (simpleType.StorageSize)
|
|
{
|
|
case StorageSize.I8:
|
|
_writer.Indented($"{left} =w extsb {left}");
|
|
_writer.Indented($"{right} =w extsb {right}");
|
|
suffix = 'w';
|
|
break;
|
|
case StorageSize.U8:
|
|
_writer.Indented($"{left} =w extub {left}");
|
|
_writer.Indented($"{right} =w extub {right}");
|
|
suffix = 'w';
|
|
break;
|
|
case StorageSize.I16:
|
|
_writer.Indented($"{left} =w extsh {left}");
|
|
_writer.Indented($"{right} =w extsh {right}");
|
|
suffix = 'w';
|
|
break;
|
|
case StorageSize.U16:
|
|
_writer.Indented($"{left} =w extuh {left}");
|
|
_writer.Indented($"{right} =w extuh {right}");
|
|
suffix = 'w';
|
|
break;
|
|
case StorageSize.I32 or StorageSize.U32:
|
|
suffix = 'w';
|
|
break;
|
|
case StorageSize.I64 or StorageSize.U64:
|
|
suffix = 'l';
|
|
break;
|
|
default:
|
|
throw new NotSupportedException($"Unsupported type '{simpleType}' for binary operator '{op}'");
|
|
}
|
|
|
|
if (op is BinaryOperator.Equal)
|
|
{
|
|
return "ceq" + suffix;
|
|
}
|
|
|
|
if (op is BinaryOperator.NotEqual)
|
|
{
|
|
return "cne" + suffix;
|
|
}
|
|
|
|
string sign;
|
|
|
|
if (simpleType is NubIntType { Signed: true })
|
|
{
|
|
sign = "s";
|
|
}
|
|
else if (simpleType is NubIntType { Signed: false })
|
|
{
|
|
sign = "u";
|
|
}
|
|
else
|
|
{
|
|
throw new NotSupportedException($"Unsupported type '{type}' for binary operator '{op}'");
|
|
}
|
|
|
|
return op switch
|
|
{
|
|
BinaryOperator.GreaterThan => 'c' + sign + "gt" + suffix,
|
|
BinaryOperator.GreaterThanOrEqual => 'c' + sign + "ge" + suffix,
|
|
BinaryOperator.LessThan => 'c' + sign + "lt" + suffix,
|
|
BinaryOperator.LessThanOrEqual => 'c' + sign + "le" + suffix,
|
|
_ => throw new ArgumentOutOfRangeException(nameof(op), op, null)
|
|
};
|
|
}
|
|
|
|
return op switch
|
|
{
|
|
BinaryOperator.Plus => "add",
|
|
BinaryOperator.Minus => "sub",
|
|
BinaryOperator.Multiply => "mul",
|
|
BinaryOperator.Divide => "div",
|
|
_ => throw new ArgumentOutOfRangeException(nameof(op))
|
|
};
|
|
}
|
|
|
|
private Val EmitExternFuncIdent(ExternFuncIdent externFuncIdent)
|
|
{
|
|
var func = _definitionTable.LookupExternFunc(externFuncIdent.Name);
|
|
return new Val(ExternFuncName(func), externFuncIdent.Type, ValKind.Direct);
|
|
}
|
|
|
|
private Val EmitLocalFuncIdent(LocalFuncIdent localFuncIdent)
|
|
{
|
|
var func = _definitionTable.LookupLocalFunc(localFuncIdent.Name);
|
|
return new Val(LocalFuncName(func), localFuncIdent.Type, ValKind.Direct);
|
|
}
|
|
|
|
private Val EmitVariableIdent(VariableIdent variableIdent)
|
|
{
|
|
return Scope.Lookup(variableIdent.Name);
|
|
}
|
|
|
|
private Val EmitLiteral(Literal literal)
|
|
{
|
|
switch (literal.Kind)
|
|
{
|
|
case LiteralKind.Integer:
|
|
{
|
|
if (literal.Type is NubFloatType { Width: 32 })
|
|
{
|
|
var value = float.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.SingleToInt32Bits(value);
|
|
return new Val(bits.ToString(), literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
if (literal.Type is NubFloatType { Width: 64 })
|
|
{
|
|
var value = double.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.DoubleToInt64Bits(value);
|
|
return new Val(bits.ToString(), literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
if (literal.Type is NubIntType)
|
|
{
|
|
return new Val(literal.Value, literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
break;
|
|
}
|
|
case LiteralKind.Float:
|
|
{
|
|
if (literal.Type is NubIntType)
|
|
{
|
|
return new Val(literal.Value.Split(".").First(), literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
if (literal.Type is NubFloatType { Width: 32 })
|
|
{
|
|
var value = float.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.SingleToInt32Bits(value);
|
|
return new Val(bits.ToString(), literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
if (literal.Type is NubFloatType { Width: 64 })
|
|
{
|
|
var value = double.Parse(literal.Value, CultureInfo.InvariantCulture);
|
|
var bits = BitConverter.DoubleToInt64Bits(value);
|
|
return new Val(bits.ToString(), literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
break;
|
|
}
|
|
case LiteralKind.String:
|
|
{
|
|
if (literal.Type is NubStringType)
|
|
{
|
|
var stringLiteral = new StringLiteral(literal.Value, StringName());
|
|
_stringLiterals.Add(stringLiteral);
|
|
return new Val(stringLiteral.Name, literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
if (literal.Type is NubCStringType)
|
|
{
|
|
var cStringLiteral = new CStringLiteral(literal.Value, CStringName());
|
|
_cStringLiterals.Add(cStringLiteral);
|
|
return new Val(cStringLiteral.Name, literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
break;
|
|
}
|
|
case LiteralKind.Bool:
|
|
{
|
|
if (literal.Type is NubBoolType)
|
|
{
|
|
return new Val(bool.Parse(literal.Value) ? "1" : "0", literal.Type, ValKind.Direct);
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
throw new NotSupportedException($"Cannot create literal of kind '{literal.Kind}' for type {literal.Type}");
|
|
}
|
|
|
|
private Val EmitStructInitializer(StructInitializer structInitializer, string? destination = null)
|
|
{
|
|
var @struct = _definitionTable.LookupStruct(structInitializer.StructType.Name);
|
|
|
|
if (destination == null)
|
|
{
|
|
destination = TmpName();
|
|
var size = structInitializer.StructType.Size(_definitionTable);
|
|
_writer.Indented($"{destination} =l alloc8 {size}");
|
|
}
|
|
|
|
foreach (var field in @struct.Fields)
|
|
{
|
|
if (!structInitializer.Initializers.TryGetValue(field.Name, out var valueExpression))
|
|
{
|
|
valueExpression = field.Value.Value;
|
|
}
|
|
|
|
Debug.Assert(valueExpression != null);
|
|
|
|
var offset = TmpName();
|
|
_writer.Indented($"{offset} =l add {destination}, {OffsetOf(@struct, field.Name)}");
|
|
EmitCopyIntoOrInitialize(valueExpression, offset);
|
|
}
|
|
|
|
return new Val(destination, structInitializer.StructType, ValKind.Direct);
|
|
}
|
|
|
|
private Val EmitUnaryExpression(UnaryExpression unaryExpression)
|
|
{
|
|
var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand));
|
|
var outputName = TmpName();
|
|
|
|
switch (unaryExpression.Operator)
|
|
{
|
|
case UnaryOperator.Negate:
|
|
{
|
|
switch (unaryExpression.Operand.Type)
|
|
{
|
|
case NubIntType { Signed: true, Width: 64 }:
|
|
_writer.Indented($"{outputName} =l neg {operand}");
|
|
return new Val(outputName, unaryExpression.Type, ValKind.Direct);
|
|
case NubIntType { Signed: true, Width: 8 or 16 or 32 }:
|
|
_writer.Indented($"{outputName} =w neg {operand}");
|
|
return new Val(outputName, unaryExpression.Type, ValKind.Direct);
|
|
case NubFloatType { Width: 64 }:
|
|
_writer.Indented($"{outputName} =d neg {operand}");
|
|
return new Val(outputName, unaryExpression.Type, ValKind.Direct);
|
|
case NubFloatType { Width: 32 }:
|
|
_writer.Indented($"{outputName} =s neg {operand}");
|
|
return new Val(outputName, unaryExpression.Type, ValKind.Direct);
|
|
}
|
|
|
|
break;
|
|
}
|
|
case UnaryOperator.Invert:
|
|
{
|
|
switch (unaryExpression.Operand.Type)
|
|
{
|
|
case NubBoolType:
|
|
_writer.Indented($"{outputName} =w xor {operand}, 1");
|
|
return new Val(outputName, unaryExpression.Type, ValKind.Direct);
|
|
}
|
|
|
|
break;
|
|
}
|
|
default:
|
|
{
|
|
throw new ArgumentOutOfRangeException();
|
|
}
|
|
}
|
|
|
|
throw new NotSupportedException($"Unary operator {unaryExpression.Operator} for type {unaryExpression.Operand.Type} not supported");
|
|
}
|
|
|
|
private Val EmitStructFieldAccess(StructFieldAccess structFieldAccess)
|
|
{
|
|
var target = EmitUnwrap(EmitExpression(structFieldAccess.Target));
|
|
|
|
var structDef = _definitionTable.LookupStruct(structFieldAccess.StructType.Name);
|
|
var offset = OffsetOf(structDef, structFieldAccess.Field);
|
|
|
|
var output = TmpName();
|
|
_writer.Indented($"{output} =l add {target}, {offset}");
|
|
|
|
// If the accessed member is an inline struct, it will not be a pointer
|
|
if (structFieldAccess.Type is NubCustomType customType && customType.Kind(_definitionTable) == CustomTypeKind.Struct)
|
|
{
|
|
return new Val(output, structFieldAccess.Type, ValKind.Direct);
|
|
}
|
|
|
|
return new Val(output, structFieldAccess.Type, ValKind.Pointer);
|
|
}
|
|
|
|
private Val EmitTraitFuncAccess(InterfaceFuncAccess interfaceFuncAccess)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
private Val EmitFuncCall(FuncCall funcCall)
|
|
{
|
|
var expression = EmitExpression(funcCall.Expression);
|
|
var funcPointer = EmitUnwrap(expression);
|
|
|
|
var parameterStrings = new List<string>();
|
|
|
|
foreach (var parameter in funcCall.Parameters)
|
|
{
|
|
var copy = EmitCreateCopyOrInitialize(parameter);
|
|
parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}");
|
|
}
|
|
|
|
if (funcCall.Type is NubVoidType)
|
|
{
|
|
_writer.Indented($"call {funcPointer}({string.Join(", ", parameterStrings)})");
|
|
return new Val(string.Empty, funcCall.Type, ValKind.Direct);
|
|
}
|
|
else
|
|
{
|
|
var outputName = TmpName();
|
|
_writer.Indented($"{outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})");
|
|
return new Val(outputName, funcCall.Type, ValKind.Direct);
|
|
}
|
|
}
|
|
} |