CPSOptimizer.scala 21.5 KB
Newer Older
Sapphie's avatar
Sapphie committed
1
2
3
4
5
6
7
8
9
10
11
package l3

import scala.collection.mutable.{ Map => MutableMap }

abstract class CPSOptimizer[T <: CPSTreeModule { type Name = Symbol }]
  (val treeModule: T) {
  import treeModule._

  protected def rewrite(tree: Tree): Tree = {
    val simplifiedTree = fixedPoint(tree)(shrink)
    val maxSize = size(simplifiedTree) * 3 / 2
12
    fixedPoint(simplifiedTree, 8) { t => inline(t, maxSize) }
Sapphie's avatar
Sapphie committed
13
14
15
16
17
18
19
20
21
22
  }

  private case class Count(applied: Int = 0, asValue: Int = 0)

  private case class State(
    census: Map[Name, Count],
    aSubst: Subst[Atom] = emptySubst,
    cSubst: Subst[Name] = emptySubst,
    eInvEnv: Map[(ValuePrimitive, Seq[Atom]), Atom] = Map.empty,
    cEnv: Map[Name, Cnt] = Map.empty,
23
24
    fEnv: Map[Name, Fun] = Map.empty,
    bEnv: Map[(Atom, Atom), Atom] = Map.empty) {
Sapphie's avatar
Sapphie committed
25

Sapphie's avatar
Sapphie committed
26
27
    def eEnv: Map[Atom, (ValuePrimitive, Seq[Atom])] =
      eInvEnv.map(_.swap)
Sapphie's avatar
Sapphie committed
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
    def dead(s: Name): Boolean =
      ! census.contains(s)
    def appliedOnce(s: Name): Boolean =
      census.get(s).contains(Count(applied = 1, asValue = 0))

    def withASubst(from: Atom, to: Atom): State =
      copy(aSubst = aSubst + (from -> aSubst(to)))
    def withASubst(from: Name, to: Atom): State =
      withASubst(AtomN(from), to)
    def withASubst(from: Name, to: Literal): State =
      withASubst(from, AtomL(to))
    def withASubst(from: Seq[Name], to: Seq[Atom]): State =
      copy(aSubst = aSubst ++ (from.map(AtomN) zip to.map(aSubst)))

    def withCSubst(from: Name, to: Name): State =
      copy(cSubst = cSubst + (from -> cSubst(to)))

    def withExp(atom: Atom, prim: ValuePrimitive, args: Seq[Atom]): State =
      copy(eInvEnv = eInvEnv + ((prim, args) -> atom))
    def withExp(name: Name, prim: ValuePrimitive, args: Seq[Atom]): State =
      withExp(AtomN(name), prim, args)

    def withCnts(cnts: Seq[Cnt]): State =
      copy(cEnv = cEnv ++ (cnts.map(_.name) zip cnts))
    def withFuns(funs: Seq[Fun]): State =
      copy(fEnv = fEnv ++ (funs.map(_.name) zip funs))
54
55
56

    def withBlockVal(block: Atom, index: Atom, value: Atom): State =
      copy(bEnv = bEnv + ((block, index) -> value))
Sapphie's avatar
Sapphie committed
57
58
59
60
61
62
63
  }

  // Shrinking optimizations

  private def shrink(tree: Tree): Tree =
    shrink(tree, State(census(tree)))

64
65
  private def replaceArgs(args: Seq[Atom], s: State): Seq[Atom] = 
    args map { a => s.aSubst.getOrElse(a, a) }
66
67
68

  private def replaceCnt(cnt: Symbol, s: State): Symbol = 
    s.cSubst.getOrElse(cnt, cnt)
69
  
70
  private def shrink(tree: Tree, s: State): Tree = tree match {
Sapphie's avatar
Sapphie committed
71
    
72
    case AppC(oldCntName, args) => {
Sapphie's avatar
Sapphie committed
73
      val replacedArgs = replaceArgs(args, s)
74
      val cntName = replaceCnt(oldCntName, s)
75
76

      if (s.appliedOnce(cntName) && s.cEnv.contains(cntName)) {
Sapphie's avatar
Sapphie committed
77
78
79
80
81
82
        val cnt = s.cEnv(cntName)
        val newState = s.withASubst(cnt.args, replacedArgs)
        shrink(cnt.body, newState)
      } else {
        AppC(cntName, replacedArgs)
      }
83
84
85
86
    }
      
    case AppF(oldFunAtom, oldRetC, args) => {
      val funAtom = s.aSubst.getOrElse(oldFunAtom, oldFunAtom)
Sapphie's avatar
Sapphie committed
87
      val replacedArgs = replaceArgs(args, s)
88
      val retC = replaceCnt(oldRetC, s)
89

Sapphie's avatar
Sapphie committed
90
      funAtom match {
91
        case AtomN(n) if s.fEnv.contains(n) && s.appliedOnce(n) => 
Sapphie's avatar
Sapphie committed
92
          val fun = s.fEnv(n)
93
94
          val newState = s.withASubst(fun.args, replacedArgs).withCSubst(fun.retC, retC)
          shrink(fun.body, newState)
Sapphie's avatar
Sapphie committed
95
        case _ => AppF(funAtom, retC, replacedArgs)
Sapphie's avatar
Sapphie committed
96
      }
97
    }
Sapphie's avatar
Sapphie committed
98

99
100
101
102
    case LetF(funs, body) =>  {
      val undeadFuns = funs.filterNot(f => s.dead(f.name))
      val nonInlined = undeadFuns.filter(fun => !s.appliedOnce(fun.name))
      val newState = s.withFuns(undeadFuns)
103

104
105
106
107
108
109
      val shrunkFuns = nonInlined.map(f => Fun(f.name, f.retC, f.args, shrink(f.body, newState)))
      val shrunkBody = shrink(body, newState)

      if (shrunkFuns.isEmpty) shrunkBody 
      else LetF(shrunkFuns, shrunkBody)
    }
110
    
111
112
    case LetP(name, prim, args, body) => {
      val replacedArgs = replaceArgs(args, s)
Sapphie's avatar
Sapphie committed
113
      lazy val newState = s.withExp(name, prim, replacedArgs)
114
      lazy val shrunkBody = shrink(body, newState)
Sapphie's avatar
Sapphie committed
115
      lazy val noOp = LetP(name, prim, replacedArgs, shrunkBody)
116

117
      // Dead code elim
Sapphie's avatar
Sapphie committed
118
      if (s.dead(name) && !impure(prim)) {
119
        shrunkBody
Sapphie's avatar
Sapphie committed
120
      } else {
121
122
        val allLitOpt = replacedArgs.map(_.asLiteral)
        lazy val asLit = allLitOpt.map(_.get)
123
124

        if (!unstable(prim) && !impure(prim) && s.eInvEnv.contains((prim, replacedArgs))) {
125
126
          val preComputedAtom = s.eInvEnv((prim, replacedArgs))
          shrink(body, newState.withASubst(name, preComputedAtom))
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
        } else if (prim == identity) { 
          shrink(body, s.withASubst(name, replacedArgs(0)))
        } else replacedArgs match {
          // Constant folding
          case Seq(AtomL(l1), AtomL(l2)) if vEvaluator.isDefinedAt((prim, asLit)) => 
            shrink(body, s.withASubst(name, vEvaluator((prim, asLit))))
          // Same argument reduction
          case Seq(a1, a2) if a1 == a2 && sameArgReduce.isDefinedAt(prim, a1) =>
            val reduced = sameArgReduce((prim, a1))
            shrink(body, s.withASubst(name, sameArgReduce((prim, reduced))))
          // Left Neutral
          case Seq(AtomL(l1), a2) if leftNeutral((l1, prim)) =>
            shrink(body, s.withASubst(name, a2))
          // Left Absorbing
          case Seq(AtomL(l1), a2) if leftAbsorbing((l1, prim)) =>
            shrink(body, s.withASubst(name, l1))
          // Right Neutral
          case Seq(a1, AtomL(l2)) if rightNeutral((prim, l2)) =>
            shrink(body, s.withASubst(name, a1))
          // Right Absorbing
          case Seq(a1, AtomL(l2)) if rightAbsorbing((prim, l2)) =>
            shrink(body, s.withASubst(name, l2))
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

          case Seq(b, idx) if prim == blockGet && s.bEnv.isDefinedAt((b, idx)) =>
            shrink(body, s.withASubst(name, s.bEnv((b, idx))))
          case Seq(b, idx, v) if prim == blockSet && s.eEnv.isDefinedAt(b) =>
            val maybeBlockAlloc = s.eEnv(b)._1
            val isKnownConstant = blockAllocTag
              .lift(maybeBlockAlloc)
              .filter(constantTags(_))
              .isDefined

            if (isKnownConstant) {
              val newBody = shrink(body, newState.withBlockVal(b, idx, v))
              LetP(name, prim, replacedArgs, newBody)
            } else {
              noOp
            }

          // Single argument primitives
          // currently only checks for block length and
          // block tag
Sapphie's avatar
Sapphie committed
169
170
          case Seq(a1) if s.eEnv.isDefinedAt(a1) =>
            val (maybeBlockAlloc, maybeLengthAtom) = s.eEnv(a1)
Sapphie's avatar
Sapphie committed
171
172
            blockAllocTag.lift(maybeBlockAlloc) match {
              case Some(tag) =>
Sapphie's avatar
Sapphie committed
173
174
175
176
177
178
179
                if (prim == blockTag) {
                  shrink(body, s.withASubst(name, AtomL(tag)))
                } else if (prim == blockLength) {
                  shrink(body, s.withASubst(name, maybeLengthAtom(0)))
                } else {
                  noOp
                }
Sapphie's avatar
Sapphie committed
180
181
182
              case None =>
                noOp
            }
Sapphie's avatar
Sapphie committed
183

184
          case _ => noOp
185
        }
Sapphie's avatar
Sapphie committed
186
      }
187
    }
188
  
189
190
    case LetC(cnts, body) => {
      val undeadConts = cnts.filterNot(cnt => s.dead(cnt.name))
Sapphie's avatar
Sapphie committed
191
192
193
194
195
      val undeadShrunkConts = undeadConts.map { cnt =>
        val newBody = shrink(cnt.body, s)
        Cnt(cnt.name, cnt.args, newBody)
      }

196
197
      val nonInlinedConts = undeadShrunkConts.filterNot { cnt =>
        s.appliedOnce(cnt.name)
Sapphie's avatar
Sapphie committed
198
199
200
      }

      val newBody = shrink(body, s.withCnts(undeadShrunkConts))
Sapphie's avatar
Sapphie committed
201
      if (nonInlinedConts.isEmpty) {
Sapphie's avatar
Sapphie committed
202
203
        newBody
      } else {
Sapphie's avatar
Sapphie committed
204
        LetC(nonInlinedConts, newBody)
205
      }
206
207
208
    }

    case If(cond, args, thenC, elseC) => 
Sapphie's avatar
Sapphie committed
209
210
211
      val newArgs = replaceArgs(args, s)
      def getApp(b: Boolean): AppC = {
        val contToUse = if (b) thenC else elseC
212
        AppC(contToUse, Seq())
Sapphie's avatar
Sapphie committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
      }
      val allLitOpt = newArgs.map(_.asLiteral)
      val isAllLit = allLitOpt.forall(_.isDefined)
      lazy val asLit = allLitOpt.map(_.get)
      // Constant folding
      if (isAllLit && cEvaluator.isDefinedAt((cond, asLit))) {
        getApp(cEvaluator((cond, asLit)))
      } else {
        lazy val x = newArgs(0)
        lazy val y = newArgs(1)
        if (newArgs.length == 2 && x == y) {
          getApp(sameArgReduceC(cond))
        } else {
          If(cond, newArgs, replaceCnt(thenC, s), replaceCnt(elseC, s))
        }
      }
229

230
    case Halt(a) => 
Sapphie's avatar
Sapphie committed
231
232
      Halt(s.aSubst.getOrElse(a, a))

233
  }
Sapphie's avatar
Sapphie committed
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

  // (Non-shrinking) inlining

  private def inline(tree: Tree, maxSize: Int): Tree = {
    def copyT(tree: Tree, subV: Subst[Atom], subC: Subst[Name]): Tree = {
      (tree: @unchecked) match {
        case LetP(name, prim, args, body) =>
          val name1 = name.copy()
          LetP(name1, prim, args map subV,
               copyT(body, subV + (AtomN(name) -> AtomN(name1)), subC))
        case LetC(cnts, body) =>
          val names = cnts map (_.name)
          val names1 = names map (_.copy())
          val subC1 = subC ++ (names zip names1)
          LetC(cnts map (copyC(_, subV, subC1)), copyT(body, subV, subC1))
        case LetF(funs, body) =>
          val names = funs map (_.name)
          val names1 = names map (_.copy())
          val subV1 = subV ++ ((names map AtomN) zip (names1 map AtomN))
          LetF(funs map (copyF(_, subV1, subC)), copyT(body, subV1, subC))
        case AppC(cnt, args) =>
          AppC(subC(cnt), args map subV)
        case AppF(fun, retC, args) =>
          AppF(subV(fun), subC(retC), args map subV)
        case If(cond, args, thenC, elseC) =>
          If(cond, args map subV, subC(thenC), subC(elseC))
        case Halt(arg) =>
          Halt(subV(arg))
      }
    }

    def copyC(cnt: Cnt, subV: Subst[Atom], subC: Subst[Name]): Cnt = {
      val args1 = cnt.args map (_.copy())
      val subV1 = subV ++ ((cnt.args map AtomN) zip (args1 map AtomN))
      Cnt(subC(cnt.name), args1, copyT(cnt.body, subV1, subC))
    }

    def copyF(fun: Fun, subV: Subst[Atom], subC: Subst[Name]): Fun = {
      val retC1 = fun.retC.copy()
      val subC1 = subC + (fun.retC -> retC1)
      val args1 = fun.args map (_.copy())
      val subV1 = subV ++ ((fun.args map AtomN) zip (args1 map AtomN))
      val AtomN(funName1) = subV(AtomN(fun.name))
      Fun(funName1, retC1, args1, copyT(fun.body, subV1, subC1))
    }

    val fibonacci = Seq(1, 2, 3, 5, 8, 13)

    val trees = LazyList.iterate((0, tree), fibonacci.length){ case (i, tree) =>
      val funLimit = fibonacci(i)
      val cntLimit = i

      def sameLen[T,U](formalArgs: Seq[T], actualArgs: Seq[U]): Boolean =
        formalArgs.length == actualArgs.length

289
290
291
292
293
294
295
      def inlineT(tree: Tree)(implicit s: State): Tree = tree match {
        
        case AppC(oldCntName, oldArgs) => {
          val cntName = replaceCnt(oldCntName, s)
          val args = replaceArgs(oldArgs, s)
          
          if (s.cEnv.contains(cntName)) {
Luca Bataillard's avatar
Luca Bataillard committed
296
297
298
            val savedCnt = s.cEnv(cntName)
            val newState = s.withASubst(savedCnt.args, args)
            copyT(savedCnt.body, newState.aSubst, newState.cSubst)
299
300
301
302
303
304
305
306
307
308
309
310
          } else {
            AppC(cntName, args)
          }
        }

        case AppF(oldFunName, oldRetC, oldArgs) => {
          val funName = s.aSubst.getOrElse(oldFunName, oldFunName)
          val retC = replaceCnt(oldRetC, s)
          val args = replaceArgs(oldArgs, s) 

          funName match {
            case AtomN(n) if s.fEnv.contains(n) => {
Luca Bataillard's avatar
Luca Bataillard committed
311
312
313
314
315
              val savedFun = s.fEnv(n)
              
              if (sameLen(savedFun.args, args)) {
                val newState = s.withASubst(savedFun.args, args).withCSubst(savedFun.retC, retC) 
                copyT(savedFun.body, newState.aSubst, newState.cSubst)
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
              } else {
                AppF(funName, retC, args)
              }
            }
            case _ => AppF(funName, retC, args)
          }
        }

        case Halt(arg) => Halt(s.aSubst.getOrElse(arg, arg))
        case If(cond, args, thenC, elseC) => If(cond, replaceArgs(args, s), replaceCnt(thenC, s), replaceCnt(elseC, s))
        case LetP(name, prim, args, body) => LetP(name, prim, replaceArgs(args, s), inlineT(body))
        
        case LetC(oldCnts, body) => {
          val cnts = oldCnts map (c => Cnt(c.name, c.args, inlineT(c.body)))
          val inlinedCnts = cnts.filter(c => size(c.body) <= cntLimit)
          val newState = s.withCnts(inlinedCnts)

          LetC(cnts, inlineT(body)(newState))
        }

        case LetF(oldFuns, body) => {
          val funs = oldFuns map (f => Fun(f.name, f.retC, f.args, inlineT(f.body)))
          val inlinedFuns = funs.filter(f => size(f.body) <= funLimit)          
          val newState = s.withFuns(inlinedFuns)

          LetF(funs, inlineT(body)(newState))
        }
      }
Sapphie's avatar
Sapphie committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407

      (i + 1, fixedPoint(inlineT(tree)(State(census(tree))))(shrink))
    }

    trees.takeWhile{ case (_, tree) => size(tree) <= maxSize }.last._2
  }

  // Census computation
  private def census(tree: Tree): Map[Name, Count] = {
    val census = MutableMap[Name, Count]().withDefault(_ => Count())
    val rhs = MutableMap[Name, Tree]()

    def incAppUseN(name: Name): Unit = {
      val currCount = census(name)
      census(name) = currCount.copy(applied = currCount.applied + 1)
      rhs.remove(name).foreach(addToCensus)
    }

    def incAppUseA(atom: Atom): Unit =
      atom.asName.foreach(incAppUseN(_))

    def incValUseN(name: Name): Unit = {
      val currCount = census(name)
      census(name) = currCount.copy(asValue = currCount.asValue + 1)
      rhs.remove(name).foreach(addToCensus)
    }

    def incValUseA(atom: Atom): Unit =
      atom.asName.foreach(incValUseN(_))

    def addToCensus(tree: Tree): Unit = (tree: @unchecked) match {
      case LetP(_, _, args, body) =>
        args foreach incValUseA; addToCensus(body)
      case LetC(cnts, body) =>
        rhs ++= (cnts map { c => (c.name, c.body) }); addToCensus(body)
      case LetF(funs, body) =>
        rhs ++= (funs map { f => (f.name, f.body) }); addToCensus(body)
      case AppC(cnt, args) =>
        incAppUseN(cnt); args foreach incValUseA
      case AppF(fun, retC, args) =>
        incAppUseA(fun); incValUseN(retC); args foreach incValUseA
      case If(_, args, thenC, elseC) =>
        args foreach incValUseA; incValUseN(thenC); incValUseN(elseC)
      case Halt(arg) =>
        incValUseA(arg)
    }

    addToCensus(tree)
    census.toMap
  }

  private def size(tree: Tree): Int = (tree: @unchecked) match {
    case LetP(_, _, _, body) => size(body) + 1
    case LetC(cs, body) => (cs map { c => size(c.body) }).sum + size(body)
    case LetF(fs, body) => (fs map { f => size(f.body) }).sum + size(body)
    case AppC(_, _) | AppF(_, _, _) | If(_, _, _, _) | Halt(_) => 1
  }

  protected val impure: ValuePrimitive => Boolean
  protected val unstable: ValuePrimitive => Boolean

  protected val blockAllocTag: PartialFunction[ValuePrimitive, Literal]
  protected val blockTag: ValuePrimitive
  protected val blockLength: ValuePrimitive
408
409
410
  protected val blockGet: ValuePrimitive
  protected val blockSet: ValuePrimitive
  protected val constantTags: Set[Literal]
Sapphie's avatar
Sapphie committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439

  protected val identity: ValuePrimitive

  protected val leftNeutral: Set[(Literal, ValuePrimitive)]
  protected val rightNeutral: Set[(ValuePrimitive, Literal)]
  protected val leftAbsorbing: Set[(Literal, ValuePrimitive)]
  protected val rightAbsorbing: Set[(ValuePrimitive, Literal)]

  protected val sameArgReduce: PartialFunction[(ValuePrimitive, Atom), Atom]
  protected val sameArgReduceC: TestPrimitive => Boolean

  protected val vEvaluator: PartialFunction[(ValuePrimitive, Seq[Literal]),
                                            Literal]
  protected val cEvaluator: PartialFunction[(TestPrimitive, Seq[Literal]),
                                            Boolean]
}

