on fa9f021 help sign in
Idris-dev/src/IRTS/Compiler.hs
415 lines 17 kB history raw
1{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-}
3module IRTS.Compiler where
5import IRTS.Lang
6import IRTS.Defunctionalise
7import IRTS.Simplified
8import IRTS.CodegenCommon
9import IRTS.CodegenC
10import IRTS.CodegenJava
11import IRTS.DumpBC
12import IRTS.CodegenJavaScript
13#ifdef IDRIS_LLVM
14import IRTS.CodegenLLVM
15#else
16import Util.LLVMStubs
17#endif
18import IRTS.Inliner
20import Idris.AbsSyntax
21import Idris.UnusedArgs
22import Idris.Error
24import Idris.Core.TT
25import Idris.Core.Evaluate
26import Idris.Core.CaseTree
28import Control.Monad.State
29import Data.List
30import System.Process
31import System.IO
32import System.Directory
33import System.Environment
34import System.FilePath ((</>), addTrailingPathSeparator)
36import Paths_idris
38compile :: Codegen -> FilePath -> Term -> Idris ()
39compile codegen f tm
40 = do checkMVs
41 let tmnames = namesUsed (STerm tm)
42 usedIn <- mapM (allNames []) tmnames
43 let used = [sUN "prim__subBigInt", sUN "prim__addBigInt"] : usedIn
44 defsIn <- mkDecls tm (concat used)
45 findUnusedArgs (concat used)
46 maindef <- irMain tm
47 objs <- getObjectFiles codegen
48 libs <- getLibs codegen
49 flags <- getFlags codegen
50 hdrs <- getHdrs codegen
51 impdirs <- allImportDirs
52 let defs = defsIn ++ [(sMN 0 "runMain", maindef)]
53 -- iputStrLn $ showSep "\n" (map show defs)
54 let (nexttag, tagged) = addTags 65536 (liftAll defs)
55 let ctxtIn = addAlist tagged emptyContext
56 iLOG "Defunctionalising"
57 let defuns_in = defunctionalise nexttag ctxtIn
58 logLvl 5 $ show defuns_in
59 iLOG "Inlining"
60 let defuns = inline defuns_in
61 logLvl 5 $ show defuns
62 iLOG "Resolving variables for CG"
63 -- iputStrLn $ showSep "\n" (map show (toAlist defuns))
64 let checked = checkDefs defuns (toAlist defuns)
65 outty <- outputTy
66 dumpCases <- getDumpCases
67 dumpDefun <- getDumpDefun
68 case dumpCases of
69 Nothing -> return ()
70 Just f -> runIO $ writeFile f (showCaseTrees defs)
71 case dumpDefun of
72 Nothing -> return ()
73 Just f -> runIO $ writeFile f (dumpDefuns defuns)
74 triple <- targetTriple
75 cpu <- targetCPU
76 optimize <- optLevel
77 iLOG "Building output"
78 case checked of
79 OK c -> runIO $ case codegen of
80 ViaC ->
81 codegenC c f outty hdrs
82 (concatMap mkObj objs)
83 (concatMap mkLib libs)
84 (concatMap mkFlag flags ++
85 concatMap incdir impdirs) NONE
86 ViaJava ->
87 codegenJava [] c f hdrs libs outty
88 ViaJavaScript ->
89 codegenJavaScript JavaScript c f outty
90 ViaNode ->
91 codegenJavaScript Node c f outty
92 ViaLLVM -> codegenLLVM c triple cpu optimize f outty
93 Bytecode -> dumpBC c f
94 Error e -> ierror e
95 where checkMVs = do i <- getIState
96 case map fst (idris_metavars i) \\ primDefs of
97 [] -> return ()
98 ms -> ifail $ "There are undefined metavariables: " ++ show ms
99 inDir d h = do let f = d </> h
100 ex <- doesFileExist f
101 if ex then return f else return h
102 mkObj f = f ++ " "
103 mkLib l = "-l" ++ l ++ " "
104 mkFlag l = l ++ " "
106 incdir i = "-I" ++ i ++ " "
109irMain :: TT Name -> Idris LDecl
110irMain tm = do i <- ir tm
111 return $ LFun [] (sMN 0 "runMain") [] (LForce i)
113mkDecls :: Term -> [Name] -> Idris [(Name, LDecl)]
114mkDecls t used
115 = do i <- getIState
116 let ds = filter (\ (n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
117 mapM traceUnused used
118 decls <- mapM build ds
119 return decls
121showCaseTrees :: [(Name, LDecl)] -> String
122showCaseTrees ds = showSep "\n\n" (map showCT ds)
123 where
124 showCT (n, LFun _ f args lexp)
125 = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t "
126 ++ show lexp
127 showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
129isCon (TyDecl _ _) = True
130isCon _ = False
132class ToIR a where
133 ir :: a -> Idris LExp
135build :: (Name, Def) -> Idris (Name, LDecl)
136build (n, d)
137 = do i <- getIState
138 case lookup n (idris_scprims i) of
139 Just (ar, op) ->
140 let args = map (\x -> sMN x "op") [0..] in
141 return (n, (LFun [] n (take ar args)
142 (LOp op (map (LV . Glob) (take ar args)))))
143 _ -> do def <- mkLDecl n d
144 logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
145 return (n, def)
147getPrim :: IState -> Name -> [LExp] -> Maybe LExp
148getPrim i n args = case lookup n (idris_scprims i) of
149 Just (ar, op) ->
150 if (ar == length args)
151 then return (LOp op args)
152 else Nothing
153 _ -> Nothing
155declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
156declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
158mkLDecl n (Function tm _) = do e <- ir tm
159 return (declArgs [] True n e)
160mkLDecl n (CaseOp ci _ _ _ pats cd)
161 = let (args, sc) = cases_runtime cd in
162 do e <- ir (args, sc)
163 return (declArgs [] (case_inlinable ci) n e)
164mkLDecl n (TyDecl (DCon t a) _) = return $ LConstructor n t a
165mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
166mkLDecl n _ = return (LFun [] n [] (LError ("Impossible declaration " ++ show n)))
168instance ToIR (TT Name) where
169 ir tm = ir' [] tm where
170 ir' env tm@(App f a)
171 | (P _ (UN m) _, args) <- unApply tm,
172 m == txt "mkForeignPrim"
173 = doForeign env args
174 | (P _ (UN u) _, [_, arg]) <- unApply tm,
175 u == txt "unsafePerformPrimIO"
176 = ir' env arg
177 -- TMP HACK - until we get inlining.
178 | (P _ (UN r) _, [_, _, _, _, _, arg]) <- unApply tm,
179 r == txt "replace"
180 = ir' env arg
181 | (P _ (UN l) _, [_, arg]) <- unApply tm,
182 l == txt "lazy"
183 = do arg' <- ir' env arg
184 return $ LLazyExp arg'
185 | (P _ (UN a) _, [_, _, arg]) <- unApply tm,
186 a == txt "assert_smaller"
187 = ir' env arg
188 | (P _ (UN a) _, [_, arg]) <- unApply tm,
189 a == txt "assert_total"
190 = ir' env arg
191 | (P _ (UN p) _, [_, arg]) <- unApply tm,
192 p == txt "par"
193 = do arg' <- ir' env arg
194 return $ LOp LPar [LLazyExp arg']
195 | (P _ (UN pf) _, [arg]) <- unApply tm,
196 pf == txt "prim_fork"
197 = do arg' <- ir' env arg
198 return $ LOp LFork [LLazyExp arg']
199 | (P _ (UN m) _, [_,size,t]) <- unApply tm,
200 m == txt "malloc"
201 = do size' <- ir' env size
202 t' <- ir' env t
203 return t' -- TODO $ malloc_ size' t'
204 | (P _ (UN tm) _, [_,t]) <- unApply tm,
205 tm == txt "trace_malloc"
206 = do t' <- ir' env t
207 return t' -- TODO
208-- | (P _ (NS (UN "S") ["Nat", "Prelude"]) _, [k]) <- unApply tm
209-- = do k' <- ir' env k
210-- return (LOp LBPlus [k', LConst (BI 1)])
211 | (P (DCon t a) n _, args) <- unApply tm
212 = irCon env t a n args
213 | (P (TCon t a) n _, args) <- unApply tm
214 = return LNothing
215 | (P _ n _, args) <- unApply tm
216 = do i <- getIState
217 args' <- mapM (ir' env) args
218 case getPrim i n args' of
219 Just tm -> return tm
220 _ -> do
221 let collapse
222 = case lookupCtxtExact n
223 (idris_optimisation i) of
224 Just oi -> collapsible oi
225 _ -> False
226 let unused
227 = case lookupCtxtExact n
228 (idris_callgraph i) of
229 Just (CGInfo _ _ _ _ unusedpos) ->
230 unusedpos
231 _ -> []
232 if collapse
233 then return LNothing
234 else return (LApp False (LV (Glob n))
235 (mkUnused unused 0 args'))
236 | (f, args) <- unApply tm
237 = do f' <- ir' env f
238 args' <- mapM (ir' env) args
239 return (LApp False f' args')
240 where mkUnused u i [] = []
241 mkUnused u i (x : xs) | i `elem` u = LNothing : mkUnused u (i + 1) xs
242 | otherwise = x : mkUnused u (i + 1) xs
243-- ir' env (P _ (NS (UN "Z") ["Nat", "Prelude"]) _)
244-- = return $ LConst (BI 0)
245 ir' env (P _ n _) = return $ LV (Glob n)
246 ir' env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i))
247 | otherwise = ifail $ "IR fail " ++ show i ++ " " ++ show tm
248 ir' env (Bind n (Lam _) sc)
249 = do let n' = uniqueName n env
250 sc' <- ir' (n' : env) sc
251 return $ LLam [n'] sc'
252 ir' env (Bind n (Let _ v) sc)
253 = do sc' <- ir' (n : env) sc
254 v' <- ir' env v
255 return $ LLet n v' sc'
256 ir' env (Bind _ _ _) = return $ LNothing
257 ir' env (Proj t i) | i == -1
258 = do t' <- ir' env t
259 return $ LOp (LMinus (ATInt ITBig))
260 [t', LConst (BI 1)]
261 ir' env (Proj t i) = do t' <- ir' env t
262 return $ LProj t' i
263 ir' env (Constant c) = return $ LConst c
264 ir' env (TType _) = return $ LNothing
265 ir' env Erased = return $ LNothing
266 ir' env Impossible = return $ LNothing
267-- ir' env _ = return $ LError "Impossible"
269 irCon env t arity n args
270 | length args == arity = buildApp env (LV (Glob n)) args
271 | otherwise = let extra = satArgs (arity - length args) in
272 do sc' <- irCon env t arity n
273 (args ++ map (\n -> P Bound n undefined) extra)
274 return $ LLam extra sc'
276 satArgs n = map (\i -> sMN i "sat") [1..n]
278 buildApp env e [] = return e
279 buildApp env e xs = do xs' <- mapM (ir' env) xs
280 return $ LApp False e xs'
282 doForeign :: [Name] -> [TT Name] -> Idris LExp
283 doForeign env (_ : fgn : args)
284 | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
285 = let maybeTys = getFTypes fgnArgTys
286 rty = mkIty' ret in
287 case maybeTys of
288 Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
289 Just tys -> do
290 args' <- mapM (ir' env) (init args)
291 -- wrap it in a prim__IO
292 -- return $ con_ 0 @@ impossible @@
293 return $ -- LLazyExp $
294 LForeign LANG_C rty fgnName (zip tys args')
295 | otherwise = ifail "Badly formed foreign function call"
297getFTypes :: TT Name -> Maybe [FType]
298getFTypes tm = case unApply tm of
299 (nil, []) -> Just []
300 (cons, [ty, xs]) ->
301 fmap (mkIty' ty :) (getFTypes xs)
302 _ -> Nothing
304mkIty' (P _ (UN ty) _) = mkIty (str ty)
305mkIty' (App (P _ (UN fi) _) (P _ (UN intTy) _))
306 | fi == txt "FIntT" = mkIntIty (str intTy)
307mkIty' (App (App (P _ (UN ff) _) _) (App (P _ (UN fa) _) (App (P _ (UN io) _) _)))
308 | ff == txt "FFunction" && fa == txt "FAny" &&
309 io == txt "IO"
310 = FFunctionIO
311mkIty' (App (App (P _ (UN ff) _) _) _)
312 | ff == txt "FFunction" = FFunction
313mkIty' _ = FAny
315-- would be better if these FInt types were evaluated at compile time
316-- TODO: add %eval directive for such things
318mkIty "FFloat" = FArith ATFloat
319mkIty "FInt" = mkIntIty "ITNative"
320mkIty "FChar" = mkIntIty "ITChar"
321mkIty "FByte" = mkIntIty "IT8"
322mkIty "FShort" = mkIntIty "IT16"
323mkIty "FLong" = mkIntIty "IT64"
324mkIty "FBits8" = mkIntIty "IT8"
325mkIty "FBits16" = mkIntIty "IT16"
326mkIty "FBits32" = mkIntIty "IT32"
327mkIty "FBits64" = mkIntIty "IT64"
328mkIty "FString" = FString
329mkIty "FPtr" = FPtr
330mkIty "FUnit" = FUnit
331mkIty "FFunction" = FFunction
332mkIty "FFunctionIO" = FFunctionIO
333mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16))
334mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8))
335mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4))
336mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2))
337mkIty x = error $ "Unknown type " ++ x
339mkIntIty "ITNative" = FArith (ATInt ITNative)
340mkIntIty "ITChar" = FArith (ATInt ITChar)
341mkIntIty "IT8" = FArith (ATInt (ITFixed IT8))
342mkIntIty "IT16" = FArith (ATInt (ITFixed IT16))
343mkIntIty "IT32" = FArith (ATInt (ITFixed IT32))
344mkIntIty "IT64" = FArith (ATInt (ITFixed IT64))
346zname = sNS (sUN "Z") ["Nat","Prelude"]
347sname = sNS (sUN "S") ["Nat","Prelude"]
349instance ToIR ([Name], SC) where
350 ir (args, tree) = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
351 tree' <- ir tree
352 return $ LLam args tree'
354instance ToIR SC where
355 ir t = ir' t where
357 ir' (STerm t) = ir t
358 ir' (UnmatchedCase str) = return $ LError str
359 ir' (ProjCase tm alts) = do tm' <- ir tm
360 alts' <- mapM (mkIRAlt tm') alts
361 return $ LCase tm' alts'
362 ir' (Case n alts) = do alts' <- mapM (mkIRAlt (LV (Glob n))) alts
363 return $ LCase (LV (Glob n)) alts'
364 ir' ImpossibleCase = return LNothing
366 -- special cases for Z and S
367 -- Needs rethink: projections make this fail
368-- mkIRAlt n (ConCase z _ [] rhs) | z == zname
369-- = mkIRAlt n (ConstCase (BI 0) rhs)
370-- mkIRAlt n (ConCase s _ [arg] rhs) | s == sname
371-- = do n' <- ir n
372-- rhs' <- ir rhs
373-- return $ LDefaultCase
374-- (LLet arg (LOp LBMinus [n', LConst (BI 1)])
375-- rhs')
376 mkIRAlt _ (ConCase n t args rhs)
377 = do rhs' <- ir rhs
378 return $ LConCase (-1) n args rhs'
379 mkIRAlt _ (ConstCase x rhs)
380 | matchable x
381 = do rhs' <- ir rhs
382 return $ LConstCase x rhs'
383 | matchableTy x
384 = do rhs' <- ir rhs
385 return $ LDefaultCase rhs'
386 mkIRAlt tm (SucCase n rhs)
387 = do rhs' <- ir rhs
388 return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
389 [tm,
390 LConst (BI 1)]) rhs')
391-- return $ LSucCase n rhs'
392 mkIRAlt _ (ConstCase c rhs)
393 = ifail $ "Can't match on (" ++ show c ++ ")"
394 mkIRAlt _ (DefaultCase rhs)
395 = do rhs' <- ir rhs
396 return $ LDefaultCase rhs'
398 matchable (I _) = True
399 matchable (BI _) = True
400 matchable (Ch _) = True
401 matchable (Str _) = True
402 matchable _ = False
404 matchableTy (AType (ATInt ITNative)) = True
405 matchableTy (AType (ATInt ITBig)) = True
406 matchableTy (AType (ATInt ITChar)) = True
407 matchableTy StrType = True
409 matchableTy (AType (ATInt (ITFixed IT8))) = True
410 matchableTy (AType (ATInt (ITFixed IT16))) = True
411 matchableTy (AType (ATInt (ITFixed IT32))) = True
412 matchableTy (AType (ATInt (ITFixed IT64))) = True
414 matchableTy _ = False