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