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