2 {-# LANGUAGE OverloadedStrings #-}
4 module Mate.BasicBlocks(
14 testCFG -- added by hs to perform benches from outside
20 import qualified Data.Map as M
21 import qualified Data.ByteString.Lazy as B
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)
41 printMapBB :: MapBB -> IO ()
44 let keys = M.keys hmap
45 mapM_ (putStr . (flip (++)) ", " . show) keys
46 putStrLn "\n\nBasicBlocks:"
49 printMapBB' :: [BlockID] -> MapBB -> IO ()
50 printMapBB' [] _ = return ()
51 printMapBB' (i:is) hmap' = case M.lookup i hmap' of
53 putStrLn $ "Block " ++ (show i)
54 mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
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"
61 Nothing -> error $ "BlockID " ++ show i ++ " not found."
66 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
67 testInstance cf method sig = do
68 cls <- parseClassFile cf
69 hmap <- parseMethod cls method sig
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"
90 parseMethod :: Class Direct -> B.ByteString -> MethodSignature -> IO (Maybe RawMethod)
91 parseMethod cls method sig = do
92 let maybe_bb = testCFG $ lookupMethodSig method sig cls
93 let msig = methodSignature $ classMethods cls !! 1
94 printfBb "BB: analysing \"%s\"\n" $ toString (method `B.append` ": " `B.append` encode msig)
97 Just m -> printMapBB $ rawMapBB m
100 -- small example how to get information about
101 -- exceptions of a method
103 let (Just m) = lookupMethodSig method sig cls
104 case attrByName m "Code" of
106 printfBb "exception: no handler for this method\n"
107 Just exceptionstream ->
108 printfBb "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
112 testCFG :: Maybe (Method Direct) -> Maybe RawMethod
115 codeseg <- attrByName m' "Code"
116 let decoded = decodeMethod codeseg
117 let mapbb = buildCFG $ codeInstructions decoded
118 let locals = fromIntegral (codeMaxLocals decoded)
119 let stacks = fromIntegral (codeStackSize decoded)
120 return $ RawMethod mapbb locals stacks
123 buildCFG :: [Instruction] -> MapBB
124 buildCFG xs = buildCFG' M.empty xs' xs'
127 xs' = markBackwardTargets $ calculateInstructionOffset xs
129 -- get already calculated jmp-targets and mark the predecessor of the
130 -- target-instruction as "FallThrough". we just care about backwards
131 -- jumps here (forward jumps are handled in buildCFG')
132 markBackwardTargets :: [OffIns] -> [OffIns]
133 markBackwardTargets [] = []
134 markBackwardTargets (x:[]) = [x]
135 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
136 x_new:markBackwardTargets (y:xs)
138 x_new = if isTarget then checkX y_off else x
139 checkX w16 = case x_bbend of
140 Just _ -> x -- already marked, don't change
141 Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
143 -- look through all remaining insns in the stream if there is a jmp to `y'
144 isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
145 cmpOffset ((_,Just (OneTarget w16)),_) = w16 == y_off
146 cmpOffset ((_,Just (TwoTarget _ w16)),_) = w16 == y_off
150 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
151 buildCFG' hmap [] _ = hmap
152 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
154 insertlist :: [BlockID] -> MapBB -> MapBB
155 insertlist [] hmap' = hmap'
156 insertlist (y:ys) hmap' = insertlist ys newhmap
158 newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
159 value = parseBasicBlock y insns
161 entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
164 Just (TwoTarget t1 t2) -> [t1, t2]
165 Just (OneTarget t) -> [t]
166 Just (FallThrough t) -> [t]
171 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
172 parseBasicBlock i insns = BasicBlock insonly endblock
174 startlist = dropWhile (\((x,_),_) -> x < i) insns
175 (Just ((_, Just endblock),_), is) = takeWhilePlusOne validins startlist
176 insonly = snd $ unzip is
178 -- also take last (non-matched) element and return it
179 takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
180 takeWhilePlusOne _ [] = (Nothing,[])
181 takeWhilePlusOne p (x:xs)
182 | p x = let (lastins, list) = takeWhilePlusOne p xs in (lastins, x:list)
183 | otherwise = (Just x,[x])
185 validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
186 validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
189 calculateInstructionOffset :: [Instruction] -> [OffIns]
190 calculateInstructionOffset = cio' (0, Nothing)
192 newoffset :: Instruction -> Int -> Offset
193 newoffset x off = (off + fromIntegral (B.length $ encodeInstructions [x]), Nothing)
195 addW16Signed :: Int -> Word16 -> Int
196 addW16Signed i w16 = i + fromIntegral s16
197 where s16 = fromIntegral w16 :: Int16
199 cio' :: Offset -> [Instruction] -> [OffIns]
201 -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
202 cio' (off,_) (x:xs) = case x of
203 IF _ w16 -> twotargets w16
204 IF_ICMP _ w16 -> twotargets w16
205 IF_ACMP _ w16 -> twotargets w16
206 IFNONNULL w16 -> twotargets w16
207 IFNULL w16 -> twotargets w16
208 GOTO w16 -> onetarget w16
212 _ -> ((off, Nothing), x):next
214 notarget = ((off, Just Return), x):next
215 onetarget w16 = ((off, Just $ OneTarget (off `addW16Signed` w16)), x):next
216 twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
217 next = cio' (newoffset x off) xs