14f89997b61caf1a93d3728d504ea5af99f7ae27
[mate.git] / Mate / BasicBlocks.hs
1 {-# LANGUAGE OverloadedStrings #-}
2 module Mate.BasicBlocks(
3   BlockID,
4   BasicBlock (..),
5   BBEnd (..),
6   MapBB,
7   printMapBB,
8   parseMethod,
9   test_main
10   )where
11
12 import Data.Binary
13 import Data.Int
14 import Data.List
15 import qualified Data.Map as M
16 import qualified Data.ByteString.Lazy as B
17
18 import JVM.ClassFile
19 import JVM.Converter
20 import JVM.Assembler
21
22 import Mate.Utilities
23
24
25 type BlockID = Int
26 -- Represents a CFG node
27 data BasicBlock = BasicBlock {
28                      -- inputs  :: [Variable],
29                      -- outputs :: [Variable],
30                      code    :: [Instruction],
31                      successor :: BBEnd }
32
33 -- describes (leaving) edges of a CFG node
34 data BBEnd = Return | FallThrough BlockID | OneTarget BlockID | TwoTarget BlockID BlockID deriving Show
35
36 type MapBB = M.Map BlockID BasicBlock
37
38 -- for immediate representation for determine BBs
39 type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
40 type OffIns = (Offset, Instruction)
41
42
43 printMapBB :: Maybe MapBB -> IO ()
44 printMapBB Nothing = putStrLn "No BasicBlock"
45 printMapBB (Just hmap) = do
46                      putStr "BlockIDs: "
47                      let keys = fst $ unzip $ M.toList hmap
48                      mapM_ (putStr . (flip (++)) ", " . show) keys
49                      putStrLn "\n\nBasicBlocks:"
50                      printMapBB' keys hmap
51   where
52   printMapBB' :: [BlockID] -> MapBB -> IO ()
53   printMapBB' [] _ = return ()
54   printMapBB' (i:is) hmap' = case M.lookup i hmap' of
55                   Just bb -> do
56                              putStrLn $ "Block " ++ (show i)
57                              mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
58                              case successor bb of
59                                Return -> putStrLn ""
60                                FallThrough t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
61                                OneTarget t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
62                                TwoTarget t1 t2 -> putStrLn $ "Sucessor: " ++ (show t1) ++ ", " ++ (show t2) ++ "\n"
63                              printMapBB' is hmap
64                   Nothing -> error $ "BlockID " ++ show i ++ " not found."
65
66 testInstance :: String -> B.ByteString -> IO ()
67 testInstance cf method = do
68                       cls <- parseClassFile cf
69                       hmap <- parseMethod cls method
70                       printMapBB hmap
71
72 test_main :: IO ()
73 test_main = do
74   test_01
75   test_02
76   test_03
77   test_04
78
79 test_01, test_02, test_03, test_04 :: IO ()
80 test_01 = testInstance "./tests/Fib.class" "fib"
81 test_02 = testInstance "./tests/While.class" "f"
82 test_03 = testInstance "./tests/While.class" "g"
83 test_04 = testInstance "./tests/Fac.class" "fac"
84
85
86 parseMethod :: Class Resolved -> B.ByteString -> IO (Maybe MapBB)
87 parseMethod cls method = do
88                      putStr "BB: analysing: "
89                      let msig = methodSignature $ (classMethods cls) !! 1
90                      B.putStrLn (method `B.append` ": " `B.append` (encode msig))
91                      return $ testCFG $ lookupMethod method cls
92
93
94 testCFG :: Maybe (Method Resolved) -> Maybe MapBB
95 testCFG (Just m) = case attrByName m "Code" of
96        Nothing -> Nothing
97        Just bytecode -> Just $ buildCFG $ codeInstructions $ decodeMethod bytecode
98 testCFG _ = Nothing
99
100
101 buildCFG :: [Instruction] -> MapBB
102 buildCFG xs = buildCFG' M.empty xs' xs'
103   where
104   xs' :: [OffIns]
105   xs' = markBackwardTargets $ calculateInstructionOffset xs
106
107 -- get already calculated jmp-targets and mark the predecessor of the
108 -- target-instruction as "FallThrough". we just care about backwards
109 -- jumps here (forward jumps are handled in buildCFG')
110 markBackwardTargets :: [OffIns] -> [OffIns]
111 markBackwardTargets [] = []
112 markBackwardTargets (x:[]) = [x]
113 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
114   (x_new):(markBackwardTargets (y:xs))
115   where
116   x_new = if isTarget then checkX y_off else x
117   checkX w16 = case x_bbend of
118     Just _ -> x -- already marked, don't change
119     Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
120
121   -- look through all remaining insns in the stream if there is a jmp to `y'
122   isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
123   cmpOffset ((_,(Just (OneTarget w16))),_) = w16 == y_off
124   cmpOffset ((_,(Just (TwoTarget _ w16))),_) = w16 == y_off
125   cmpOffset _ = False
126
127
128 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
129 buildCFG' hmap [] _ = hmap
130 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
131   where
132   insertlist :: [BlockID] -> MapBB -> MapBB
133   insertlist [] hmap' = hmap'
134   insertlist (y:ys) hmap' = insertlist ys newhmap
135     where
136     newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
137     value = parseBasicBlock y insns
138
139   entryi :: [BlockID]
140   entryi = (if off == 0 then [0] else []) ++ -- also consider the entrypoint
141         case entry of
142         Just (TwoTarget t1 t2) -> [t1, t2]
143         Just (OneTarget t) -> [t]
144         Just (FallThrough t) -> [t]
145         Just (Return) -> []
146         Nothing -> []
147
148
149 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
150 parseBasicBlock i insns = BasicBlock insonly endblock
151   where
152   startlist = dropWhile (\((x,_),_) -> x < i) insns
153   (Just ((_,(Just endblock)),_), is) = takeWhilePlusOne validins startlist
154   insonly = snd $ unzip is
155
156   -- also take last (non-matched) element and return it
157   takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
158   takeWhilePlusOne _ [] = (Nothing,[])
159   takeWhilePlusOne p (x:xs)
160     | p x       =  let (lastins, list) = takeWhilePlusOne p xs in (lastins, (x:list))
161     | otherwise =  (Just x,[x])
162
163   validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
164   validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
165
166
167 calculateInstructionOffset :: [Instruction] -> [OffIns]
168 calculateInstructionOffset = cio' (0, Nothing)
169   where
170   newoffset :: Instruction -> Int -> Offset
171   newoffset x off = (off + (fromIntegral $ B.length $ encodeInstructions [x]), Nothing)
172
173   addW16Signed :: Int -> Word16 -> Int
174   addW16Signed i w16 = i + (fromIntegral s16)
175     where s16 = (fromIntegral w16) :: Int16
176
177   cio' :: Offset -> [Instruction] -> [OffIns]
178   cio' _ [] = []
179   -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
180   cio' (off,_) (x:xs) = case x of
181       IF _ w16 -> twotargets w16
182       IF_ICMP _ w16 -> twotargets w16
183       GOTO w16 -> onetarget w16
184       IRETURN -> notarget
185       RETURN -> notarget
186       _ -> ((off, Nothing), x):next
187     where
188     notarget = ((off, Just Return), x):next
189     onetarget w16 = ((off, Just $ OneTarget $ (off `addW16Signed` w16)), x):next
190     twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
191     next = cio' (newoffset x off) xs