refactor: store amount of arguments of a method in RawMethod
[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   Method,
10 #ifdef DBG_BB
11   printMapBB,
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 import Mate.Utilities
30
31 #ifdef DEBUG
32 import Text.Printf
33 #endif
34
35 -- for immediate representation to determine BBs
36 type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
37 type OffIns = (Offset, Instruction)
38
39
40 #ifdef DBG_BB
41 printMapBB :: MapBB -> IO ()
42 printMapBB hmap = do
43   putStr "BlockIDs: "
44   let keys = M.keys 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 #if 0
65 #ifdef DBG_BB
66 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
67 testInstance cf method sig = do
68   cls <- parseClassFile cf
69   hmap <- parseMethod cls method sig
70   printMapBB hmap
71 #endif
72
73 #ifdef DBG_BB
74 test_main :: IO ()
75 test_main = do
76   test_01
77   test_02
78   test_03
79   test_04
80
81 test_01, test_02, test_03, test_04 :: IO ()
82 test_01 = testInstance "./tests/Fib.class" "fib"
83 test_02 = testInstance "./tests/While.class" "f"
84 test_03 = testInstance "./tests/While.class" "g"
85 test_04 = testInstance "./tests/Fac.class" "fac"
86 #endif
87 #endif
88
89
90 parseMethod :: Class Direct -> B.ByteString -> MethodSignature -> IO RawMethod
91 parseMethod cls methodname sig = do
92   let method = case lookupMethodSig methodname sig cls of
93         Just m -> m
94         Nothing -> error $ "method " ++ (show . toString) methodname ++ " not found"
95   let codeseg = case attrByName method "Code" of
96         Just m -> m
97         Nothing -> error $ "codeseg " ++ (show . toString) methodname ++ " not found"
98   let decoded = decodeMethod codeseg
99   let mapbb = testCFG decoded
100   let locals = fromIntegral (codeMaxLocals decoded)
101   let stacks = fromIntegral (codeStackSize decoded)
102   let methoddirect = methodInfoToMethod (MethodInfo methodname "" sig) cls
103   let isStatic = methodIsStatic methoddirect
104   let nametype = methodNameType methoddirect
105   let argscount = methodGetArgsCount nametype + (if isStatic then 0 else 1)
106
107   let msig = methodSignature $ classMethods cls !! 1
108   printfBb "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
109 #ifdef DBG_BB
110   case maybe_bb of
111     Just m -> printMapBB $ rawMapBB m
112     Nothing -> return ()
113 #endif
114   -- small example how to get information about
115   -- exceptions of a method
116   -- TODO: remove ;-)
117   let (Just m) = lookupMethodSig methodname sig cls
118   case attrByName m "Code" of
119     Nothing ->
120       printfBb "exception: no handler for this method\n"
121     Just exceptionstream ->
122       printfBb "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
123   return $ RawMethod mapbb locals stacks argscount
124
125
126 testCFG :: Code -> MapBB
127 testCFG = buildCFG . codeInstructions
128
129 buildCFG :: [Instruction] -> MapBB
130 buildCFG xs = buildCFG' M.empty xs' xs'
131   where
132   xs' :: [OffIns]
133   xs' = markBackwardTargets $ calculateInstructionOffset xs
134
135 -- get already calculated jmp-targets and mark the predecessor of the
136 -- target-instruction as "FallThrough". we just care about backwards
137 -- jumps here (forward jumps are handled in buildCFG')
138 markBackwardTargets :: [OffIns] -> [OffIns]
139 markBackwardTargets [] = []
140 markBackwardTargets (x:[]) = [x]
141 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
142   x_new:markBackwardTargets (y:xs)
143     where
144       x_new = if isTarget then checkX y_off else x
145       checkX w16 = case x_bbend of
146         Just _ -> x -- already marked, don't change
147         Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
148
149       -- look through all remaining insns in the stream if there is a jmp to `y'
150       isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
151       cmpOffset ((_,Just (OneTarget w16)),_) = w16 == y_off
152       cmpOffset ((_,Just (TwoTarget _ w16)),_) = w16 == y_off
153       cmpOffset _ = False
154
155
156 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
157 buildCFG' hmap [] _ = hmap
158 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
159   where
160     insertlist :: [BlockID] -> MapBB -> MapBB
161     insertlist [] hmap' = hmap'
162     insertlist (y:ys) hmap' = insertlist ys newhmap
163       where
164         newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
165         value = parseBasicBlock y insns
166     entryi :: [BlockID]
167     entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
168       where
169         ys = case entry of
170           Just (TwoTarget t1 t2) -> [t1, t2]
171           Just (OneTarget t) -> [t]
172           Just (FallThrough t) -> [t]
173           Just Return -> []
174           Nothing -> []
175
176
177 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
178 parseBasicBlock i insns = BasicBlock insonly endblock
179   where
180     startlist = dropWhile (\((x,_),_) -> x < i) insns
181     (Just ((_, Just endblock),_), is) = takeWhilePlusOne validins startlist
182     insonly = snd $ unzip is
183
184     -- also take last (non-matched) element and return it
185     takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
186     takeWhilePlusOne _ [] = (Nothing,[])
187     takeWhilePlusOne p (x:xs)
188       | p x       =  let (lastins, list) = takeWhilePlusOne p xs in (lastins, x:list)
189       | otherwise =  (Just x,[x])
190
191     validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
192     validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
193
194
195 calculateInstructionOffset :: [Instruction] -> [OffIns]
196 calculateInstructionOffset = cio' (0, Nothing)
197   where
198     newoffset :: Instruction -> Int -> Offset
199     newoffset x off = (off + fromIntegral (B.length $ encodeInstructions [x]), Nothing)
200
201     addW16Signed :: Int -> Word16 -> Int
202     addW16Signed i w16 = i + fromIntegral s16
203       where s16 = fromIntegral w16 :: Int16
204
205     cio' :: Offset -> [Instruction] -> [OffIns]
206     cio' _ [] = []
207     -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
208     cio' (off,_) (x:xs) = case x of
209         IF _ w16 -> twotargets w16
210         IF_ICMP _ w16 -> twotargets w16
211         IF_ACMP _ w16 -> twotargets w16
212         IFNONNULL w16 -> twotargets w16
213         IFNULL w16 -> twotargets w16
214         GOTO w16 -> onetarget w16
215         IRETURN -> notarget
216         ARETURN -> notarget
217         RETURN -> notarget
218         _ -> ((off, Nothing), x):next
219       where
220         notarget = ((off, Just Return), x):next
221         onetarget w16 = ((off, Just $ OneTarget (off `addW16Signed` w16)), x):next
222         twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
223         next = cio' (newoffset x off) xs