object CPSOptimizerHigh extends CPSOptimizer(SymbolicCPSTreeModule)
    with (SymbolicCPSTreeModule.Tree => SymbolicCPSTreeModule.Tree) {
  import treeModule._
  import L3Primitive._

  def apply(tree: Tree): Tree =
    rewrite(tree)

  import scala.language.implicitConversions
  private[this] implicit def l3IntToLit(i: L3Int): Literal = IntLit(i)
  private[this] implicit def intToLit(i: Int): Literal = IntLit(L3Int(i))

Sapphie's avatar
Sapphie committed
440
441
  protected val impure: ValuePrimitive => Boolean =
    Set(ByteRead, ByteWrite, BlockSet)
Sapphie's avatar
Sapphie committed
442

Sapphie's avatar
Sapphie committed
443
444
445
446
  protected val unstable: ValuePrimitive => Boolean = {
    case BlockAlloc(_) | BlockGet | ByteRead => true
    case _ => false 
  }
Sapphie's avatar
Sapphie committed
447

Sapphie's avatar
Sapphie committed
448
449
450
451
452
  protected val blockAllocTag: PartialFunction[ValuePrimitive, Literal] = {
    case BlockAlloc(t) => t
  }
  protected val blockTag: ValuePrimitive = BlockTag
  protected val blockLength: ValuePrimitive = BlockLength
453
454
455
  protected val blockGet: ValuePrimitive = BlockGet
  protected val blockSet: ValuePrimitive = BlockSet
  protected val constantTags: Set[Literal] = Set(intToLit(200), intToLit(202))
Sapphie's avatar
Sapphie committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497

  protected val identity: ValuePrimitive = Id

  protected val leftNeutral: Set[(Literal, ValuePrimitive)] = Set(
    (IntLit(L3Int(0)), IntAdd),
    (IntLit(L3Int(1)), IntMul),
    (IntLit(L3Int((-1 << 1) >> 1)), IntBitwiseAnd),
    (IntLit(L3Int(0)), IntBitwiseOr),
    (IntLit(L3Int(0)), IntBitwiseXOr)
  )
  protected val rightNeutral: Set[(ValuePrimitive, Literal)] = Set(
    (IntAdd, IntLit(L3Int(0))),
    (IntSub, IntLit(L3Int(0))),
    (IntMul, IntLit(L3Int(1))),
    (IntDiv, IntLit(L3Int(1))),
    (IntShiftLeft, IntLit(L3Int(0))),
    (IntShiftRight, IntLit(L3Int(0))),
    (IntBitwiseAnd, IntLit(L3Int((-1 << 1) >> 1))),
    (IntBitwiseOr, IntLit(L3Int(0))),
    (IntBitwiseXOr, IntLit(L3Int(0))),
  )

  protected val leftAbsorbing: Set[(Literal, ValuePrimitive)] = Set(
    (IntLit(L3Int(0)), IntMul),
    (IntLit(L3Int(0)), IntMod),
    (IntLit(L3Int(0)), IntBitwiseAnd),
    (IntLit(L3Int((-1 << 1) >> 1)), IntBitwiseOr),
    (IntLit(L3Int(0)), IntShiftLeft),
    (IntLit(L3Int(0)), IntShiftRight)
  )

  protected val rightAbsorbing: Set[(ValuePrimitive, Literal)] = Set(
    (IntMul, IntLit(L3Int(0))),
    (IntBitwiseAnd, IntLit(L3Int(0))),
    (IntBitwiseOr, IntLit(L3Int((-1 << 1) >> 1)))
  )

  protected val sameArgReduce: PartialFunction[(ValuePrimitive, Atom), Atom] = {
    case (IntBitwiseAnd | IntBitwiseOr, a) => a
    case (IntSub | IntBitwiseXOr | IntMod, _) => AtomL(IntLit(L3Int(0)))
    case (IntDiv, _) => AtomL(IntLit(L3Int(1)))
  }
Sapphie's avatar
Sapphie committed
498
499


Sapphie's avatar
Sapphie committed
500
501
502
503
  protected val sameArgReduceC: PartialFunction[TestPrimitive, Boolean] = {
    case IntLt => false
    case IntLe | Eq => true
  }
Sapphie's avatar
Sapphie committed
504
505

  protected val vEvaluator: PartialFunction[(ValuePrimitive, Seq[Literal]),
Sapphie's avatar
Sapphie committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
                                            Literal] = {
    case (vPrim, Seq(IntLit(x), IntLit(y))) => vPrim match {
      case IntAdd => IntLit(x + y)
      case IntSub => IntLit(x - y)
      case IntMod => IntLit(x % y)
      case IntDiv => IntLit(x / y)
      case IntMul => IntLit(x * y)
      case IntBitwiseAnd => IntLit(x & y)
      case IntBitwiseOr => IntLit(x | y)
      case IntBitwiseXOr => IntLit(x ^ y)
      case IntShiftLeft => IntLit(x << y)
      case IntShiftRight => IntLit(x >> y)
    }
  }
Sapphie's avatar
Sapphie committed
520
521

  protected val cEvaluator: PartialFunction[(TestPrimitive, Seq[Literal]),
Sapphie's avatar
Sapphie committed
522
523
524
525
526
                                            Boolean] = {
    case (IntLe, Seq(IntLit(x), IntLit(y))) => x <= y
    case (IntLt, Seq(IntLit(x), IntLit(y))) => x < y
    case (Eq, Seq(l1, l2)) => l1 == l2
  }
Sapphie's avatar
Sapphie committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
}

