-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathBeyondRelooper.kt
More file actions
307 lines (279 loc) · 8.12 KB
/
Copy pathBeyondRelooper.kt
File metadata and controls
307 lines (279 loc) · 8.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import com.squareup.moshi.*
import java.util.LinkedList
import java.util.TreeSet
import java.util.TreeMap
fun log(s: String) {
val logEnabled = false
if (logEnabled) {
System.err.println(s)
}
}
// A map from block id to it's reverse post order.
typealias Rpo = TreeMap<Int, Int>
fun reversePostOrder(
cfg: Cfg,
): Rpo {
val visited = TreeSet<Int>()
val queue = LinkedList<Int>()
val res = LinkedList<Int>()
queue.add(0)
while (queue.isNotEmpty()) {
val h = queue.peekFirst()
visited.add(h)
var flipped = false
cfg[h]!!.reversed().forEach { b ->
if (visited.contains(b).not()) {
flipped = true
queue.add(0, b)
}
}
if (flipped.not()) {
res.add(h)
queue.pollFirst()
}
}
val map = TreeMap<Int, Int>()
res.reversed().forEachIndexed { i, o ->
map[o] = i
}
return map
}
fun isMergeNode(
bid: Int,
rpo: Rpo,
preds: Predecessors,
): Boolean {
val count = preds[bid]!!.fold(0) { acc, pred ->
if (rpo[pred]!! < rpo[bid]!!) {
acc + 1
} else {
acc
}
}
return count >= 2
}
fun isLoopHeader(
bid: Int,
rpo: Rpo,
preds: Predecessors,
): Boolean {
return preds[bid]!!.any {
rpo[it]!! > rpo[bid]!!
}
}
sealed interface ContainingSyntax
data class LoopHeadedBy(val node: DTree) : ContainingSyntax
typealias Context = List<ContainingSyntax>
fun doTree(
node: DTree,
rpo: Rpo,
preds: Predecessors,
blocks: Blocks,
context: Context,
labelToBlock: LabelToBlock,
): List<BriloopInstr> {
val (x, children) = node
val mergeNodes = children.filter { (bid, _) -> isMergeNode(bid, rpo, preds) }
val codeForX = nodeWithin(node, mergeNodes, rpo, preds, blocks, labelToBlock)
val instr: List<BriloopInstr> = if (isLoopHeader(x, rpo, preds)) {
val ctxt1 = listOf(LoopHeadedBy(node)) + context
val loop = BriloopLoopStmt(
body = codeForX(ctxt1),
)
listOf(loop)
} else {
codeForX(context)
}
return instr
}
fun nodeWithin(
node: DTree,
nodes: List<DTree>,
rpo: Rpo,
preds: Predecessors,
blocks: Blocks,
labelToBlock: LabelToBlock,
): (Context) -> List<BriloopInstr> {
fun base(): (Context) -> List<BriloopInstr> = { context: Context ->
val bid = node.bid
val brilInstrs = blocks[bid]!!
val briloopInstrs = LinkedList<BriloopInstr>()
for (i in 0 ..< brilInstrs.size - 1) {
val briloopInstr = brilInstrs[i]!!.toBriloop()
if (briloopInstr != null) {
briloopInstrs.add(briloopInstr)
}
}
val lastBrilInstr = brilInstrs[brilInstrs.size - 1]!!
val next: List<BriloopInstr> = if (lastBrilInstr is BrilJmpOp) {
doBranch(node, labelToBlock[lastBrilInstr.label]!!, context, labelToBlock, rpo, preds, blocks)
} else if (lastBrilInstr is BrilBrOp) {
BriloopIfThenStmt(
arg = lastBrilInstr.arg,
tru = doBranch(node, labelToBlock[lastBrilInstr.labelL]!!, context, labelToBlock, rpo, preds, blocks),
fals = doBranch(node, labelToBlock[lastBrilInstr.labelR]!!, context, labelToBlock, rpo, preds, blocks),
).let { listOf<BriloopInstr>(it) }
} else if (lastBrilInstr is BrilRetOp) {
BriloopOp(
op = "ret",
args = lastBrilInstr.arg?.let { listOf(it) },
dest = null,
type = null,
value = null,
funcs = null,
).let{ it -> listOf<BriloopInstr>(it) }
} else {
val lastBriloopInstr = lastBrilInstr.toBriloop()
if (lastBriloopInstr == null) {
log("Couldn't translate $lastBrilInstr")
} else {
briloopInstrs.add(lastBriloopInstr)
}
doBranch(node, node.bid + 1, context, labelToBlock, rpo, preds, blocks)
//throw IllegalStateException("Unexpected last node of block $lastBrilInstr")
}
briloopInstrs + next
}
fun inductive(): (Context) -> List<BriloopInstr> = { context: Context ->
listOf<BriloopInstr>(
BriloopBlockStmt(
body = nodeWithin(node, nodes.drop(1), rpo, preds, blocks, labelToBlock)(listOf(LoopHeadedBy(nodes.first())) + context)
)
) + doTree(nodes.first(), rpo, preds, blocks, context, labelToBlock)
}
return if (nodes.isEmpty()) {
base()
} else {
inductive()
}
}
var i = 0
fun generateVariableName(): String {
val name = "__v$i"
i = i + 1
return name
}
fun doBranch(
node: DTree,
nextbid: Int,
ctxt: Context,
labelToBlock: LabelToBlock,
rpo: Rpo,
preds: Predecessors,
blocks: Blocks,
) : List<BriloopInstr> {
val (bid, children) = node
val target = nextbid
// is backward edge
return if (rpo[target]!! < rpo[bid]!!) {
val name = generateVariableName()
val i = ctxt.indexOfFirst { (it is LoopHeadedBy) && (it.node.bid == target) }
val ival = BriloopValueInt(i)
val cont = BriloopContinueStmt(
value = ival,
)
listOf(
cont
)
// is Merge Label
} else if (isMergeNode(target, rpo, preds)) {
val name = generateVariableName()
val i = ctxt.indexOfFirst { (it is LoopHeadedBy) && (it.node.bid == target) }
val ival = BriloopValueInt(i)
val brStmt = BriloopBreakStmt(
value = ival,
)
listOf(
brStmt,
)
} else {
doTree(
node = children.first { it.bid == target } ,
rpo = rpo,
preds = preds,
blocks = blocks,
context = ctxt,
labelToBlock = labelToBlock,
)
}
}
fun sortedDtree(
dtree: DTree,
rpo: Rpo,
): DTree {
return dtree.copy(
children = dtree
.children
.map { sortedDtree(it, rpo) }
.sortedWith { l, r -> rpo[r.bid]!!.compareTo(l.bid) }
)
}
fun beyondRelooper(
func: BrilFunction
): BriloopFunction {
val (blocks, cfg) = cfg(func)
val preds = predecessors(cfg)
log("Preds")
preds.forEach { log(it.toString()) }
val doms = doms(blocks, cfg)
val sdoms = flip_doms(doms)
val idoms = idomsSearch(sdoms)
val tree = dtree(idoms)
log("dom tree")
log(tree.toString())
val rpo = reversePostOrder(cfg)
log("Rpo")
log(rpo.toString())
val orderedTree = sortedDtree(tree, rpo)
log("ordered tree")
log(orderedTree.formatted())
val labelToBlock = labelToBlock(blocks)
log("Merge nodes")
for (i in 0 ..< cfg.size) {
val text = if (isMergeNode(i, rpo, preds)) {
" is a merge node"
} else {
" is NOT a merge node"
}
log("Block $i $text")
}
log("Loop headers")
for (i in 0 ..< cfg.size) {
val text = if (isLoopHeader(i, rpo, preds)) {
" is a loop header node"
} else {
" is NOT a loop header node"
}
log("Block $i $text")
}
val brilooped = doTree(orderedTree, rpo, preds, blocks, emptyList(), labelToBlock)
return BriloopFunction(
name = func.name,
args = func.args?.map {
val arg: BriloopArg = it.toBriloop()
arg
},
type = func.type.toBriloop(),
instrs = brilooped,
)
}
@kotlin.ExperimentalStdlibApi
fun main(args: Array<String>) {
log("beyond relooper")
val moshi = moshi()
val brilAdapterProgram = brilProgram(args, moshi)
if (brilAdapterProgram == null) {
log("No program found")
return
}
val (_, brilProgram) = brilAdapterProgram
val briloopFuncs = brilProgram.functions.map { func ->
beyondRelooper(func)
}
val briloopProgram = BriloopProgram(
functions = briloopFuncs,
)
val briloopAdapter = moshi.adapter<BriloopProgram>()
val json = briloopAdapter.toJson(briloopProgram)
println(json)
}