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