object CPSOptimizerLow extends CPSOptimizer(SymbolicCPSTreeModuleLow)
    with (SymbolicCPSTreeModuleLow.LetF => SymbolicCPSTreeModuleLow.LetF) {
  import treeModule._
  import CPSValuePrimitive._
  import CPSTestPrimitive._

  def apply(tree: LetF): LetF = rewrite(tree) match {
    case tree @ LetF(_, _) => tree
    case other => LetF(Seq(), other)
  }

  protected val impure: ValuePrimitive => Boolean =
    Set(BlockSet, ByteRead, ByteWrite)

  protected val unstable: ValuePrimitive => Boolean = {
    case BlockAlloc(_) | BlockGet | ByteRead => true
    case _ => false
  }

  protected val blockAllocTag: PartialFunction[ValuePrimitive, Literal] = {
    case BlockAlloc(tag) => tag
  }
  protected val blockTag: ValuePrimitive = BlockTag
  protected val blockLength: ValuePrimitive = BlockLength
553
554
555
  protected val blockGet: ValuePrimitive = BlockGet
  protected val blockSet: ValuePrimitive = BlockSet
  protected val constantTags = Set(200, 202)
Sapphie's avatar
Sapphie committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605

  protected val identity: ValuePrimitive = Id

  protected val leftNeutral: Set[(Literal, ValuePrimitive)] =
    Set((0, Add), (1, Mul), (~0, And), (0, Or), (0, XOr))
  protected val rightNeutral: Set[(ValuePrimitive, Literal)] =
    Set((Add, 0), (Sub, 0), (Mul, 1), (Div, 1),
        (ShiftLeft, 0), (ShiftRight, 0),
        (And, ~0), (Or, 0), (XOr, 0))

  protected val leftAbsorbing: Set[(Literal, ValuePrimitive)] =
    Set((0, Mul), (0, Div),
        (0, ShiftLeft), (0, ShiftRight),
        (0, And), (~0, Or))
  protected val rightAbsorbing: Set[(ValuePrimitive, Literal)] =
    Set((Mul, 0), (And, 0), (Or, ~0))

  protected val sameArgReduce: PartialFunction[(ValuePrimitive, Atom), Atom] = {
    case (And | Or, a) => a
    case (Sub | Mod | XOr, _) => AtomL(0)
    case (Div, _) => AtomL(1)
  }

  protected val sameArgReduceC: PartialFunction[TestPrimitive, Boolean] = {
    case Le | Eq => true
    case Lt => false
  }

  protected val vEvaluator: PartialFunction[(ValuePrimitive, Seq[Literal]),
                                            Literal] = {
    case (Add, Seq(x, y)) => x + y
    case (Sub, Seq(x, y)) => x - y
    case (Mul, Seq(x, y)) => x * y
    case (Div, Seq(x, y)) if y.toInt != 0 => x / y
    case (Mod, Seq(x, y)) if y.toInt != 0 => x % y

    case (ShiftLeft,  Seq(x, y)) => x << y
    case (ShiftRight, Seq(x, y)) => x >> y
    case (And, Seq(x, y)) => x & y
    case (Or,  Seq(x, y)) => x | y
    case (XOr, Seq(x, y)) => x ^ y
  }

  protected val cEvaluator: PartialFunction[(TestPrimitive, Seq[Literal]),
                                            Boolean] = {
    case (Lt, Seq(x, y)) => x < y
    case (Le, Seq(x, y)) => x <= y
    case (Eq, Seq(x, y)) => x == y
  }
}