mirror of
https://github.com/irmen/prog8.git
synced 2025-06-17 16:23:42 +00:00
Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
4bfdbad2e4 | |||
06137ecdc4 | |||
d89f5b0df8 | |||
b6e2b36692 | |||
a6d789cfbc | |||
c07907e7bd | |||
7d8496c874 | |||
164ac56db1 | |||
fdddb8ca64 | |||
a9d4b8b0fa | |||
ec7b9f54c2 | |||
307558a7e7 | |||
febf423eab | |||
a999c23014 | |||
69f1ade595 | |||
b166576e54 | |||
ee2ba5f398 | |||
cb9825484d |
@ -781,3 +781,18 @@ set_array_float .proc
|
||||
; -- copies the 5 bytes of the mflt value pointed to by SCRATCH_ZPWORD1,
|
||||
; into the 5 bytes pointed to by A/Y. Clobbers A,Y.
|
||||
.pend
|
||||
|
||||
|
||||
swap_floats .proc
|
||||
; -- swap floats pointed to by SCRATCH_ZPWORD1, SCRATCH_ZPWORD2
|
||||
ldy #4
|
||||
- lda (c64.SCRATCH_ZPWORD1),y
|
||||
pha
|
||||
lda (c64.SCRATCH_ZPWORD2),y
|
||||
sta (c64.SCRATCH_ZPWORD1),y
|
||||
pla
|
||||
sta (c64.SCRATCH_ZPWORD2),y
|
||||
dey
|
||||
bpl -
|
||||
rts
|
||||
.pend
|
||||
|
@ -1 +1 @@
|
||||
2.2
|
||||
2.3
|
||||
|
@ -155,6 +155,7 @@ interface INameScope {
|
||||
}
|
||||
|
||||
fun containsCodeOrVars() = statements.any { it !is Directive || it.directive == "%asminclude" || it.directive == "%asm"}
|
||||
fun containsNoVars() = statements.all { it !is VarDecl }
|
||||
fun containsNoCodeNorVars() = !containsCodeOrVars()
|
||||
|
||||
fun remove(stmt: Statement) {
|
||||
@ -229,7 +230,7 @@ class Program(val name: String, val modules: MutableList<Module>): Node {
|
||||
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(node is Module && replacement is Module)
|
||||
val idx = modules.indexOf(node)
|
||||
val idx = modules.withIndex().find { it.value===node }!!.index
|
||||
modules[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
@ -256,7 +257,7 @@ class Module(override val name: String,
|
||||
override fun definingScope(): INameScope = program.namespace
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(node is Statement && replacement is Statement)
|
||||
val idx = statements.indexOf(node)
|
||||
val idx = statements.withIndex().find { it.value===node }!!.index
|
||||
statements[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ import prog8.ast.processing.*
|
||||
import prog8.compiler.CompilationOptions
|
||||
import prog8.compiler.BeforeAsmGenerationAstChanger
|
||||
import prog8.optimizer.AssignmentTransformer
|
||||
import prog8.optimizer.FlattenAnonymousScopesAndNopRemover
|
||||
|
||||
|
||||
internal fun Program.checkValid(compilerOptions: CompilationOptions, errors: ErrorReporter) {
|
||||
@ -26,12 +25,23 @@ internal fun Program.reorderStatements() {
|
||||
reorder.applyModifications()
|
||||
}
|
||||
|
||||
internal fun Program.inlineSubroutines(): Int {
|
||||
val reorder = SubroutineInliner(this)
|
||||
reorder.visit(this)
|
||||
return reorder.applyModifications()
|
||||
}
|
||||
|
||||
internal fun Program.addTypecasts(errors: ErrorReporter) {
|
||||
val caster = TypecastsAdder(this, errors)
|
||||
caster.visit(this)
|
||||
caster.applyModifications()
|
||||
}
|
||||
|
||||
internal fun Program.verifyFunctionArgTypes() {
|
||||
val fixer = VerifyFunctionArgTypes(this)
|
||||
fixer.visit(this)
|
||||
}
|
||||
|
||||
internal fun Program.transformAssignments(errors: ErrorReporter) {
|
||||
val transform = AssignmentTransformer(this, errors)
|
||||
transform.visit(this)
|
||||
@ -71,7 +81,8 @@ internal fun Program.checkIdentifiers(errors: ErrorReporter) {
|
||||
}
|
||||
}
|
||||
|
||||
internal fun Program.removeNopsFlattenAnonScopes() {
|
||||
val flattener = FlattenAnonymousScopesAndNopRemover()
|
||||
flattener.visit(this)
|
||||
internal fun Program.variousCleanups() {
|
||||
val process = VariousCleanups()
|
||||
process.visit(this)
|
||||
process.applyModifications()
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ sealed class Expression: Node {
|
||||
abstract fun constValue(program: Program): NumericLiteralValue?
|
||||
abstract fun accept(visitor: IAstVisitor)
|
||||
abstract fun accept(visitor: AstWalker, parent: Node)
|
||||
abstract fun referencesIdentifiers(vararg name: String): Boolean // todo: remove this and add identifier usage tracking into CallGraph instead
|
||||
abstract fun referencesIdentifiers(vararg name: String): Boolean
|
||||
abstract fun inferType(program: Program): InferredTypes.InferredType
|
||||
|
||||
infix fun isSameAs(other: Expression): Boolean {
|
||||
@ -529,7 +529,7 @@ class ArrayLiteralValue(val type: InferredTypes.InferredType, // inferred be
|
||||
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(replacement is Expression)
|
||||
val idx = value.indexOf(node)
|
||||
val idx = value.withIndex().find { it.value===node }!!.index
|
||||
value[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
@ -731,6 +731,8 @@ data class IdentifierReference(val nameInSource: List<String>, override val posi
|
||||
fun targetVarDecl(namespace: INameScope): VarDecl? = targetStatement(namespace) as? VarDecl
|
||||
fun targetSubroutine(namespace: INameScope): Subroutine? = targetStatement(namespace) as? Subroutine
|
||||
|
||||
override fun equals(other: Any?) = other is IdentifierReference && other.nameInSource==nameInSource
|
||||
|
||||
override fun linkParents(parent: Node) {
|
||||
this.parent = parent
|
||||
}
|
||||
@ -798,7 +800,7 @@ class FunctionCall(override var target: IdentifierReference,
|
||||
if(node===target)
|
||||
target=replacement as IdentifierReference
|
||||
else {
|
||||
val idx = args.indexOf(node)
|
||||
val idx = args.withIndex().find { it.value===node }!!.index
|
||||
args[idx] = replacement as Expression
|
||||
}
|
||||
replacement.parent = this
|
||||
|
@ -326,7 +326,7 @@ internal class AstChecker(private val program: Program,
|
||||
}
|
||||
|
||||
override fun visit(repeatLoop: RepeatLoop) {
|
||||
if(repeatLoop.untilCondition.referencesIdentifiers("A", "X", "Y")) // TODO use callgraph?
|
||||
if(repeatLoop.untilCondition.referencesIdentifiers("A", "X", "Y"))
|
||||
errors.warn("using a register in the loop condition is risky (it could get clobbered)", repeatLoop.untilCondition.position)
|
||||
if(repeatLoop.untilCondition.inferType(program).typeOrElse(DataType.STRUCT) !in IntegerDatatypes)
|
||||
errors.err("condition value should be an integer type", repeatLoop.untilCondition.position)
|
||||
@ -334,7 +334,7 @@ internal class AstChecker(private val program: Program,
|
||||
}
|
||||
|
||||
override fun visit(whileLoop: WhileLoop) {
|
||||
if(whileLoop.condition.referencesIdentifiers("A", "X", "Y")) // TODO use callgraph?
|
||||
if(whileLoop.condition.referencesIdentifiers("A", "X", "Y"))
|
||||
errors.warn("using a register in the loop condition is risky (it could get clobbered)", whileLoop.condition.position)
|
||||
if(whileLoop.condition.inferType(program).typeOrElse(DataType.STRUCT) !in IntegerDatatypes)
|
||||
errors.err("condition value should be an integer type", whileLoop.condition.position)
|
||||
@ -463,7 +463,6 @@ internal class AstChecker(private val program: Program,
|
||||
}
|
||||
|
||||
// the initializer value can't refer to the variable itself (recursive definition)
|
||||
// TODO use callgraph for check?
|
||||
if(decl.value?.referencesIdentifiers(decl.name) == true || decl.arraysize?.index?.referencesIdentifiers(decl.name) == true) {
|
||||
err("recursive var declaration")
|
||||
}
|
||||
@ -733,7 +732,7 @@ internal class AstChecker(private val program: Program,
|
||||
}
|
||||
"**" -> {
|
||||
if(leftDt in IntegerDatatypes)
|
||||
errors.err("power operator requires floating point", expr.position)
|
||||
errors.err("power operator requires floating point operands", expr.position)
|
||||
}
|
||||
"and", "or", "xor" -> {
|
||||
// only integer numeric operands accepted, and if literal constants, only boolean values accepted (0 or 1)
|
||||
|
@ -10,6 +10,46 @@ import prog8.ast.statements.*
|
||||
internal class AstVariousTransforms(private val program: Program) : AstWalker() {
|
||||
private val noModifications = emptyList<IAstModification>()
|
||||
|
||||
override fun after(functionCallStatement: FunctionCallStatement, parent: Node): Iterable<IAstModification> {
|
||||
if(functionCallStatement.target.nameInSource == listOf("swap")) {
|
||||
// if x and y are both just identifiers, do not rewrite (there should be asm generation for that)
|
||||
// otherwise:
|
||||
// rewrite swap(x,y) as follows:
|
||||
// - declare a temp variable of the same datatype
|
||||
// - temp = x, x = y, y= temp
|
||||
val first = functionCallStatement.args[0]
|
||||
val second = functionCallStatement.args[1]
|
||||
if(first !is IdentifierReference && second !is IdentifierReference) {
|
||||
val dt = first.inferType(program).typeOrElse(DataType.STRUCT)
|
||||
val tempname = "prog8_swaptmp_${functionCallStatement.hashCode()}"
|
||||
val tempvardecl = VarDecl(VarDeclType.VAR, dt, ZeropageWish.DONTCARE, null, tempname, null, null, isArray = false, autogeneratedDontRemove = true, position = first.position)
|
||||
val tempvar = IdentifierReference(listOf(tempname), first.position)
|
||||
val assignTemp = Assignment(
|
||||
AssignTarget(null, tempvar, null, null, first.position),
|
||||
null,
|
||||
first,
|
||||
first.position
|
||||
)
|
||||
val assignFirst = Assignment(
|
||||
AssignTarget.fromExpr(first),
|
||||
null,
|
||||
second,
|
||||
first.position
|
||||
)
|
||||
val assignSecond = Assignment(
|
||||
AssignTarget.fromExpr(second),
|
||||
null,
|
||||
tempvar,
|
||||
first.position
|
||||
)
|
||||
val scope = AnonymousScope(mutableListOf(tempvardecl, assignTemp, assignFirst, assignSecond), first.position)
|
||||
return listOf(IAstModification.ReplaceNode(functionCallStatement, scope, parent))
|
||||
}
|
||||
}
|
||||
|
||||
return noModifications
|
||||
}
|
||||
|
||||
override fun before(functionCall: FunctionCall, parent: Node): Iterable<IAstModification> {
|
||||
if(functionCall.target.nameInSource.size==1 && functionCall.target.nameInSource[0]=="lsb") {
|
||||
// lsb(...) is just an alias for type cast to ubyte, so replace with "... as ubyte"
|
||||
@ -43,13 +83,16 @@ internal class AstVariousTransforms(private val program: Program) : AstWalker()
|
||||
val symbolsInSub = subroutine.allDefinedSymbols()
|
||||
val namesInSub = symbolsInSub.map{ it.first }.toSet()
|
||||
if(subroutine.asmAddress==null) {
|
||||
if(subroutine.asmParameterRegisters.isEmpty()) {
|
||||
return subroutine.parameters
|
||||
.filter { it.name !in namesInSub }
|
||||
.map {
|
||||
val vardecl = ParameterVarDecl(it.name, it.type, subroutine.position)
|
||||
IAstModification.InsertFirst(vardecl, subroutine)
|
||||
}
|
||||
if(subroutine.asmParameterRegisters.isEmpty() && subroutine.parameters.isNotEmpty()) {
|
||||
val vars = subroutine.statements.filterIsInstance<VarDecl>().map { it.name }.toSet()
|
||||
if(!vars.containsAll(subroutine.parameters.map{it.name})) {
|
||||
return subroutine.parameters
|
||||
.filter { it.name !in namesInSub }
|
||||
.map {
|
||||
val vardecl = ParameterVarDecl(it.name, it.type, subroutine.position)
|
||||
IAstModification.InsertFirst(vardecl, subroutine)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -104,11 +147,11 @@ internal class AstVariousTransforms(private val program: Program) : AstWalker()
|
||||
// this array literal is part of an expression, turn it into an identifier reference
|
||||
val litval2 = array.cast(arrayDt.typeOrElse(DataType.STRUCT))
|
||||
if(litval2!=null && litval2!=array) {
|
||||
val vardecl = VarDecl.createAuto(litval2)
|
||||
val identifier = IdentifierReference(listOf(vardecl.name), vardecl.position)
|
||||
val vardecl2 = VarDecl.createAuto(litval2)
|
||||
val identifier = IdentifierReference(listOf(vardecl2.name), vardecl2.position)
|
||||
return listOf(
|
||||
IAstModification.ReplaceNode(array, identifier, parent),
|
||||
IAstModification.InsertFirst(vardecl, array.definingScope() as Node)
|
||||
IAstModification.InsertFirst(vardecl2, array.definingScope() as Node)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@ -52,7 +52,7 @@ interface IAstModification {
|
||||
class InsertAfter(val after: Statement, val stmt: Statement, val parent: Node) : IAstModification {
|
||||
override fun perform() {
|
||||
if(parent is INameScope) {
|
||||
val idx = parent.statements.indexOf(after)+1
|
||||
val idx = parent.statements.withIndex().find { it.value===after }!!.index + 1
|
||||
parent.statements.add(idx, stmt)
|
||||
stmt.linkParents(parent)
|
||||
} else {
|
||||
|
39
compiler/src/prog8/ast/processing/SubroutineInliner.kt
Normal file
39
compiler/src/prog8/ast/processing/SubroutineInliner.kt
Normal file
@ -0,0 +1,39 @@
|
||||
package prog8.ast.processing
|
||||
|
||||
import prog8.ast.Node
|
||||
import prog8.ast.Program
|
||||
import prog8.ast.statements.*
|
||||
import prog8.optimizer.CallGraph
|
||||
|
||||
|
||||
internal class SubroutineInliner(private val program: Program) : AstWalker() {
|
||||
private val noModifications = emptyList<IAstModification>()
|
||||
private val callgraph = CallGraph(program)
|
||||
|
||||
override fun after(subroutine: Subroutine, parent: Node): Iterable<IAstModification> {
|
||||
|
||||
if(!subroutine.isAsmSubroutine && callgraph.calledBy[subroutine]!=null && subroutine.containsCodeOrVars()) {
|
||||
|
||||
// TODO for now, inlined subroutines can't have parameters or local variables - improve this
|
||||
if(subroutine.parameters.isEmpty() && subroutine.containsNoVars()) {
|
||||
if (subroutine.countStatements() <= 5) {
|
||||
if (callgraph.calledBy.getValue(subroutine).size == 1 || !subroutine.statements.any { it.expensiveToInline })
|
||||
return inline(subroutine)
|
||||
}
|
||||
}
|
||||
}
|
||||
return noModifications
|
||||
}
|
||||
|
||||
private fun inline(subroutine: Subroutine): Iterable<IAstModification> {
|
||||
val calls = callgraph.calledBy.getValue(subroutine)
|
||||
return calls.map {
|
||||
call -> IAstModification.ReplaceNode(
|
||||
call,
|
||||
AnonymousScope(subroutine.statements, call.position),
|
||||
call.parent
|
||||
)
|
||||
}.plus(IAstModification.Remove(subroutine, subroutine.parent))
|
||||
}
|
||||
|
||||
}
|
@ -87,7 +87,9 @@ class TypecastsAdder(val program: Program, val errors: ErrorReporter) : AstWalke
|
||||
|
||||
private fun afterFunctionCallArgs(call: IFunctionCall, scope: INameScope): Iterable<IAstModification> {
|
||||
// see if a typecast is needed to convert the arguments into the required parameter's type
|
||||
return when(val sub = call.target.targetStatement(scope)) {
|
||||
val modifications = mutableListOf<IAstModification>()
|
||||
|
||||
when(val sub = call.target.targetStatement(scope)) {
|
||||
is Subroutine -> {
|
||||
for(arg in sub.parameters.zip(call.args.withIndex())) {
|
||||
val argItype = arg.second.value.inferType(program)
|
||||
@ -96,48 +98,55 @@ class TypecastsAdder(val program: Program, val errors: ErrorReporter) : AstWalke
|
||||
val requiredType = arg.first.type
|
||||
if (requiredType != argtype) {
|
||||
if (argtype isAssignableTo requiredType) {
|
||||
return listOf(IAstModification.ReplaceNode(
|
||||
modifications += IAstModification.ReplaceNode(
|
||||
call.args[arg.second.index],
|
||||
TypecastExpression(arg.second.value, requiredType, true, arg.second.value.position),
|
||||
call as Node))
|
||||
call as Node)
|
||||
} else if(requiredType == DataType.UWORD && argtype in PassByReferenceDatatypes) {
|
||||
// we allow STR/ARRAY values in place of UWORD parameters. Take their address instead.
|
||||
return listOf(IAstModification.ReplaceNode(
|
||||
modifications += IAstModification.ReplaceNode(
|
||||
call.args[arg.second.index],
|
||||
AddressOf(arg.second.value as IdentifierReference, arg.second.value.position),
|
||||
call as Node))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
emptyList()
|
||||
}
|
||||
is BuiltinFunctionStatementPlaceholder -> {
|
||||
val func = BuiltinFunctions.getValue(sub.name)
|
||||
if(func.pure) {
|
||||
// non-pure functions don't get automatic typecasts because sometimes they act directly on their parameters
|
||||
for (arg in func.parameters.zip(call.args.withIndex())) {
|
||||
val argItype = arg.second.value.inferType(program)
|
||||
if (argItype.isKnown) {
|
||||
val argtype = argItype.typeOrElse(DataType.STRUCT)
|
||||
if (arg.first.possibleDatatypes.any { argtype == it })
|
||||
continue
|
||||
for (possibleType in arg.first.possibleDatatypes) {
|
||||
if (argtype isAssignableTo possibleType) {
|
||||
return listOf(IAstModification.ReplaceNode(
|
||||
call as Node)
|
||||
} else if(arg.second.value is NumericLiteralValue) {
|
||||
try {
|
||||
val castedValue = (arg.second.value as NumericLiteralValue).cast(requiredType)
|
||||
modifications += IAstModification.ReplaceNode(
|
||||
call.args[arg.second.index],
|
||||
TypecastExpression(arg.second.value, possibleType, true, arg.second.value.position),
|
||||
call as Node))
|
||||
castedValue,
|
||||
call as Node)
|
||||
} catch (x: ExpressionError) {
|
||||
// no cast possible
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
emptyList()
|
||||
}
|
||||
null -> emptyList()
|
||||
is BuiltinFunctionStatementPlaceholder -> {
|
||||
val func = BuiltinFunctions.getValue(sub.name)
|
||||
for (arg in func.parameters.zip(call.args.withIndex())) {
|
||||
val argItype = arg.second.value.inferType(program)
|
||||
if (argItype.isKnown) {
|
||||
val argtype = argItype.typeOrElse(DataType.STRUCT)
|
||||
if (arg.first.possibleDatatypes.any { argtype == it })
|
||||
continue
|
||||
for (possibleType in arg.first.possibleDatatypes) {
|
||||
if (argtype isAssignableTo possibleType) {
|
||||
modifications += IAstModification.ReplaceNode(
|
||||
call.args[arg.second.index],
|
||||
TypecastExpression(arg.second.value, possibleType, true, arg.second.value.position),
|
||||
call as Node)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
null -> { }
|
||||
else -> throw FatalAstException("call to something weird $sub ${call.target}")
|
||||
}
|
||||
|
||||
return modifications
|
||||
}
|
||||
|
||||
override fun after(typecast: TypecastExpression, parent: Node): Iterable<IAstModification> {
|
||||
|
43
compiler/src/prog8/ast/processing/VariousCleanups.kt
Normal file
43
compiler/src/prog8/ast/processing/VariousCleanups.kt
Normal file
@ -0,0 +1,43 @@
|
||||
package prog8.ast.processing
|
||||
|
||||
import prog8.ast.INameScope
|
||||
import prog8.ast.Node
|
||||
import prog8.ast.expressions.NumericLiteralValue
|
||||
import prog8.ast.expressions.TypecastExpression
|
||||
import prog8.ast.statements.AnonymousScope
|
||||
import prog8.ast.statements.NopStatement
|
||||
|
||||
|
||||
internal class VariousCleanups: AstWalker() {
|
||||
private val noModifications = emptyList<IAstModification>()
|
||||
|
||||
override fun before(nopStatement: NopStatement, parent: Node): Iterable<IAstModification> {
|
||||
return listOf(IAstModification.Remove(nopStatement, parent))
|
||||
}
|
||||
|
||||
override fun before(scope: AnonymousScope, parent: Node): Iterable<IAstModification> {
|
||||
return if(parent is INameScope)
|
||||
listOf(ScopeFlatten(scope, parent as INameScope))
|
||||
else
|
||||
noModifications
|
||||
}
|
||||
|
||||
class ScopeFlatten(val scope: AnonymousScope, val into: INameScope) : IAstModification {
|
||||
override fun perform() {
|
||||
val idx = into.statements.indexOf(scope)
|
||||
if(idx>=0) {
|
||||
into.statements.addAll(idx+1, scope.statements)
|
||||
into.statements.remove(scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun before(typecast: TypecastExpression, parent: Node): Iterable<IAstModification> {
|
||||
if(typecast.expression is NumericLiteralValue) {
|
||||
val value = (typecast.expression as NumericLiteralValue).cast(typecast.type)
|
||||
return listOf(IAstModification.ReplaceNode(typecast, value, parent))
|
||||
}
|
||||
|
||||
return noModifications
|
||||
}
|
||||
}
|
42
compiler/src/prog8/ast/processing/VerifyFunctionArgTypes.kt
Normal file
42
compiler/src/prog8/ast/processing/VerifyFunctionArgTypes.kt
Normal file
@ -0,0 +1,42 @@
|
||||
package prog8.ast.processing
|
||||
|
||||
import prog8.ast.IFunctionCall
|
||||
import prog8.ast.INameScope
|
||||
import prog8.ast.Program
|
||||
import prog8.ast.base.DataType
|
||||
import prog8.ast.expressions.FunctionCall
|
||||
import prog8.ast.statements.BuiltinFunctionStatementPlaceholder
|
||||
import prog8.ast.statements.FunctionCallStatement
|
||||
import prog8.ast.statements.Subroutine
|
||||
import prog8.compiler.CompilerException
|
||||
import prog8.functions.BuiltinFunctions
|
||||
|
||||
class VerifyFunctionArgTypes(val program: Program) : IAstVisitor {
|
||||
|
||||
override fun visit(functionCall: FunctionCall)
|
||||
= checkTypes(functionCall as IFunctionCall, functionCall.definingScope())
|
||||
|
||||
override fun visit(functionCallStatement: FunctionCallStatement)
|
||||
= checkTypes(functionCallStatement as IFunctionCall, functionCallStatement.definingScope())
|
||||
|
||||
private fun checkTypes(call: IFunctionCall, scope: INameScope) {
|
||||
val argtypes = call.args.map { it.inferType(program).typeOrElse(DataType.STRUCT) }
|
||||
val target = call.target.targetStatement(scope)
|
||||
when(target) {
|
||||
is Subroutine -> {
|
||||
val paramtypes = target.parameters.map { it.type }
|
||||
if(argtypes!=paramtypes)
|
||||
throw CompilerException("parameter type mismatch $call")
|
||||
}
|
||||
is BuiltinFunctionStatementPlaceholder -> {
|
||||
val func = BuiltinFunctions.getValue(target.name)
|
||||
val paramtypes = func.parameters.map { it.possibleDatatypes }
|
||||
for(x in argtypes.zip(paramtypes)) {
|
||||
if(x.first !in x.second)
|
||||
throw CompilerException("parameter type mismatch $call")
|
||||
}
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
@ -69,7 +69,7 @@ class Block(override val name: String,
|
||||
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(replacement is Statement)
|
||||
val idx = statements.indexOf(node)
|
||||
val idx = statements.withIndex().find { it.value===node }!!.index
|
||||
statements[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
@ -340,7 +340,7 @@ class ArrayIndex(var index: Expression, override val position: Position) : Node
|
||||
open class Assignment(var target: AssignTarget, var aug_op : String?, var value: Expression, override val position: Position) : Statement() {
|
||||
override lateinit var parent: Node
|
||||
override val expensiveToInline
|
||||
get() = value !is NumericLiteralValue
|
||||
get() = value is BinaryExpression
|
||||
|
||||
override fun linkParents(parent: Node) {
|
||||
this.parent = parent
|
||||
@ -569,7 +569,7 @@ class FunctionCallStatement(override var target: IdentifierReference,
|
||||
if(node===target)
|
||||
target = replacement as IdentifierReference
|
||||
else {
|
||||
val idx = args.indexOf(node)
|
||||
val idx = args.withIndex().find { it.value===node }!!.index
|
||||
args[idx] = replacement as Expression
|
||||
}
|
||||
replacement.parent = this
|
||||
@ -619,7 +619,7 @@ class AnonymousScope(override var statements: MutableList<Statement>,
|
||||
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(replacement is Statement)
|
||||
val idx = statements.indexOf(node)
|
||||
val idx = statements.withIndex().find { it.value===node }!!.index
|
||||
statements[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
@ -668,8 +668,6 @@ class Subroutine(override val name: String,
|
||||
get() = statements.any { it.expensiveToInline }
|
||||
|
||||
override lateinit var parent: Node
|
||||
val calledBy = mutableListOf<Node>()
|
||||
val calls = mutableSetOf<Subroutine>()
|
||||
|
||||
val scopedname: String by lazy { makeScopedName(name) }
|
||||
|
||||
@ -681,7 +679,7 @@ class Subroutine(override val name: String,
|
||||
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(replacement is Statement)
|
||||
val idx = statements.indexOf(node)
|
||||
val idx = statements.withIndex().find { it.value===node }!!.index
|
||||
statements[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
@ -700,6 +698,32 @@ class Subroutine(override val name: String,
|
||||
.filter { it is InlineAssembly }
|
||||
.map { (it as InlineAssembly).assembly }
|
||||
.count { " rti" in it || "\trti" in it || " rts" in it || "\trts" in it || " jmp" in it || "\tjmp" in it }
|
||||
|
||||
fun countStatements(): Int {
|
||||
class StatementCounter: IAstVisitor {
|
||||
var count = 0
|
||||
|
||||
override fun visit(block: Block) {
|
||||
count += block.statements.size
|
||||
super.visit(block)
|
||||
}
|
||||
|
||||
override fun visit(subroutine: Subroutine) {
|
||||
count += subroutine.statements.size
|
||||
super.visit(subroutine)
|
||||
}
|
||||
|
||||
override fun visit(scope: AnonymousScope) {
|
||||
count += scope.statements.size
|
||||
super.visit(scope)
|
||||
}
|
||||
}
|
||||
|
||||
// the (recursive) number of statements
|
||||
val counter = StatementCounter()
|
||||
counter.visit(this)
|
||||
return counter.count
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -899,7 +923,7 @@ class WhenStatement(var condition: Expression,
|
||||
if(node===condition)
|
||||
condition = replacement as Expression
|
||||
else {
|
||||
val idx = choices.indexOf(node)
|
||||
val idx = choices.withIndex().find { it.value===node }!!.index
|
||||
choices[idx] = replacement as WhenChoice
|
||||
}
|
||||
replacement.parent = this
|
||||
@ -966,7 +990,7 @@ class StructDecl(override val name: String,
|
||||
|
||||
override fun replaceChildNode(node: Node, replacement: Node) {
|
||||
require(replacement is Statement)
|
||||
val idx = statements.indexOf(node)
|
||||
val idx = statements.withIndex().find { it.value===node }!!.index
|
||||
statements[idx] = replacement
|
||||
replacement.parent = this
|
||||
}
|
||||
|
@ -42,7 +42,7 @@ fun compileProgram(filepath: Path,
|
||||
optimizeAst(programAst, errors)
|
||||
postprocessAst(programAst, errors, compilationOptions)
|
||||
|
||||
// printAst(programAst) // TODO
|
||||
// printAst(programAst)
|
||||
|
||||
if(writeAssembly)
|
||||
programName = writeAssembly(programAst, errors, outputDir, optimize, compilationOptions)
|
||||
@ -146,10 +146,10 @@ private fun processAst(programAst: Program, errors: ErrorReporter, compilerOptio
|
||||
errors.handle()
|
||||
programAst.constantFold(errors)
|
||||
errors.handle()
|
||||
programAst.removeNopsFlattenAnonScopes()
|
||||
programAst.reorderStatements()
|
||||
programAst.addTypecasts(errors)
|
||||
errors.handle()
|
||||
programAst.variousCleanups()
|
||||
programAst.checkValid(compilerOptions, errors)
|
||||
errors.handle()
|
||||
programAst.checkIdentifiers(errors)
|
||||
@ -163,9 +163,10 @@ private fun optimizeAst(programAst: Program, errors: ErrorReporter) {
|
||||
// keep optimizing expressions and statements until no more steps remain
|
||||
val optsDone1 = programAst.simplifyExpressions()
|
||||
val optsDone2 = programAst.optimizeStatements(errors)
|
||||
val optsDone3 = programAst.inlineSubroutines()
|
||||
programAst.constantFold(errors) // because simplified statements and expressions could give rise to more constants that can be folded away:
|
||||
errors.handle()
|
||||
if (optsDone1 + optsDone2 == 0)
|
||||
if (optsDone1 + optsDone2 + optsDone3 == 0)
|
||||
break
|
||||
}
|
||||
|
||||
@ -179,11 +180,12 @@ private fun postprocessAst(programAst: Program, errors: ErrorReporter, compilerO
|
||||
errors.handle()
|
||||
programAst.addTypecasts(errors)
|
||||
errors.handle()
|
||||
programAst.removeNopsFlattenAnonScopes()
|
||||
programAst.variousCleanups()
|
||||
programAst.checkValid(compilerOptions, errors) // check if final tree is still valid
|
||||
errors.handle()
|
||||
programAst.checkRecursion(errors) // check if there are recursive subroutine calls
|
||||
errors.handle()
|
||||
programAst.verifyFunctionArgTypes()
|
||||
}
|
||||
|
||||
private fun writeAssembly(programAst: Program, errors: ErrorReporter, outputDir: Path,
|
||||
|
@ -691,7 +691,6 @@ internal class AsmGen(private val program: Program,
|
||||
loopEndLabels.push(endLabel)
|
||||
loopContinueLabels.push(whileLabel)
|
||||
out(whileLabel)
|
||||
// TODO optimize for the simple cases, can we avoid stack use?
|
||||
expressionsAsmGen.translateExpression(stmt.condition)
|
||||
val conditionDt = stmt.condition.inferType(program)
|
||||
if(!conditionDt.isKnown)
|
||||
@ -720,7 +719,6 @@ internal class AsmGen(private val program: Program,
|
||||
loopEndLabels.push(endLabel)
|
||||
loopContinueLabels.push(repeatLabel)
|
||||
out(repeatLabel)
|
||||
// TODO optimize this for the simple cases, can we avoid stack use?
|
||||
translate(stmt.body)
|
||||
expressionsAsmGen.translateExpression(stmt.untilCondition)
|
||||
val conditionDt = stmt.untilCondition.inferType(program)
|
||||
|
@ -46,7 +46,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
}
|
||||
|
||||
// TODO this is the FALLBACK:
|
||||
// TODO this is the slow FALLBACK, eventually we don't want to have to use it anymore:
|
||||
errors.warn("using suboptimal in-place assignment code (this should still be optimized)", assign.position)
|
||||
val normalAssignment = assign.asDesugaredNonaugmented()
|
||||
return translateNormalAssignment(normalAssignment)
|
||||
@ -91,7 +91,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
else -> throw AssemblyError("assignment to array: invalid array dt $arrayDt")
|
||||
}
|
||||
} else {
|
||||
TODO()
|
||||
TODO("aug assignment to element in array/string")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -155,45 +155,120 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
sta $targetName+1,y
|
||||
""")
|
||||
}
|
||||
DataType.ARRAY_F -> return false // TODO optimize?
|
||||
DataType.ARRAY_F -> return false // TODO optimize instead of fallback?
|
||||
else -> throw AssemblyError("assignment to array: invalid array dt $arrayDt")
|
||||
}
|
||||
return true
|
||||
}
|
||||
is AddressOf -> {
|
||||
TODO("$assign")
|
||||
TODO("assign address into array $assign")
|
||||
}
|
||||
is DirectMemoryRead -> {
|
||||
TODO("$assign")
|
||||
TODO("assign memory read into array $assign")
|
||||
}
|
||||
is ArrayIndexedExpression -> {
|
||||
if(assign.aug_op != "setvalue")
|
||||
return false // we don't put effort into optimizing anything beside simple assignment
|
||||
val valueArrayExpr = assign.value as ArrayIndexedExpression
|
||||
val valueArrayIndex = valueArrayExpr.arrayspec.index
|
||||
if(valueArrayIndex is RegisterExpr || arrayIndex is RegisterExpr) {
|
||||
throw AssemblyError("cannot generate code for array operations with registers as index")
|
||||
}
|
||||
val valueVariablename = asmgen.asmIdentifierName(valueArrayExpr.identifier)
|
||||
val valueDt = valueArrayExpr.identifier.inferType(program).typeOrElse(DataType.STRUCT)
|
||||
when(arrayDt) {
|
||||
DataType.ARRAY_UB -> {
|
||||
if (arrayDt != DataType.ARRAY_B && arrayDt != DataType.ARRAY_UB && arrayDt != DataType.STR)
|
||||
throw AssemblyError("assignment to array: expected byte array or string")
|
||||
if (assign.aug_op == "setvalue") {
|
||||
if (valueArrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #${valueArrayIndex.number.toHex()}")
|
||||
else
|
||||
asmgen.translateArrayIndexIntoY(valueArrayExpr)
|
||||
asmgen.out(" lda $valueVariablename,y")
|
||||
if (arrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #${arrayIndex.number.toHex()}")
|
||||
else
|
||||
asmgen.translateArrayIndexIntoY(targetArray)
|
||||
asmgen.out(" sta $targetName,y")
|
||||
} else {
|
||||
return false // TODO optimize
|
||||
}
|
||||
DataType.ARRAY_UB, DataType.ARRAY_B, DataType.STR -> {
|
||||
if (valueArrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #${valueArrayIndex.number.toHex()}")
|
||||
else
|
||||
asmgen.translateArrayIndexIntoY(valueArrayExpr)
|
||||
asmgen.out(" lda $valueVariablename,y")
|
||||
if (arrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #${arrayIndex.number.toHex()}")
|
||||
else
|
||||
asmgen.translateArrayIndexIntoY(targetArray)
|
||||
asmgen.out(" sta $targetName,y")
|
||||
}
|
||||
DataType.ARRAY_UW, DataType.ARRAY_W -> {
|
||||
if (valueArrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #2*${valueArrayIndex.number.toHex()}")
|
||||
else {
|
||||
asmgen.translateArrayIndexIntoA(valueArrayExpr)
|
||||
asmgen.out(" asl a | tay")
|
||||
}
|
||||
asmgen.out("""
|
||||
lda $valueVariablename,y
|
||||
pha
|
||||
lda $valueVariablename+1,y
|
||||
pha
|
||||
""")
|
||||
if (arrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #2*${arrayIndex.number.toHex()}")
|
||||
else {
|
||||
asmgen.translateArrayIndexIntoA(targetArray)
|
||||
asmgen.out(" asl a | tay")
|
||||
}
|
||||
asmgen.out("""
|
||||
pla
|
||||
sta $targetName+1,y
|
||||
pla
|
||||
sta $targetName,y
|
||||
""")
|
||||
return true
|
||||
}
|
||||
DataType.ARRAY_F -> {
|
||||
if (valueArrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #5*${valueArrayIndex.number.toHex()}")
|
||||
else {
|
||||
asmgen.translateArrayIndexIntoA(valueArrayExpr)
|
||||
asmgen.out("""
|
||||
sta ${C64Zeropage.SCRATCH_REG}
|
||||
asl a
|
||||
asl a
|
||||
clc
|
||||
adc ${C64Zeropage.SCRATCH_REG}
|
||||
tay
|
||||
""")
|
||||
}
|
||||
asmgen.out("""
|
||||
lda $valueVariablename,y
|
||||
pha
|
||||
lda $valueVariablename+1,y
|
||||
pha
|
||||
lda $valueVariablename+2,y
|
||||
pha
|
||||
lda $valueVariablename+3,y
|
||||
pha
|
||||
lda $valueVariablename+4,y
|
||||
pha
|
||||
""")
|
||||
if (arrayIndex is NumericLiteralValue)
|
||||
asmgen.out(" ldy #5*${arrayIndex.number.toHex()}")
|
||||
else {
|
||||
asmgen.translateArrayIndexIntoA(targetArray)
|
||||
asmgen.out("""
|
||||
sta ${C64Zeropage.SCRATCH_REG}
|
||||
asl a
|
||||
asl a
|
||||
clc
|
||||
adc ${C64Zeropage.SCRATCH_REG}
|
||||
tay
|
||||
""")
|
||||
}
|
||||
asmgen.out("""
|
||||
pla
|
||||
sta $targetName+4,y
|
||||
pla
|
||||
sta $targetName+3,y
|
||||
pla
|
||||
sta $targetName+2,y
|
||||
pla
|
||||
sta $targetName+1,y
|
||||
pla
|
||||
sta $targetName,y
|
||||
""")
|
||||
return true
|
||||
}
|
||||
DataType.ARRAY_B -> TODO()
|
||||
DataType.ARRAY_UW -> TODO()
|
||||
DataType.ARRAY_W -> TODO()
|
||||
DataType.ARRAY_F -> TODO()
|
||||
else -> throw AssemblyError("assignment to array: invalid array dt")
|
||||
}
|
||||
return true
|
||||
@ -219,13 +294,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda #$hexValue | sta $hexAddr")
|
||||
"+=" -> asmgen.out(" lda $hexAddr | clc | adc #$hexValue | sta $hexAddr")
|
||||
"-=" -> asmgen.out(" lda $hexAddr | sec | sbc #$hexValue | sta $hexAddr")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("membyte /= const $hexValue")
|
||||
"*=" -> TODO("membyte *= const $hexValue")
|
||||
"&=" -> asmgen.out(" lda $hexAddr | and #$hexValue | sta $hexAddr")
|
||||
"|=" -> asmgen.out(" lda $hexAddr | ora #$hexValue | sta $hexAddr")
|
||||
"^=" -> asmgen.out(" lda $hexAddr | eor #$hexValue | sta $hexAddr")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("membyte %= const $hexValue")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -258,9 +332,8 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
Register.Y -> asmgen.out(" sty ${C64Zeropage.SCRATCH_B1} | lda $hexAddr | sec | sbc ${C64Zeropage.SCRATCH_B1} | sta $hexAddr")
|
||||
}
|
||||
}
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("membyte /= register")
|
||||
"*=" -> TODO("membyte *= register")
|
||||
"&=" -> {
|
||||
when ((assign.value as RegisterExpr).register) {
|
||||
Register.A -> asmgen.out(" and $hexAddr | sta $hexAddr")
|
||||
@ -282,7 +355,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
Register.Y -> asmgen.out(" tya | eor $hexAddr | sta $hexAddr")
|
||||
}
|
||||
}
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("membyte %= register")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -291,15 +364,22 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
is IdentifierReference -> {
|
||||
val sourceName = asmgen.asmIdentifierName(assign.value as IdentifierReference)
|
||||
TODO("$assign")
|
||||
when(assign.aug_op) {
|
||||
"setvalue" -> asmgen.out(" lda $sourceName | sta $hexAddr")
|
||||
else -> TODO("membyte aug.assign variable $assign")
|
||||
}
|
||||
return true
|
||||
}
|
||||
is DirectMemoryRead -> {
|
||||
val memory = (assign.value as DirectMemoryRead).addressExpression.constValue(program)!!.number.toHex()
|
||||
asmgen.out(" lda $memory | sta $hexAddr")
|
||||
when(assign.aug_op) {
|
||||
"setvalue" -> asmgen.out(" lda $memory | sta $hexAddr")
|
||||
else -> TODO("membyte aug.assign memread $assign")
|
||||
}
|
||||
return true
|
||||
}
|
||||
is ArrayIndexedExpression -> {
|
||||
TODO("$assign")
|
||||
TODO("membyte = array value $assign")
|
||||
}
|
||||
is AddressOf -> throw AssemblyError("can't assign address to byte")
|
||||
else -> {
|
||||
@ -312,7 +392,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
|
||||
private fun inplaceAssignToNonConstMemoryByte(assign: Assignment): Boolean {
|
||||
// target address is not constant, so evaluate it on the stack
|
||||
// target address is not constant, so evaluate it from the stack
|
||||
asmgen.translateExpression(assign.target.memoryAddress!!.addressExpression)
|
||||
asmgen.out("""
|
||||
inx
|
||||
@ -330,13 +410,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda #$hexValue | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
"+=" -> asmgen.out(" lda (${C64Zeropage.SCRATCH_W1}),y | clc | adc #$hexValue | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
"-=" -> asmgen.out(" lda (${C64Zeropage.SCRATCH_W1}),y | sec | sbc #$hexValue | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("membyte /= const $hexValue")
|
||||
"*=" -> TODO("membyte *= const $hexValue")
|
||||
"&=" -> asmgen.out(" lda (${C64Zeropage.SCRATCH_W1}),y | and #$hexValue | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
"|=" -> asmgen.out(" lda (${C64Zeropage.SCRATCH_W1}),y | ora #$hexValue | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
"^=" -> asmgen.out(" lda (${C64Zeropage.SCRATCH_W1}),y | eor #$hexValue | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("membyte %= const $hexValue")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -370,9 +449,8 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
Register.Y -> asmgen.out(" tya | ldy #0 | sta ${C64Zeropage.SCRATCH_B1} | lda (${C64Zeropage.SCRATCH_W1}),y | sec | sbc ${C64Zeropage.SCRATCH_B1} | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
}
|
||||
}
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("membyte /= register")
|
||||
"*=" -> TODO("membyte *= register")
|
||||
"&=" -> {
|
||||
when ((assign.value as RegisterExpr).register) {
|
||||
Register.A -> asmgen.out(" ldy #0 | and (${C64Zeropage.SCRATCH_W1}),y| sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
@ -394,7 +472,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
Register.Y -> asmgen.out(" tya | ldy #0 | eor (${C64Zeropage.SCRATCH_W1}),y | sta (${C64Zeropage.SCRATCH_W1}),y")
|
||||
}
|
||||
}
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("membyte %= register")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -403,13 +481,10 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
is IdentifierReference -> {
|
||||
val sourceName = asmgen.asmIdentifierName(assign.value as IdentifierReference)
|
||||
TODO("$assign")
|
||||
}
|
||||
is AddressOf -> {
|
||||
TODO("$assign")
|
||||
TODO("membyte = variable $assign")
|
||||
}
|
||||
is DirectMemoryRead -> {
|
||||
TODO("$assign")
|
||||
TODO("membyte = memread $assign")
|
||||
}
|
||||
is ArrayIndexedExpression -> {
|
||||
if (assign.aug_op == "setvalue") {
|
||||
@ -436,6 +511,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
return true
|
||||
}
|
||||
is AddressOf -> throw AssemblyError("can't assign memory address to memory byte")
|
||||
else -> {
|
||||
fallbackAssignment(assign)
|
||||
return true
|
||||
@ -459,13 +535,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda #$hexValue | sta $targetName")
|
||||
"+=" -> asmgen.out(" lda $targetName | clc | adc #$hexValue | sta $targetName")
|
||||
"-=" -> asmgen.out(" lda $targetName | sec | sbc #$hexValue | sta $targetName")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("variable /= const $hexValue")
|
||||
"*=" -> TODO("variable *= const $hexValue")
|
||||
"&=" -> asmgen.out(" lda $targetName | and #$hexValue | sta $targetName")
|
||||
"|=" -> asmgen.out(" lda $targetName | ora #$hexValue | sta $targetName")
|
||||
"^=" -> asmgen.out(" lda $targetName | eor #$hexValue | sta $targetName")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("variable %= const $hexValue")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -485,7 +560,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
Register.Y -> asmgen.out(" sty $targetName")
|
||||
}
|
||||
}
|
||||
else -> TODO("$assign")
|
||||
else -> TODO("aug.assign variable = register $assign")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -495,13 +570,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda $sourceName | sta $targetName")
|
||||
"+=" -> asmgen.out(" lda $targetName | clc | adc $sourceName | sta $targetName")
|
||||
"-=" -> asmgen.out(" lda $targetName | sec | sbc $sourceName | sta $targetName")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("variable /= variable")
|
||||
"*=" -> TODO("variable *= variable")
|
||||
"&=" -> asmgen.out(" lda $targetName | and $sourceName | sta $targetName")
|
||||
"|=" -> asmgen.out(" lda $targetName | ora $sourceName | sta $targetName")
|
||||
"^=" -> asmgen.out(" lda $targetName | eor $sourceName | sta $targetName")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("variable %= variable")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -509,7 +583,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
return true
|
||||
}
|
||||
is DirectMemoryRead -> {
|
||||
TODO("$assign")
|
||||
TODO("variable = memory read $assign")
|
||||
}
|
||||
is ArrayIndexedExpression -> {
|
||||
if (assign.aug_op == "setvalue") {
|
||||
@ -572,7 +646,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
sta $targetName+1
|
||||
""")
|
||||
}
|
||||
else -> TODO("$assign")
|
||||
else -> TODO("variable aug.assign ${assign.aug_op} const $hexNumber")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -617,7 +691,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
return true
|
||||
}
|
||||
else -> {
|
||||
TODO("$assign")
|
||||
TODO("variable aug.assign variable")
|
||||
}
|
||||
}
|
||||
return true
|
||||
@ -714,7 +788,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
""")
|
||||
return true
|
||||
}
|
||||
else -> TODO("$assign")
|
||||
else -> TODO("float const value aug.assign $assign")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -727,7 +801,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> assignFromFloatVariable(assign.target, assign.value as IdentifierReference)
|
||||
"+=" -> return false // TODO optimized float += variable
|
||||
"-=" -> return false // TODO optimized float -= variable
|
||||
else -> TODO("$assign")
|
||||
else -> TODO("float non-const value aug.assign $assign")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -763,7 +837,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
sta $targetName+4
|
||||
""")
|
||||
}
|
||||
else -> TODO("$assign")
|
||||
else -> TODO("float $assign")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@ -803,13 +877,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda #$hexValue")
|
||||
"+=" -> asmgen.out(" clc | adc #$hexValue")
|
||||
"-=" -> asmgen.out(" sec | sbc #$hexValue")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("A /= const $hexValue")
|
||||
"*=" -> TODO("A *= const $hexValue")
|
||||
"&=" -> asmgen.out(" and #$hexValue")
|
||||
"|=" -> asmgen.out(" ora #$hexValue")
|
||||
"^=" -> asmgen.out(" eor #$hexValue")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("A %= const $hexValue")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -820,13 +893,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" ldx #$hexValue")
|
||||
"+=" -> asmgen.out(" txa | clc | adc #$hexValue | tax")
|
||||
"-=" -> asmgen.out(" txa | sec | sbc #$hexValue | tax")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("X /= const $hexValue")
|
||||
"*=" -> TODO("X *= const $hexValue")
|
||||
"&=" -> asmgen.out(" txa | and #$hexValue | tax")
|
||||
"|=" -> asmgen.out(" txa | ora #$hexValue | tax")
|
||||
"^=" -> asmgen.out(" txa | eor #$hexValue | tax")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("X %= const $hexValue")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -837,13 +909,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" ldy #$hexValue")
|
||||
"+=" -> asmgen.out(" tya | clc | adc #$hexValue | tay")
|
||||
"-=" -> asmgen.out(" tya | sec | sbc #$hexValue | tay")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("Y /= const $hexValue")
|
||||
"*=" -> TODO("Y *= const $hexValue")
|
||||
"&=" -> asmgen.out(" tya | and #$hexValue | tay")
|
||||
"|=" -> asmgen.out(" tya | ora #$hexValue | tay")
|
||||
"^=" -> asmgen.out(" tya | eor #$hexValue | tay")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("Y %= const $hexValue")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -863,13 +934,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda $sourceName")
|
||||
"+=" -> asmgen.out(" clc | adc $sourceName")
|
||||
"-=" -> asmgen.out(" sec | sbc $sourceName")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("A /= variable")
|
||||
"*=" -> TODO("A *= variable")
|
||||
"&=" -> asmgen.out(" and $sourceName")
|
||||
"|=" -> asmgen.out(" ora $sourceName")
|
||||
"^=" -> asmgen.out(" eor $sourceName")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("A %= variable")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -880,13 +950,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" ldx $sourceName")
|
||||
"+=" -> asmgen.out(" txa | clc | adc $sourceName | tax")
|
||||
"-=" -> asmgen.out(" txa | sec | sbc $sourceName | tax")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("X /= variable")
|
||||
"*=" -> TODO("X *= variable")
|
||||
"&=" -> asmgen.out(" txa | and $sourceName | tax")
|
||||
"|=" -> asmgen.out(" txa | ora $sourceName | tax")
|
||||
"^=" -> asmgen.out(" txa | eor $sourceName | tax")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("X %= variable")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -897,13 +966,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" ldy $sourceName")
|
||||
"+=" -> asmgen.out(" tya | clc | adc $sourceName | tay")
|
||||
"-=" -> asmgen.out(" tya | sec | sbc $sourceName | tay")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("Y /= variable")
|
||||
"*=" -> TODO("Y *= variable")
|
||||
"&=" -> asmgen.out(" tya | and $sourceName | tay")
|
||||
"|=" -> asmgen.out(" tya | ora $sourceName | tay")
|
||||
"^=" -> asmgen.out(" tya | eor $sourceName | tay")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("Y %= variable")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -918,8 +986,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
when ((assign.value as RegisterExpr).register) {
|
||||
Register.A -> {
|
||||
when (assign.target.register!!) {
|
||||
Register.A -> {
|
||||
}
|
||||
Register.A -> {}
|
||||
Register.X -> asmgen.out(" tax")
|
||||
Register.Y -> asmgen.out(" tay")
|
||||
}
|
||||
@ -927,8 +994,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
Register.X -> {
|
||||
when (assign.target.register!!) {
|
||||
Register.A -> asmgen.out(" txa")
|
||||
Register.X -> {
|
||||
}
|
||||
Register.X -> {}
|
||||
Register.Y -> asmgen.out(" txa | tay")
|
||||
}
|
||||
}
|
||||
@ -936,8 +1002,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
when (assign.target.register!!) {
|
||||
Register.A -> asmgen.out(" tya")
|
||||
Register.X -> asmgen.out(" tya | tax")
|
||||
Register.Y -> {
|
||||
}
|
||||
Register.Y -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -992,9 +1057,8 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
}
|
||||
}
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("register /= register")
|
||||
"*=" -> TODO("register *= register")
|
||||
"&=" -> {
|
||||
when ((assign.value as RegisterExpr).register) {
|
||||
Register.A -> {
|
||||
@ -1020,9 +1084,9 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
}
|
||||
}
|
||||
"|=" -> TODO()
|
||||
"^=" -> TODO()
|
||||
"%=" -> TODO("%=")
|
||||
"|=" -> TODO("register |= register")
|
||||
"^=" -> TODO("register ^= register")
|
||||
"%=" -> TODO("register %= register")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -1039,13 +1103,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" lda $hexAddr")
|
||||
"+=" -> asmgen.out(" clc | adc $hexAddr")
|
||||
"-=" -> asmgen.out(" sec | sbc $hexAddr")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("A /= memory $hexAddr")
|
||||
"*=" -> TODO("A *= memory $hexAddr")
|
||||
"&=" -> asmgen.out(" and $hexAddr")
|
||||
"|=" -> asmgen.out(" ora $hexAddr")
|
||||
"^=" -> asmgen.out(" eor $hexAddr")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("A %= memory $hexAddr")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -1056,13 +1119,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" ldx $hexAddr")
|
||||
"+=" -> asmgen.out(" txa | clc | adc $hexAddr | tax")
|
||||
"-=" -> asmgen.out(" txa | sec | sbc $hexAddr | tax")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("X /= memory $hexAddr")
|
||||
"*=" -> TODO("X *= memory $hexAddr")
|
||||
"&=" -> asmgen.out(" txa | and $hexAddr | tax")
|
||||
"|=" -> asmgen.out(" txa | ora $hexAddr | tax")
|
||||
"^=" -> asmgen.out(" txa | eor $hexAddr | tax")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("X %= memory $hexAddr")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -1073,13 +1135,12 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
"setvalue" -> asmgen.out(" ldy $hexAddr")
|
||||
"+=" -> asmgen.out(" tya | clc | adc $hexAddr | tay")
|
||||
"-=" -> asmgen.out(" tya | sec | sbc $hexAddr | tay")
|
||||
"/=" -> TODO("/=")
|
||||
"*=" -> TODO("*=")
|
||||
"**=" -> TODO("**=")
|
||||
"/=" -> TODO("Y /= memory $hexAddr")
|
||||
"*=" -> TODO("Y *= memory $hexAddr")
|
||||
"&=" -> asmgen.out(" tya | and $hexAddr | tay")
|
||||
"|=" -> asmgen.out(" tya | ora $hexAddr | tay")
|
||||
"^=" -> asmgen.out(" tya | eor $hexAddr | tay")
|
||||
"%=" -> TODO("%=")
|
||||
"%=" -> TODO("Y %= memory $hexAddr")
|
||||
"<<=" -> throw AssemblyError("<<= should have been replaced by lsl()")
|
||||
">>=" -> throw AssemblyError("<<= should have been replaced by lsr()")
|
||||
else -> throw AssemblyError("invalid aug_op ${assign.aug_op}")
|
||||
@ -1089,9 +1150,6 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
return true
|
||||
}
|
||||
}
|
||||
is AddressOf -> {
|
||||
TODO("$assign")
|
||||
}
|
||||
is ArrayIndexedExpression -> {
|
||||
if (assign.aug_op == "setvalue") {
|
||||
val arrayExpr = assign.value as ArrayIndexedExpression
|
||||
@ -1117,6 +1175,7 @@ internal class AssignmentAsmGen(private val program: Program, private val errors
|
||||
}
|
||||
return true
|
||||
}
|
||||
is AddressOf -> throw AssemblyError("can't load a memory address into a register")
|
||||
else -> {
|
||||
fallbackAssignment(assign)
|
||||
return true
|
||||
|
@ -2,12 +2,8 @@ package prog8.compiler.target.c64.codegen
|
||||
|
||||
import prog8.ast.IFunctionCall
|
||||
import prog8.ast.Program
|
||||
import prog8.ast.base.ByteDatatypes
|
||||
import prog8.ast.base.DataType
|
||||
import prog8.ast.base.Register
|
||||
import prog8.ast.base.WordDatatypes
|
||||
import prog8.ast.base.*
|
||||
import prog8.ast.expressions.*
|
||||
import prog8.ast.statements.AssignTarget
|
||||
import prog8.ast.statements.FunctionCallStatement
|
||||
import prog8.compiler.AssemblyError
|
||||
import prog8.compiler.target.c64.C64MachineDefinition.C64Zeropage
|
||||
@ -581,32 +577,32 @@ internal class BuiltinFunctionsAsmGen(private val program: Program, private val
|
||||
ldy $firstName
|
||||
lda $secondName
|
||||
sta $firstName
|
||||
tya
|
||||
sta $secondName
|
||||
sty $secondName
|
||||
ldy $firstName+1
|
||||
lda $secondName+1
|
||||
sta $firstName+1
|
||||
tya
|
||||
sta $secondName+1
|
||||
sty $secondName+1
|
||||
""")
|
||||
return
|
||||
}
|
||||
if(dt.istype(DataType.FLOAT)) {
|
||||
TODO("optimized case for swapping 2 float vars-- asm subroutine")
|
||||
asmgen.out("""
|
||||
lda #<$firstName
|
||||
sta ${C64Zeropage.SCRATCH_W1}
|
||||
lda #>$firstName
|
||||
sta ${C64Zeropage.SCRATCH_W1+1}
|
||||
lda #<$secondName
|
||||
sta ${C64Zeropage.SCRATCH_W2}
|
||||
lda #>$secondName
|
||||
sta ${C64Zeropage.SCRATCH_W2+1}
|
||||
jsr c64flt.swap_floats
|
||||
""")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// TODO more optimized cases? for instance swapping elements of array vars?
|
||||
|
||||
// suboptimal code via the evaluation stack...
|
||||
asmgen.translateExpression(first)
|
||||
asmgen.translateExpression(second)
|
||||
// pop in reverse order
|
||||
val firstTarget = AssignTarget.fromExpr(first)
|
||||
val secondTarget = AssignTarget.fromExpr(second)
|
||||
asmgen.assignFromEvalResult(firstTarget)
|
||||
asmgen.assignFromEvalResult(secondTarget)
|
||||
// other types of swap() calls should have been replaced by a different statement sequence involving a temp variable
|
||||
throw AssemblyError("no asm generation for swap funccall $fcall")
|
||||
}
|
||||
|
||||
private fun funcAbs(fcall: IFunctionCall, func: FSignature) {
|
||||
|
@ -240,16 +240,26 @@ internal class ExpressionsAsmGen(private val program: Program, private val asmge
|
||||
}
|
||||
}
|
||||
DataType.UWORD -> {
|
||||
if(amount<=2)
|
||||
repeat(amount) { asmgen.out(" lsr $ESTACK_HI_PLUS1_HEX,x | ror $ESTACK_LO_PLUS1_HEX,x") }
|
||||
var left = amount
|
||||
while(left>=7) {
|
||||
asmgen.out(" jsr math.shift_right_uw_7")
|
||||
left -= 7
|
||||
}
|
||||
if (left in 0..2)
|
||||
repeat(left) { asmgen.out(" lsr $ESTACK_HI_PLUS1_HEX,x | ror $ESTACK_LO_PLUS1_HEX,x") }
|
||||
else
|
||||
asmgen.out(" jsr math.shift_right_uw_$amount") // 3-7 (8+ is done via other optimizations)
|
||||
asmgen.out(" jsr math.shift_right_uw_$left")
|
||||
}
|
||||
DataType.WORD -> {
|
||||
if(amount<=2)
|
||||
repeat(amount) { asmgen.out(" lda $ESTACK_HI_PLUS1_HEX,x | asl a | ror $ESTACK_HI_PLUS1_HEX,x | ror $ESTACK_LO_PLUS1_HEX,x") }
|
||||
var left = amount
|
||||
while(left>=7) {
|
||||
asmgen.out(" jsr math.shift_right_w_7")
|
||||
left -= 7
|
||||
}
|
||||
if (left in 0..2)
|
||||
repeat(left) { asmgen.out(" lda $ESTACK_HI_PLUS1_HEX,x | asl a | ror $ESTACK_HI_PLUS1_HEX,x | ror $ESTACK_LO_PLUS1_HEX,x") }
|
||||
else
|
||||
asmgen.out(" jsr math.shift_right_w_$amount") // 3-7 (8+ is done via other optimizations)
|
||||
asmgen.out(" jsr math.shift_right_w_$left")
|
||||
}
|
||||
else -> throw AssemblyError("weird type")
|
||||
}
|
||||
@ -269,11 +279,15 @@ internal class ExpressionsAsmGen(private val program: Program, private val asmge
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(amount<=2) {
|
||||
repeat(amount) { asmgen.out(" asl $ESTACK_LO_PLUS1_HEX,x | rol $ESTACK_HI_PLUS1_HEX,x") }
|
||||
} else {
|
||||
asmgen.out(" jsr math.shift_left_w_$amount") // 3-7 (8+ is done via other optimizations)
|
||||
var left=amount
|
||||
while(left>=7) {
|
||||
asmgen.out(" jsr math.shift_left_w_7")
|
||||
left -= 7
|
||||
}
|
||||
if (left in 0..2)
|
||||
repeat(left) { asmgen.out(" asl $ESTACK_LO_PLUS1_HEX,x | rol $ESTACK_HI_PLUS1_HEX,x") }
|
||||
else
|
||||
asmgen.out(" jsr math.shift_left_w_$left")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
@ -16,7 +16,7 @@ import prog8.compiler.toHex
|
||||
import kotlin.math.absoluteValue
|
||||
|
||||
// todo choose more efficient comparisons to avoid needless lda's
|
||||
// todo optimize common case step == 2 / -2
|
||||
// todo optimize common case when step == 2 or -2
|
||||
|
||||
|
||||
internal class ForLoopsAsmGen(private val program: Program, private val asmgen: AsmGen) {
|
||||
@ -339,7 +339,7 @@ $continueLabel inc $loopLabel+1
|
||||
$endLabel""")
|
||||
}
|
||||
DataType.ARRAY_UB, DataType.ARRAY_B -> {
|
||||
// TODO: optimize loop code when the length of the array is < 256, don't need a separate counter in such cases
|
||||
// TODO: optimize loop code when the length of the array is < 256, don't need a separate counter var in such cases
|
||||
val length = decl.arraysize!!.size()!!
|
||||
if(stmt.loopRegister!=null && stmt.loopRegister!= Register.A)
|
||||
throw AssemblyError("can only use A")
|
||||
@ -366,7 +366,7 @@ $counterLabel .byte 0
|
||||
$endLabel""")
|
||||
}
|
||||
DataType.ARRAY_W, DataType.ARRAY_UW -> {
|
||||
// TODO: optimize loop code when the length of the array is < 256, don't need a separate counter in such cases
|
||||
// TODO: optimize loop code when the length of the array is < 256, don't need a separate counter var in such cases
|
||||
val length = decl.arraysize!!.size()!! * 2
|
||||
if(stmt.loopRegister!=null)
|
||||
throw AssemblyError("can't use register to loop over words")
|
||||
@ -410,7 +410,7 @@ $endLabel""")
|
||||
}
|
||||
|
||||
private fun translateForOverConstRange(stmt: ForLoop, iterableDt: DataType, range: IntProgression) {
|
||||
// TODO: optimize loop code when the range is < 256 iterations, don't need a separate counter in such cases
|
||||
// TODO: optimize loop code when the range is < 256 iterations, don't need a separate counter var in such cases
|
||||
if (range.isEmpty())
|
||||
throw AssemblyError("empty range")
|
||||
val loopLabel = asmgen.makeLabel("for_loop")
|
||||
|
@ -24,10 +24,10 @@ private val asmRefRx = Regex("""[\-+a-zA-Z0-9_ \t]+(...)[ \t]+(\S+).*""", RegexO
|
||||
|
||||
class CallGraph(private val program: Program) : IAstVisitor {
|
||||
|
||||
val modulesImporting = mutableMapOf<Module, List<Module>>().withDefault { mutableListOf() }
|
||||
val modulesImportedBy = mutableMapOf<Module, List<Module>>().withDefault { mutableListOf() }
|
||||
val subroutinesCalling = mutableMapOf<INameScope, List<Subroutine>>().withDefault { mutableListOf() }
|
||||
val subroutinesCalledBy = mutableMapOf<Subroutine, List<Node>>().withDefault { mutableListOf() }
|
||||
val imports = mutableMapOf<Module, List<Module>>().withDefault { mutableListOf() }
|
||||
val importedBy = mutableMapOf<Module, List<Module>>().withDefault { mutableListOf() }
|
||||
val calls = mutableMapOf<INameScope, List<Subroutine>>().withDefault { mutableListOf() }
|
||||
val calledBy = mutableMapOf<Subroutine, List<Node>>().withDefault { mutableListOf() }
|
||||
|
||||
// TODO add dataflow graph: what statements use what variables - can be used to eliminate unused vars
|
||||
val usedSymbols = mutableSetOf<Statement>()
|
||||
@ -55,17 +55,8 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
it.importedBy.clear()
|
||||
it.imports.clear()
|
||||
|
||||
it.importedBy.addAll(modulesImportedBy.getValue(it))
|
||||
it.imports.addAll(modulesImporting.getValue(it))
|
||||
|
||||
forAllSubroutines(it) { sub ->
|
||||
sub.calledBy.clear()
|
||||
sub.calls.clear()
|
||||
|
||||
sub.calledBy.addAll(subroutinesCalledBy.getValue(sub))
|
||||
sub.calls.addAll(subroutinesCalling.getValue(sub))
|
||||
}
|
||||
|
||||
it.importedBy.addAll(importedBy.getValue(it))
|
||||
it.imports.addAll(imports.getValue(it))
|
||||
}
|
||||
|
||||
val rootmodule = program.modules.first()
|
||||
@ -85,8 +76,8 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
val thisModule = directive.definingModule()
|
||||
if (directive.directive == "%import") {
|
||||
val importedModule: Module = program.modules.single { it.name == directive.args[0].name }
|
||||
modulesImporting[thisModule] = modulesImporting.getValue(thisModule).plus(importedModule)
|
||||
modulesImportedBy[importedModule] = modulesImportedBy.getValue(importedModule).plus(thisModule)
|
||||
imports[thisModule] = imports.getValue(thisModule).plus(importedModule)
|
||||
importedBy[importedModule] = importedBy.getValue(importedModule).plus(thisModule)
|
||||
} else if (directive.directive == "%asminclude") {
|
||||
val asm = loadAsmIncludeFile(directive.args[0].str!!, thisModule.source)
|
||||
val scope = directive.definingScope()
|
||||
@ -141,8 +132,8 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
val otherSub = functionCall.target.targetSubroutine(program.namespace)
|
||||
if (otherSub != null) {
|
||||
functionCall.definingSubroutine()?.let { thisSub ->
|
||||
subroutinesCalling[thisSub] = subroutinesCalling.getValue(thisSub).plus(otherSub)
|
||||
subroutinesCalledBy[otherSub] = subroutinesCalledBy.getValue(otherSub).plus(functionCall)
|
||||
calls[thisSub] = calls.getValue(thisSub).plus(otherSub)
|
||||
calledBy[otherSub] = calledBy.getValue(otherSub).plus(functionCall)
|
||||
}
|
||||
}
|
||||
super.visit(functionCall)
|
||||
@ -152,8 +143,8 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
val otherSub = functionCallStatement.target.targetSubroutine(program.namespace)
|
||||
if (otherSub != null) {
|
||||
functionCallStatement.definingSubroutine()?.let { thisSub ->
|
||||
subroutinesCalling[thisSub] = subroutinesCalling.getValue(thisSub).plus(otherSub)
|
||||
subroutinesCalledBy[otherSub] = subroutinesCalledBy.getValue(otherSub).plus(functionCallStatement)
|
||||
calls[thisSub] = calls.getValue(thisSub).plus(otherSub)
|
||||
calledBy[otherSub] = calledBy.getValue(otherSub).plus(functionCallStatement)
|
||||
}
|
||||
}
|
||||
super.visit(functionCallStatement)
|
||||
@ -163,8 +154,8 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
val otherSub = jump.identifier?.targetSubroutine(program.namespace)
|
||||
if (otherSub != null) {
|
||||
jump.definingSubroutine()?.let { thisSub ->
|
||||
subroutinesCalling[thisSub] = subroutinesCalling.getValue(thisSub).plus(otherSub)
|
||||
subroutinesCalledBy[otherSub] = subroutinesCalledBy.getValue(otherSub).plus(jump)
|
||||
calls[thisSub] = calls.getValue(thisSub).plus(otherSub)
|
||||
calledBy[otherSub] = calledBy.getValue(otherSub).plus(jump)
|
||||
}
|
||||
}
|
||||
super.visit(jump)
|
||||
@ -190,14 +181,14 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
if (jumptarget != null && (jumptarget[0].isLetter() || jumptarget[0] == '_')) {
|
||||
val node = program.namespace.lookup(jumptarget.split('.'), context)
|
||||
if (node is Subroutine) {
|
||||
subroutinesCalling[scope] = subroutinesCalling.getValue(scope).plus(node)
|
||||
subroutinesCalledBy[node] = subroutinesCalledBy.getValue(node).plus(context)
|
||||
calls[scope] = calls.getValue(scope).plus(node)
|
||||
calledBy[node] = calledBy.getValue(node).plus(context)
|
||||
} else if (jumptarget.contains('.')) {
|
||||
// maybe only the first part already refers to a subroutine
|
||||
val node2 = program.namespace.lookup(listOf(jumptarget.substringBefore('.')), context)
|
||||
if (node2 is Subroutine) {
|
||||
subroutinesCalling[scope] = subroutinesCalling.getValue(scope).plus(node2)
|
||||
subroutinesCalledBy[node2] = subroutinesCalledBy.getValue(node2).plus(context)
|
||||
calls[scope] = calls.getValue(scope).plus(node2)
|
||||
calledBy[node2] = calledBy.getValue(node2).plus(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -209,8 +200,8 @@ class CallGraph(private val program: Program) : IAstVisitor {
|
||||
if (target.contains('.')) {
|
||||
val node = program.namespace.lookup(listOf(target.substringBefore('.')), context)
|
||||
if (node is Subroutine) {
|
||||
subroutinesCalling[scope] = subroutinesCalling.getValue(scope).plus(node)
|
||||
subroutinesCalledBy[node] = subroutinesCalledBy.getValue(node).plus(context)
|
||||
calls[scope] = calls.getValue(scope).plus(node)
|
||||
calledBy[node] = calledBy.getValue(node).plus(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,46 +0,0 @@
|
||||
package prog8.optimizer
|
||||
|
||||
import prog8.ast.INameScope
|
||||
import prog8.ast.Node
|
||||
import prog8.ast.Program
|
||||
import prog8.ast.processing.IAstVisitor
|
||||
import prog8.ast.statements.AnonymousScope
|
||||
import prog8.ast.statements.NopStatement
|
||||
import prog8.ast.statements.Statement
|
||||
|
||||
internal class FlattenAnonymousScopesAndNopRemover: IAstVisitor {
|
||||
private var scopesToFlatten = mutableListOf<INameScope>()
|
||||
private val nopStatements = mutableListOf<NopStatement>()
|
||||
|
||||
override fun visit(program: Program) {
|
||||
super.visit(program)
|
||||
for(scope in scopesToFlatten.reversed()) {
|
||||
val namescope = scope.parent as INameScope
|
||||
val idx = namescope.statements.indexOf(scope as Statement)
|
||||
if(idx>=0) {
|
||||
val nop = NopStatement.insteadOf(namescope.statements[idx])
|
||||
nop.parent = namescope as Node
|
||||
namescope.statements[idx] = nop
|
||||
namescope.statements.addAll(idx, scope.statements)
|
||||
scope.statements.forEach { it.parent = namescope }
|
||||
visit(nop)
|
||||
}
|
||||
}
|
||||
|
||||
this.nopStatements.forEach {
|
||||
it.definingScope().remove(it)
|
||||
}
|
||||
}
|
||||
|
||||
override fun visit(scope: AnonymousScope) {
|
||||
if(scope.parent is INameScope) {
|
||||
scopesToFlatten.add(scope) // get rid of the anonymous scope
|
||||
}
|
||||
|
||||
return super.visit(scope)
|
||||
}
|
||||
|
||||
override fun visit(nopStatement: NopStatement) {
|
||||
nopStatements.add(nopStatement)
|
||||
}
|
||||
}
|
@ -16,7 +16,6 @@ import kotlin.math.floor
|
||||
|
||||
/*
|
||||
TODO: remove unreachable code after return and exit()
|
||||
TODO: proper inlining of tiny subroutines (at first, restrict to subs without parameters and variables in them, and build it up from there: correctly renaming/relocating all variables in them and refs to those as well)
|
||||
*/
|
||||
|
||||
|
||||
|
@ -17,7 +17,7 @@ internal class UnusedCodeRemover: AstWalker() {
|
||||
val entrypoint = program.entrypoint()
|
||||
program.modules.forEach {
|
||||
callgraph.forAllSubroutines(it) { sub ->
|
||||
if (sub !== entrypoint && !sub.keepAlways && (sub.calledBy.isEmpty() || (sub.containsNoCodeNorVars() && !sub.isAsmSubroutine)))
|
||||
if (sub !== entrypoint && !sub.keepAlways && (callgraph.calledBy[sub].isNullOrEmpty() || (sub.containsNoCodeNorVars() && !sub.isAsmSubroutine)))
|
||||
removals.add(IAstModification.Remove(sub, sub.definingScope() as Node))
|
||||
}
|
||||
}
|
||||
|
@ -2,10 +2,13 @@
|
||||
TODO
|
||||
====
|
||||
|
||||
- BUG FIX: fix register argument clobbering when calling asmsubs. (see fixme_argclobber.p8)
|
||||
|
||||
|
||||
- finalize (most) of the still missing "new" assignment asm code generation
|
||||
- aliases for imported symbols for example perhaps '%alias print = c64scr.print'
|
||||
- option to load library files from a directory instead of the embedded ones (easier library development/debugging)
|
||||
- investigate support for 8bitguy's Commander X16 platform https://murray2.com/forums/commander-x16.9/ and https://github.com/commanderx16/x16-docs
|
||||
- investigate support for 8bitguy's Commander X16 platform https://www.commanderx16.com and https://github.com/commanderx16/x16-docs
|
||||
- see if we can group some errors together for instance the (now single) errors about unidentified symbols
|
||||
|
||||
|
||||
|
@ -1,8 +1,7 @@
|
||||
%import c64utils
|
||||
;%import c64flt
|
||||
;%option enable_floats
|
||||
%zeropage dontuse
|
||||
|
||||
|
||||
main {
|
||||
|
||||
sub start() {
|
||||
|
Binary file not shown.
BIN
examples/compiled/mandelbrot-gfx.prg
Normal file
BIN
examples/compiled/mandelbrot-gfx.prg
Normal file
Binary file not shown.
Binary file not shown.
@ -1,6 +1,7 @@
|
||||
%import c64lib
|
||||
%import c64utils
|
||||
|
||||
|
||||
spritedata $2000 {
|
||||
; this memory block contains the sprite data
|
||||
; it must start on an address aligned to 64 bytes.
|
||||
|
47
examples/fixme_argclobber.p8
Normal file
47
examples/fixme_argclobber.p8
Normal file
@ -0,0 +1,47 @@
|
||||
%import c64lib
|
||||
%import c64utils
|
||||
%import c64flt
|
||||
%zeropage basicsafe
|
||||
%option enable_floats
|
||||
|
||||
|
||||
; TODO: fix register argument clobbering when calling asmsubs.
|
||||
; for instance if the first arg goes into Y, and the second in A,
|
||||
; but when calculating the second argument clobbers Y, the first argument gets destroyed.
|
||||
|
||||
main {
|
||||
|
||||
sub start() {
|
||||
function(20, calculate())
|
||||
asmfunction(20, calculate())
|
||||
|
||||
c64.CHROUT('\n')
|
||||
|
||||
if @($0400)==@($0402) and @($0401) == @($0403) {
|
||||
c64scr.print("ok: results are same\n")
|
||||
} else {
|
||||
c64scr.print("error: result differ; arg got clobbered\n")
|
||||
}
|
||||
}
|
||||
|
||||
sub function(ubyte a1, ubyte a2) {
|
||||
; non-asm function passes via stack, this is ok
|
||||
@($0400) = a1
|
||||
@($0401) = a2
|
||||
}
|
||||
|
||||
asmsub asmfunction(ubyte a1 @ Y, ubyte a2 @ A) {
|
||||
; asm-function passes via registers, risk of clobbering
|
||||
%asm {{
|
||||
sty $0402
|
||||
sta $0403
|
||||
}}
|
||||
}
|
||||
|
||||
sub calculate() -> ubyte {
|
||||
Y = 99
|
||||
return Y
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,9 @@
|
||||
%import c64lib
|
||||
%import c64graphics
|
||||
|
||||
; TODO fix compiler errors when compiling without optimizations
|
||||
|
||||
|
||||
main {
|
||||
|
||||
sub start() {
|
||||
|
54
examples/mandelbrot-gfx.p8
Normal file
54
examples/mandelbrot-gfx.p8
Normal file
@ -0,0 +1,54 @@
|
||||
%import c64lib
|
||||
%import c64flt
|
||||
%import c64graphics
|
||||
%zeropage floatsafe
|
||||
|
||||
; Draw a mandelbrot in graphics mode (the image will be 256 x 200 pixels).
|
||||
; NOTE: this will take an eternity to draw on a real c64.
|
||||
; even in Vice in warp mode (700% speed on my machine) it's slow, but you can see progress
|
||||
|
||||
; TODO fix compiler errors when compiling without optimizations
|
||||
|
||||
|
||||
main {
|
||||
const ubyte width = 255
|
||||
const ubyte height = 200
|
||||
const ubyte max_iter = 16
|
||||
|
||||
sub start() {
|
||||
graphics.enable_bitmap_mode()
|
||||
|
||||
ubyte pixelx
|
||||
ubyte pixely
|
||||
|
||||
for pixely in 0 to height-1 {
|
||||
float yy = (pixely as float)/0.4/height - 1.0
|
||||
|
||||
for pixelx in 0 to width-1 {
|
||||
float xx = (pixelx as float)/0.3/width - 2.2
|
||||
|
||||
float xsquared = 0.0
|
||||
float ysquared = 0.0
|
||||
float x = 0.0
|
||||
float y = 0.0
|
||||
ubyte iter = 0
|
||||
|
||||
while iter<max_iter and xsquared+ysquared<4.0 {
|
||||
y = x*y*2.0 + yy
|
||||
x = xsquared - ysquared + xx
|
||||
xsquared = x*x
|
||||
ysquared = y*y
|
||||
iter++
|
||||
}
|
||||
|
||||
if iter & 1 {
|
||||
graphics.plotx = pixelx
|
||||
graphics.plot(pixely)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
forever {
|
||||
}
|
||||
}
|
||||
}
|
@ -30,7 +30,7 @@ main {
|
||||
float y = 0.0
|
||||
ubyte iter = 0
|
||||
|
||||
while (iter<max_iter and xsquared+ysquared<4.0) {
|
||||
while iter<max_iter and xsquared+ysquared<4.0 {
|
||||
y = x*y*2.0 + yy
|
||||
x = xsquared - ysquared + xx
|
||||
xsquared = x*x
|
||||
|
@ -1,6 +1,9 @@
|
||||
%import c64utils
|
||||
%zeropage basicsafe
|
||||
|
||||
; TODO fix compiler errors when compiling ( /= )
|
||||
|
||||
|
||||
main {
|
||||
|
||||
struct Color {
|
||||
|
@ -12,10 +12,8 @@ main {
|
||||
ubyte color
|
||||
|
||||
forever {
|
||||
float x = sin(t)
|
||||
float y = cos(t*1.1356)
|
||||
ubyte xx=(x * width/2.2) + width/2.0 as ubyte
|
||||
ubyte yy=(y * height/2.2) + height/2.0 as ubyte
|
||||
ubyte xx=(sin(t) * width/2.2) + width/2.0 as ubyte
|
||||
ubyte yy=(cos(t*1.1356) * height/2.2) + height/2.0 as ubyte
|
||||
c64scr.setcc(xx, yy, 81, color)
|
||||
t += 0.08
|
||||
color++
|
||||
|
@ -7,6 +7,11 @@
|
||||
; staged speed increase
|
||||
; some simple sound effects
|
||||
|
||||
|
||||
|
||||
; TODO fix noCollision() at bottom when compiled without optimizations (codegen issue).
|
||||
|
||||
|
||||
main {
|
||||
|
||||
const ubyte boardOffsetX = 14
|
||||
@ -107,6 +112,7 @@ waitkey:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if dropypos>ypos {
|
||||
ypos = dropypos
|
||||
sound.blockdrop()
|
||||
@ -543,6 +549,7 @@ blocklogic {
|
||||
sub noCollision(ubyte xpos, ubyte ypos) -> ubyte {
|
||||
ubyte i
|
||||
for i in 15 downto 0 {
|
||||
; TODO FIX THIS when compiling without optimizations (codegen problem: clobbering register arguments, see fixme_argclobber):
|
||||
if currentBlock[i] and c64scr.getchr(xpos + (i&3), ypos+i/4)!=32
|
||||
return false
|
||||
}
|
||||
|
@ -2,15 +2,46 @@
|
||||
%import c64utils
|
||||
%import c64flt
|
||||
%zeropage basicsafe
|
||||
%option enable_floats
|
||||
|
||||
|
||||
; TODO: fix register argument clobbering when calling asmsubs.
|
||||
; for instance if the first arg goes into Y, and the second in A,
|
||||
; but when calculating the second argument clobbers Y, the first argument gets destroyed.
|
||||
|
||||
main {
|
||||
|
||||
sub start() {
|
||||
A=42
|
||||
function(20, calculate())
|
||||
asmfunction(20, calculate())
|
||||
|
||||
c64.CHROUT('\n')
|
||||
|
||||
if @($0400)==@($0402) and @($0401) == @($0403) {
|
||||
c64scr.print("ok: results are same\n")
|
||||
} else {
|
||||
c64scr.print("error: result differ; arg got clobbered\n")
|
||||
}
|
||||
}
|
||||
|
||||
sub function(ubyte a1, ubyte a2) {
|
||||
; non-asm function passes via stack, this is ok
|
||||
@($0400) = a1
|
||||
@($0401) = a2
|
||||
}
|
||||
|
||||
asmsub asmfunction(ubyte a1 @ Y, ubyte a2 @ A) {
|
||||
; asm-function passes via registers, risk of clobbering
|
||||
%asm {{
|
||||
sty $0402
|
||||
sta $0403
|
||||
}}
|
||||
}
|
||||
|
||||
sub calculate() -> ubyte {
|
||||
Y = 99
|
||||
return Y
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -3,6 +3,7 @@
|
||||
%import c64graphics
|
||||
%option enable_floats
|
||||
|
||||
; TODO fix compiler errors when compiling without optimizations
|
||||
|
||||
main {
|
||||
|
||||
|
Reference in New Issue
Block a user