Skip to content

Commit

Permalink
copy propagation
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaszcz committed Jun 14, 2024
1 parent e2a6344 commit 3b01785
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/Juvix/Compiler/Reg/Transformation/CopyPropagation.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
module Juvix.Compiler.Reg.Transformation.CopyPropagation where

import Data.HashMap.Strict qualified as HashMap
import Data.HashSet qualified as HashSet
import Juvix.Compiler.Reg.Extra
import Juvix.Compiler.Reg.Transformation.Base

type VarMap = HashMap VarRef VarRef

copyPropagateFunction :: Code -> Code
copyPropagateFunction =
snd
. runIdentity
. recurseF
ForwardRecursorSig
{ _forwardFun = \i acc -> return (go i acc),
_forwardCombine = combine
}
mempty
where
go :: Instruction -> VarMap -> (VarMap, Instruction)
go instr mpv = case instr' of
Assign InstrAssign {..}
| VRef v <- _instrAssignValue ->
(HashMap.insert _instrAssignResult v mpv', instr')
_ ->
(mpv', instr')
where
instr' = overValueRefs (adjustVarRef mpv) instr
mpv' = maybe mpv (filterOutVars mpv) (getResultVar instr')

filterOutVars :: VarMap -> VarRef -> VarMap
filterOutVars mpv v = HashMap.filter (/= v) mpv

adjustVarRef :: VarMap -> VarRef -> VarRef
adjustVarRef mpv vref@VarRef {..} = case _varRefGroup of
VarGroupArgs -> vref
VarGroupLocal -> fromMaybe vref $ HashMap.lookup vref mpv

combine :: Instruction -> NonEmpty VarMap -> (VarMap, Instruction)
combine instr mpvs = (mpv, instr)
where
mpv' :| mpvs' = fmap HashMap.toList mpvs
mpv =
HashMap.fromList
. HashSet.toList
. foldr (HashSet.intersection . HashSet.fromList) (HashSet.fromList mpv')
$ mpvs'

copyPropagate :: InfoTable -> InfoTable
copyPropagate = mapT (const copyPropagateFunction)

0 comments on commit 3b01785

Please sign in to comment.