debug: use #ifdef guards
[mate.git] / Mate / BasicBlocks.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE OverloadedStrings #-}
3 module Mate.BasicBlocks(
4   BlockID,
5   BasicBlock (..),
6   BBEnd (..),
7   MapBB,
8 #ifdef DEBUG
9   printMapBB,
10   test_main,
11 #endif
12   parseMethod,
13   testCFG -- added by hs to perform benches from outside
14   )where
15
16 import Data.Binary
17 import Data.Int
18 import Data.List
19 import qualified Data.Map as M
20 import qualified Data.ByteString.Lazy as B
21
22 import JVM.ClassFile
23 import JVM.Converter
24 import JVM.Assembler
25
26 import Mate.Utilities
27 import Mate.Types
28
29
30 -- for immediate representation to determine BBs
31 type Offset = (Int, Maybe BBEnd) -- (offset in bytecode, offset to jump target)
32 type OffIns = (Offset, Instruction)
33
34
35 #ifdef DEBUG
36 printMapBB :: Maybe MapBB -> IO ()
37 printMapBB Nothing = putStrLn "No BasicBlock"
38 printMapBB (Just hmap) = do
39                      putStr "BlockIDs: "
40                      let keys = fst $ unzip $ M.toList hmap
41                      mapM_ (putStr . (flip (++)) ", " . show) keys
42                      putStrLn "\n\nBasicBlocks:"
43                      printMapBB' keys hmap
44   where
45   printMapBB' :: [BlockID] -> MapBB -> IO ()
46   printMapBB' [] _ = return ()
47   printMapBB' (i:is) hmap' = case M.lookup i hmap' of
48                   Just bb -> do
49                              putStrLn $ "Block " ++ (show i)
50                              mapM_ putStrLn (map ((++) "\t" . show) $ code bb)
51                              case successor bb of
52                                Return -> putStrLn ""
53                                FallThrough t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
54                                OneTarget t1 -> putStrLn $ "Sucessor: " ++ (show t1) ++ "\n"
55                                TwoTarget t1 t2 -> putStrLn $ "Sucessor: " ++ (show t1) ++ ", " ++ (show t2) ++ "\n"
56                              printMapBB' is hmap
57                   Nothing -> error $ "BlockID " ++ show i ++ " not found."
58 #endif
59
60 #ifdef DEBUG
61 testInstance :: String -> B.ByteString -> IO ()
62 testInstance cf method = do
63                       cls <- parseClassFile cf
64                       hmap <- parseMethod cls method
65                       printMapBB hmap
66 #endif
67
68 #ifdef DEBUG
69 test_main :: IO ()
70 test_main = do
71   test_01
72   test_02
73   test_03
74   test_04
75
76 test_01, test_02, test_03, test_04 :: IO ()
77 test_01 = testInstance "./tests/Fib.class" "fib"
78 test_02 = testInstance "./tests/While.class" "f"
79 test_03 = testInstance "./tests/While.class" "g"
80 test_04 = testInstance "./tests/Fac.class" "fac"
81 #endif
82
83
84 parseMethod :: Class Resolved -> B.ByteString -> IO (Maybe MapBB)
85 parseMethod cls method = do
86                      let maybe_bb = testCFG $ lookupMethod method cls
87 #ifdef DEBUG
88                      putStr "BB: analysing: "
89                      let msig = methodSignature $ (classMethods cls) !! 1
90                      putStrLn $ toString (method `B.append` ": " `B.append` (encode msig))
91                      printMapBB maybe_bb
92 #endif
93                      return maybe_bb
94
95
96 testCFG :: Maybe (Method Resolved) -> Maybe MapBB
97 testCFG (Just m) = case attrByName m "Code" of
98        Nothing -> Nothing
99        Just bytecode -> Just $ buildCFG $ codeInstructions $ decodeMethod bytecode
100 testCFG _ = Nothing
101
102
103 buildCFG :: [Instruction] -> MapBB
104 buildCFG xs = buildCFG' M.empty xs' xs'
105   where
106   xs' :: [OffIns]
107   xs' = markBackwardTargets $ calculateInstructionOffset xs
108
109 -- get already calculated jmp-targets and mark the predecessor of the
110 -- target-instruction as "FallThrough". we just care about backwards
111 -- jumps here (forward jumps are handled in buildCFG')
112 markBackwardTargets :: [OffIns] -> [OffIns]
113 markBackwardTargets [] = []
114 markBackwardTargets (x:[]) = [x]
115 markBackwardTargets insns@(x@((x_off,x_bbend),x_ins):y@((y_off,_),_):xs) =
116   (x_new):(markBackwardTargets (y:xs))
117   where
118   x_new = if isTarget then checkX y_off else x
119   checkX w16 = case x_bbend of
120     Just _ -> x -- already marked, don't change
121     Nothing -> ((x_off, Just $ FallThrough w16), x_ins) -- mark previous insn
122
123   -- look through all remaining insns in the stream if there is a jmp to `y'
124   isTarget = case find cmpOffset insns of Just _ -> True; Nothing -> False
125   cmpOffset ((_,(Just (OneTarget w16))),_) = w16 == y_off
126   cmpOffset ((_,(Just (TwoTarget _ w16))),_) = w16 == y_off
127   cmpOffset _ = False
128
129
130 buildCFG' :: MapBB -> [OffIns] -> [OffIns] -> MapBB
131 buildCFG' hmap [] _ = hmap
132 buildCFG' hmap (((off, entry), _):xs) insns = buildCFG' (insertlist entryi hmap) xs insns
133   where
134   insertlist :: [BlockID] -> MapBB -> MapBB
135   insertlist [] hmap' = hmap'
136   insertlist (y:ys) hmap' = insertlist ys newhmap
137     where
138     newhmap = if M.member y hmap' then hmap' else M.insert y value hmap'
139     value = parseBasicBlock y insns
140
141   entryi :: [BlockID]
142   entryi = (if off == 0 then [0] else []) ++ -- also consider the entrypoint
143         case entry of
144         Just (TwoTarget t1 t2) -> [t1, t2]
145         Just (OneTarget t) -> [t]
146         Just (FallThrough t) -> [t]
147         Just (Return) -> []
148         Nothing -> []
149
150
151 parseBasicBlock :: Int -> [OffIns] -> BasicBlock
152 parseBasicBlock i insns = BasicBlock insonly endblock
153   where
154   startlist = dropWhile (\((x,_),_) -> x < i) insns
155   (Just ((_,(Just endblock)),_), is) = takeWhilePlusOne validins startlist
156   insonly = snd $ unzip is
157
158   -- also take last (non-matched) element and return it
159   takeWhilePlusOne :: (a -> Bool) -> [a] -> (Maybe a,[a])
160   takeWhilePlusOne _ [] = (Nothing,[])
161   takeWhilePlusOne p (x:xs)
162     | p x       =  let (lastins, list) = takeWhilePlusOne p xs in (lastins, (x:list))
163     | otherwise =  (Just x,[x])
164
165   validins :: ((Int, Maybe BBEnd), Instruction) -> Bool
166   validins ((_,x),_) = case x of Just _ -> False; Nothing -> True
167
168
169 calculateInstructionOffset :: [Instruction] -> [OffIns]
170 calculateInstructionOffset = cio' (0, Nothing)
171   where
172   newoffset :: Instruction -> Int -> Offset
173   newoffset x off = (off + (fromIntegral $ B.length $ encodeInstructions [x]), Nothing)
174
175   addW16Signed :: Int -> Word16 -> Int
176   addW16Signed i w16 = i + (fromIntegral s16)
177     where s16 = (fromIntegral w16) :: Int16
178
179   cio' :: Offset -> [Instruction] -> [OffIns]
180   cio' _ [] = []
181   -- TODO(bernhard): add more instruction with offset (IF_ACMP, JSR, ...)
182   cio' (off,_) (x:xs) = case x of
183       IF _ w16 -> twotargets w16
184       IF_ICMP _ w16 -> twotargets w16
185       IF_ACMP _ w16 -> twotargets w16
186       GOTO w16 -> onetarget w16
187       IRETURN -> notarget
188       ARETURN -> notarget
189       RETURN -> notarget
190       _ -> ((off, Nothing), x):next
191     where
192     notarget = ((off, Just Return), x):next
193     onetarget w16 = ((off, Just $ OneTarget $ (off `addW16Signed` w16)), x):next
194     twotargets w16 = ((off, Just $ TwoTarget (off + 3) (off `addW16Signed` w16)), x):next
195     next = cio' (newoffset x off) xs