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
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)
42 printMapBB :: MapBB -> IO ()
45 let keys = M.keys hmap
46 mapM_ (putStr . (flip (++)) ", " . show) keys
47 putStrLn "\n\nBasicBlocks:"
50 printMapBB' :: [BlockID] -> MapBB -> IO ()
51 printMapBB' [] _ = return ()
52 printMapBB' (i:is) hmap' = case M.lookup i hmap' of
54 putStrLn $ "Block " ++ (show i)
55 mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
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"
62 Nothing -> error $ "BlockID " ++ show i ++ " not found."
67 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
68 testInstance cf method sig = do
69 cls <- parseClassFile cf
70 hmap <- parseMethod cls method sig
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"
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)
108 let msig = methodSignature method
109 printfBb "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
113 -- small example how to get information about
114 -- exceptions of a method
116 let (Just m) = lookupMethodSig methodname sig cls
117 case attrByName m "Code" of
119 printfBb "exception: no handler for this method\n"
120 Just exceptionstream ->
121 printfBb "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
122 return $ RawMethod mapbb locals stacks argscount
125 testCFG :: Code -> MapBB
126 testCFG = buildCFG . codeInstructions
128 buildCFG :: [Instruction] -> MapBB
129 buildCFG xs = buildCFG' M.empty xs' xs'
132 xs' = markBackwardTargets $ calculateInstructionOffset xs
134 -- get already calculated jmp-targets and mark the predecessor of the
135 -- target-instruction as "FallThrough". we just care about backwards
136 -- jumps here (forward jumps are handled in buildCFG')
137 markBackwardTargets :: [OffIns] -> [OffIns]
138 markBackwardTargets [] = []
139 markBackwardTargets (x:[]) = [x]
140 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
141 x_new:markBackwardTargets (y:xs)
143 x_new = if isTarget then checkX y_off else x
144 checkX w16 = case x_bbend of
145 Just _ -> x -- already marked, don't change
146 Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
148 -- look through all remaining insns in the stream if there is a jmp to `y'
149 isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
150 cmpOffset ((_,Just (OneTarget w16)),_) = w16 == y_off
151 cmpOffset ((_,Just (TwoTarget _ w16)),_) = w16 == y_off
155 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
156 buildCFG' hmap [] _ = hmap
157 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
159 insertlist :: [BlockID] -> MapBB -> MapBB
160 insertlist [] hmap' = hmap'
161 insertlist (y:ys) hmap' = insertlist ys newhmap
163 newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
164 value = parseBasicBlock y insns
166 entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
169 Just (TwoTarget t1 t2) -> [t1, t2]
170 Just (OneTarget t) -> [t]
171 Just (FallThrough t) -> [t]
176 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
177 parseBasicBlock i insns = BasicBlock insonly endblock
179 startlist = dropWhile (\((x,_),_) -> x < i) insns
180 (Just ((_, Just endblock),_), is) = takeWhilePlusOne validins startlist
181 insonly = snd $ unzip is
183 -- also take last (non-matched) element and return it
184 takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
185 takeWhilePlusOne _ [] = (Nothing,[])
186 takeWhilePlusOne p (x:xs)
187 | p x = let (lastins, list) = takeWhilePlusOne p xs in (lastins, x:list)
188 | otherwise = (Just x,[x])
190 validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
191 validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
194 calculateInstructionOffset :: [Instruction] -> [OffIns]
195 calculateInstructionOffset = cio' (0, Nothing)
197 newoffset :: Instruction -> Int -> Offset
198 newoffset x off = (off + fromIntegral (B.length $ encodeInstructions [x]), Nothing)
200 addW16Signed :: Int -> Word16 -> Int
201 addW16Signed i w16 = i + fromIntegral s16
202 where s16 = fromIntegral w16 :: Int16
204 cio' :: Offset -> [Instruction] -> [OffIns]
206 -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
207 cio' (off,_) (x:xs) = case x of
208 IF _ w16 -> twotargets w16
209 IF_ICMP _ w16 -> twotargets w16
210 IF_ACMP _ w16 -> twotargets w16
211 IFNONNULL w16 -> twotargets w16
212 IFNULL w16 -> twotargets w16
213 GOTO w16 -> onetarget w16
217 _ -> ((off, Nothing), x):next
219 notarget = ((off, Just Return), x):next
220 onetarget w16 = ((off, Just $ OneTarget (off `addW16Signed` w16)), x):next
221 twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
222 next = cio' (newoffset x off) xs