1 {-# LANGUAGE OverloadedStrings #-}
2 module Mate.BasicBlocks(
10 testCFG -- added by hs to perform benches from outside
13 import Data.Binary hiding (get)
15 import qualified Data.Map as M
16 import qualified Data.ByteString.Lazy as B
18 import Control.Monad.State
19 import Control.Applicative
30 -- (offset in bytecode, offset to jump target, ins)
31 type OffIns = (Int, Maybe BBEnd, Instruction)
33 type Targets = [BlockID]
34 type BBState = Targets
35 type AnalyseState = State BBState [OffIns]
38 printMapBB :: MapBB -> IO ()
41 let keys = M.keys hmap
42 mapM_ (printfBb . flip (++) ", " . show) keys
43 printfBb "\n\nBasicBlocks:\n"
46 printMapBB' :: [BlockID] -> MapBB -> IO ()
47 printMapBB' [] _ = return ()
48 printMapBB' (i:is) hmap' = case M.lookup i hmap' of
50 printfBb $ "Block " ++ show i ++ "\n"
51 mapM_ (printfBb . flip (++) "\n" . (++) "\t" . show) $ code bb
52 printfBb $ case successor bb of
54 FallThrough t1 -> "Sucessor: " ++ show t1 ++ "\n"
55 OneTarget t1 -> "Sucessor: " ++ show t1 ++ "\n"
56 TwoTarget t1 t2 -> "Sucessor: " ++ show t1 ++ ", " ++ show t2 ++ "\n"
58 Nothing -> error $ "BlockID " ++ show i ++ " not found."
61 testInstance :: String -> B.ByteString -> MethodSignature -> IO ()
62 testInstance cf method sig = do
63 cls <- parseClassFile cf
64 hmap <- parseMethod cls method sig
74 test_01, test_02, test_03, test_04 :: IO ()
75 test_01 = testInstance "./tests/Fib.class" "fib"
76 test_02 = testInstance "./tests/While.class" "f"
77 test_03 = testInstance "./tests/While.class" "g"
78 test_04 = testInstance "./tests/Fac.class" "fac"
82 parseMethod :: Class Direct -> B.ByteString -> MethodSignature -> IO RawMethod
83 parseMethod cls methodname sig = do
84 let method = fromMaybe
85 (error $ "method " ++ (show . toString) methodname ++ " not found")
86 (lookupMethodSig methodname sig cls)
87 let codeseg = fromMaybe
88 (error $ "codeseg " ++ (show . toString) methodname ++ " not found")
89 (attrByName method "Code")
90 let decoded = decodeMethod codeseg
91 let mapbb = testCFG decoded
92 let locals = fromIntegral (codeMaxLocals decoded)
93 let stacks = fromIntegral (codeStackSize decoded)
94 let codelen = fromIntegral (codeLength decoded)
95 let methoddirect = methodInfoToMethod (MethodInfo methodname "" sig) cls
96 let isStatic = methodIsStatic methoddirect
97 let nametype = methodNameType methoddirect
98 let argscount = methodGetArgsCount nametype + (if isStatic then 0 else 1)
100 let msig = methodSignature method
101 printfBb $ printf "BB: analysing \"%s\"\n" $ toString (methodname `B.append` ": " `B.append` encode msig)
103 -- small example how to get information about
104 -- exceptions of a method
106 let (Just m) = lookupMethodSig methodname sig cls
107 case attrByName m "Code" of
109 printfBb $ printf "exception: no handler for this method\n"
110 Just exceptionstream ->
111 printfBb $ printf "exception: \"%s\"\n" (show $ codeExceptions $ decodeMethod exceptionstream)
112 return $ RawMethod mapbb locals stacks argscount codelen
115 testCFG :: Code -> MapBB
116 testCFG = buildCFG . codeInstructions
118 buildCFG :: [Instruction] -> MapBB
119 buildCFG xs = buildCFG' M.empty xs' xs'
122 xs' = evalState (calculateInstructionOffset xs) []
125 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
126 buildCFG' hmap [] _ = hmap
127 buildCFG' hmap ((off, entry, _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
129 insertlist :: [BlockID] -> MapBB -> MapBB
130 insertlist [] hmap' = hmap'
131 insertlist (y:ys) hmap' = insertlist ys newhmap
133 newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
134 value = parseBasicBlock y insns
136 entryi = if off == 0 then 0:ys else ys -- also consider the entrypoint
139 Just (TwoTarget t1 t2) -> [t1, t2]
140 Just (OneTarget t) -> [t]
141 Just (FallThrough t) -> [t]
146 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
147 parseBasicBlock i insns = BasicBlock insonly endblock
149 (lastblock, is) = takeWhilePlusOne validins omitins insns
150 (_, _, insonly) = unzip3 is
151 (_, Just endblock, _) = fromJust lastblock
153 -- also take last (non-matched) element and return it
154 takeWhilePlusOne :: (a -> Bool) -> (a -> Bool) -> [a] -> (Maybe a, [a])
155 takeWhilePlusOne _ _ [] = (Nothing, [])
156 takeWhilePlusOne p omit (x:xs)
158 | p x = second (x:) next
159 | otherwise = (Just x, [x])
161 next = takeWhilePlusOne p omit xs
163 validins :: OffIns -> Bool
164 validins (_, x, _) = isNothing x
166 omitins :: OffIns -> Bool
167 omitins (off, _, _) = off < i
170 calculateInstructionOffset :: [Instruction] -> AnalyseState
171 calculateInstructionOffset = cio' (0, Nothing, NOP)
173 addW16Signed :: Int -> Word16 -> Int
174 addW16Signed i w16 = i + fromIntegral s16
175 where s16 = fromIntegral w16 :: Int16
177 cio' :: OffIns -> [Instruction] -> AnalyseState
178 cio' _ [] = return $ []
179 cio' (off,_,_) (x:xs) = case x of
180 IF _ w16 -> twotargets w16
181 IF_ICMP _ w16 -> twotargets w16
182 IF_ACMP _ w16 -> twotargets w16
183 IFNONNULL w16 -> twotargets w16
184 IFNULL w16 -> twotargets w16
185 GOTO w16 -> onetarget w16
192 tailinsns <- next -- eval remaining instructions
193 isNextInsATarget <- (elem newoffset) <$> get
194 let bbtyp = if isNextInsATarget
195 then Just $ FallThrough newoffset
197 return $ (off, bbtyp, x):tailinsns
198 notarget = ((off, Just Return, x):) <$> next
200 let jump = off `addW16Signed` w16
202 ((off, Just $ OneTarget jump, x):) <$> next
206 let jump = off `addW16Signed` w16
208 ((off, Just $ TwoTarget nojump jump, x):) <$> next
209 next = cio' nextins xs
210 nextins = (newoffset, Nothing, NOP)
211 newoffset = off + insnLength x
213 -- TODO(bernhard): does GHC memomize results? i.e. does it calculate the size
214 -- of `NOP' only once?
215 insnLength :: Num a => Instruction -> a
216 insnLength = fromIntegral . B.length . encodeInstructions . (:[])