[WASM] NFC. Fold instructions from the wasm expression builder

This commit is contained in:
Igor Laevsky
2021-09-08 20:18:09 +03:00
committed by teamcityserver
parent 718965227e
commit 1db45faba2
3 changed files with 24 additions and 10 deletions
@@ -30,3 +30,18 @@ fun WasmModule.calculateIds() {
tables.calculateIds(startIndex = importedTables.size)
tags.calculateIds(startIndex = importedTags.size)
}
// This is used to perform simple peephole-like optimizations from the WasmExpressionBuilder.
// Takes two adjacent instructions and returns an array with 0, 1 or 2 instructions to replace the original ones.
// Returns null if no action is required.
fun foldWasmInstructions(prev: WasmInstr?, next: WasmInstr): List<WasmInstr>? {
if (prev == null)
return null
// Unreachable is not needed after another unreachable or return
if (next.operator == WasmOp.UNREACHABLE && prev.operator in listOf(WasmOp.UNREACHABLE, WasmOp.RETURN))
return listOf(prev)
return null
}
@@ -9,8 +9,6 @@ abstract class WasmExpressionBuilder {
abstract fun buildInstr(op: WasmOp, vararg immediates: WasmImmediate)
abstract var numberOfNestedBlocks: Int
abstract val lastInstr: WasmOp?
fun buildConstI32(value: Int) {
buildInstr(WasmOp.I32_CONST, WasmImmediate.ConstI32(value))
}
@@ -32,10 +30,6 @@ abstract class WasmExpressionBuilder {
}
fun buildUnreachable() {
// Unreachable is not needed
if (lastInstr == WasmOp.UNREACHABLE || lastInstr == WasmOp.RETURN)
return
buildInstr(WasmOp.UNREACHABLE)
}
@@ -10,7 +10,15 @@ class WasmIrExpressionBuilder(
) : WasmExpressionBuilder() {
override fun buildInstr(op: WasmOp, vararg immediates: WasmImmediate) {
expression.add(WasmInstr(op, immediates.toList()))
val nextInstr = WasmInstr(op, immediates.toList())
val foldedInstrs = foldWasmInstructions(expression.lastOrNull(), nextInstr)
if (foldedInstrs == null) {
expression += nextInstr
} else {
expression.removeLastOrNull()
expression += foldedInstrs
}
}
@@ -19,9 +27,6 @@ class WasmIrExpressionBuilder(
assert(value >= 0) { "end without matching block" }
field = value
}
override val lastInstr: WasmOp?
get() = expression.lastOrNull()?.operator
}
inline fun buildWasmExpression(body: WasmExpressionBuilder.() -> Unit): MutableList<WasmInstr> {