dfe1b363f7429c934ba16aefe9e3b5d4dfb706ba
[mate.git] / Mate / BasicBlocks.hs
1 {-# LANGUAGE OverloadedStrings #-}
2 module Mate.BasicBlocks(
3   BlockID,
4   BasicBlock,
5   BBEnd,
6   MapBB,
7   Method,
8   printMapBB,
9   parseMethod,
10   testCFG -- added by hs to perform benches from outside
11   )where
12
13 import Data.Binary
14 import Data.Int
15 import Data.List
16 import qualified Data.Map as M
17 import qualified Data.ByteString.Lazy as B
18 import Data.Maybe
19
20 import JVM.ClassFile
21 import JVM.Converter
22 import JVM.Assembler
23
24 import Mate.Types
25 import Mate.Debug
26 import Mate.Utilities
27
28 -- for immediate representation to determine BBs
29 type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
30 type OffIns = (Offset, Instruction)
31
32
33 printMapBB :: MapBB -> IO ()
34 printMapBB hmap = do
35   printfBb "BlockIDs: "
36   let keys = M.keys hmap
37   mapM_ (printfBb . flip (++) ", " . show) keys
38   printfBb "\n\nBasicBlocks:\n"
39   printMapBB' keys hmap
40     where
41       printMapBB' :: [BlockID] -> MapBB -> IO ()
42       printMapBB' [] _ = return ()
43       printMapBB' (i:is) hmap' = case M.lookup i hmap' of
44         Just bb -> do
45           printfBb $ "Block " ++ show i ++ "\n"
46           mapM_ (printfBb . flip (++) "\n" . (++) "\t" . show) $ code bb
47           printfBb $ case successor bb of
48             Return -> ""
49             FallThrough t1 -> "Sucessor: " ++ show t1 ++ "\n"
50             OneTarget t1 -> "Sucessor: " ++ show t1 ++ "\n"
51             TwoTarget t1 t2 -> "Sucessor: " ++ show t1 ++ ", " ++ show t2 ++ "\n"
52           printMapBB' is hmap
53         Nothing -> error $ "BlockID " ++ show i ++ " not found."
54
55 {-
56 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
57 testInstance cf method sig = do
58   cls <- parseClassFile cf
59   hmap <- parseMethod cls method sig
60   printMapBB hmap
61
62 test_main :: IO ()
63 test_main = do
64   test_01
65   test_02
66   test_03
67   test_04
68
69 test_01, test_02, test_03, test_04 :: IO ()
70 test_01 = testInstance "./tests/Fib.class" "fib"
71 test_02 = testInstance "./tests/While.class" "f"
72 test_03 = testInstance "./tests/While.class" "g"
73 test_04 = testInstance "./tests/Fac.class" "fac"
74 -}
75
76
77 parseMethod :: Class Direct -> B.ByteString -> MethodSignature -> IO RawMethod
78 parseMethod cls methodname sig = do
79   let method = fromMaybe
80                (error $ "method " ++ (show . toString) methodname ++ " not found")
81                (lookupMethodSig methodname sig cls)
82   let codeseg = fromMaybe
83                 (error $ "codeseg " ++ (show . toString) methodname ++ " not found")
84                 (attrByName method "Code")
85   let decoded = decodeMethod codeseg
86   let mapbb = testCFG decoded
87   let locals = fromIntegral (codeMaxLocals decoded)
88   let stacks = fromIntegral (codeStackSize decoded)
89   let codelen = fromIntegral (codeLength decoded)
90   let methoddirect = methodInfoToMethod (MethodInfo methodname "" sig) cls
91   let isStatic = methodIsStatic methoddirect
92   let nametype = methodNameType methoddirect
93   let argscount = methodGetArgsCount nametype + (if isStatic then 0 else 1)
94
95   let msig = methodSignature method
96   printfBb $ printf "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
97   printMapBB mapbb
98   -- small example how to get information about
99   -- exceptions of a method
100   -- TODO: remove ;-)
101   let (Just m) = lookupMethodSig methodname sig cls
102   case attrByName m "Code" of
103     Nothing ->
104       printfBb $ printf "exception: no handler for this method\n"
105     Just exceptionstream ->
106       printfBb $ printf "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
107   return $ RawMethod mapbb locals stacks argscount codelen
108
109
110 testCFG :: Code -> MapBB
111 testCFG = buildCFG . codeInstructions
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 = case x_bbend of
129         Just _ -> x -- already marked, don't change
130         Nothing -> if isTarget then checkX y_off else x
131       checkX w16 = case x_bbend of
132         Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
133         _ -> error "basicblock: something is wrong"
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     entryi :: [BlockID]
153     entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
154       where
155         ys = 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         IFNONNULL w16 -> twotargets w16
199         IFNULL w16 -> twotargets w16
200         GOTO w16 -> onetarget w16
201         IRETURN -> notarget
202         ARETURN -> notarget
203         RETURN -> notarget
204         _ -> ((off, Nothing), x):next
205       where
206         notarget = ((off, Just Return), x):next
207         onetarget w16 = ((off, Just $ OneTarget (off `addW16Signed` w16)), x):next
208         twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
209         next = cio' (newoffset x off) xs