9faa0edf73d1eb5c42749f7ab09318282d65e8d3
[ghc-hetmet.git] / compiler / vectorise / VectUtils.hs
1 module VectUtils (
2   collectAnnTypeBinders, collectAnnTypeArgs, isAnnTypeArg,
3   collectAnnValBinders,
4   dataConTagZ, mkDataConTag, mkDataConTagLit,
5
6   newLocalVVar,
7
8   mkBuiltinCo, voidType, mkWrapType,
9   mkPADictType, mkPArrayType, mkPDataType, mkPReprType, mkPArray,
10
11   pdataReprTyCon, pdataReprDataCon, mkVScrut,
12   prDictOfType, prDFunOfTyCon,
13   paDictArgType, paDictOfType, paDFunType,
14   paMethod, wrapPR, replicatePD, emptyPD, packPD, packByTagPD,
15   combinePD,
16   liftPD,
17   zipScalars, scalarClosure,
18   polyAbstract, polyApply, polyVApply, polyArity,
19   Inline(..), addInlineArity, inlineMe,
20   hoistBinding, hoistExpr, hoistPolyVExpr, takeHoisted,
21   buildClosure, buildClosures,
22   mkClosureApp
23 ) where
24
25 import VectCore
26 import VectMonad
27
28 import MkCore ( mkCoreTup, mkCoreTupTy, mkWildCase )
29 import CoreSyn
30 import CoreUtils
31 import CoreUnfold         ( mkInlineRule )
32 import Coercion
33 import Type
34 import TypeRep
35 import TyCon
36 import DataCon
37 import Var
38 import MkId               ( unwrapFamInstScrut )
39 import Id                 ( setIdUnfolding )
40 import TysWiredIn
41 import BasicTypes         ( Boxity(..) )
42 import Literal            ( Literal, mkMachInt )
43
44 import Outputable
45 import FastString
46
47 import Control.Monad
48
49 collectAnnTypeArgs :: AnnExpr b ann -> (AnnExpr b ann, [Type])
50 collectAnnTypeArgs expr = go expr []
51   where
52     go (_, AnnApp f (_, AnnType ty)) tys = go f (ty : tys)
53     go e                             tys = (e, tys)
54
55 collectAnnTypeBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
56 collectAnnTypeBinders expr = go [] expr
57   where
58     go bs (_, AnnLam b e) | isTyVar b = go (b:bs) e
59     go bs e                           = (reverse bs, e)
60
61 collectAnnValBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
62 collectAnnValBinders expr = go [] expr
63   where
64     go bs (_, AnnLam b e) | isId b = go (b:bs) e
65     go bs e                        = (reverse bs, e)
66
67 isAnnTypeArg :: AnnExpr b ann -> Bool
68 isAnnTypeArg (_, AnnType _) = True
69 isAnnTypeArg _              = False
70
71 dataConTagZ :: DataCon -> Int
72 dataConTagZ con = dataConTag con - fIRST_TAG
73
74 mkDataConTagLit :: DataCon -> Literal
75 mkDataConTagLit = mkMachInt . toInteger . dataConTagZ
76
77 mkDataConTag :: DataCon -> CoreExpr
78 mkDataConTag = mkIntLitInt . dataConTagZ
79
80 splitPrimTyCon :: Type -> Maybe TyCon
81 splitPrimTyCon ty
82   | Just (tycon, []) <- splitTyConApp_maybe ty
83   , isPrimTyCon tycon
84   = Just tycon
85
86   | otherwise = Nothing
87
88 mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type
89 mkBuiltinTyConApp get_tc tys
90   = do
91       tc <- builtin get_tc
92       return $ mkTyConApp tc tys
93
94 mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type
95 mkBuiltinTyConApps get_tc tys ty
96   = do
97       tc <- builtin get_tc
98       return $ foldr (mk tc) ty tys
99   where
100     mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
101
102 voidType :: VM Type
103 voidType = mkBuiltinTyConApp VectMonad.voidTyCon []
104
105 mkWrapType :: Type -> VM Type
106 mkWrapType ty = mkBuiltinTyConApp wrapTyCon [ty]
107
108 mkClosureTypes :: [Type] -> Type -> VM Type
109 mkClosureTypes = mkBuiltinTyConApps closureTyCon
110
111 mkPReprType :: Type -> VM Type
112 mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]
113
114 mkPADictType :: Type -> VM Type
115 mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
116
117 mkPArrayType :: Type -> VM Type
118 mkPArrayType ty
119   | Just tycon <- splitPrimTyCon ty
120   = do
121       r <- lookupPrimPArray tycon
122       case r of
123         Just arr -> return $ mkTyConApp arr []
124         Nothing  -> cantVectorise "Primitive tycon not vectorised" (ppr tycon)
125 mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
126
127 mkPDataType :: Type -> VM Type
128 mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty]
129
130 mkPArray :: Type -> CoreExpr -> CoreExpr -> VM CoreExpr
131 mkPArray ty len dat = do
132                         tc <- builtin parrayTyCon
133                         let [dc] = tyConDataCons tc
134                         return $ mkConApp dc [Type ty, len, dat]
135
136 mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
137 mkBuiltinCo get_tc
138   = do
139       tc <- builtin get_tc
140       return $ mkTyConApp tc []
141
142 pdataReprTyCon :: Type -> VM (TyCon, [Type])
143 pdataReprTyCon ty = builtin pdataTyCon >>= (`lookupFamInst` [ty])
144
145 pdataReprDataCon :: Type -> VM (DataCon, [Type])
146 pdataReprDataCon ty
147   = do
148       (tc, arg_tys) <- pdataReprTyCon ty
149       let [dc] = tyConDataCons tc
150       return (dc, arg_tys)
151
152 mkVScrut :: VExpr -> VM (CoreExpr, CoreExpr, TyCon, [Type])
153 mkVScrut (ve, le)
154   = do
155       (tc, arg_tys) <- pdataReprTyCon ty
156       return (ve, unwrapFamInstScrut tc arg_tys le, tc, arg_tys)
157   where
158     ty = exprType ve
159
160 prDFunOfTyCon :: TyCon -> VM CoreExpr
161 prDFunOfTyCon tycon
162   = liftM Var
163   . maybeCantVectoriseM "No PR dictionary for tycon" (ppr tycon)
164   $ lookupTyConPR tycon
165
166 paDictArgType :: TyVar -> VM (Maybe Type)
167 paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
168   where
169     go ty k | Just k' <- kindView k = go ty k'
170     go ty (FunTy k1 k2)
171       = do
172           tv   <- newTyVar (fsLit "a") k1
173           mty1 <- go (TyVarTy tv) k1
174           case mty1 of
175             Just ty1 -> do
176                           mty2 <- go (AppTy ty (TyVarTy tv)) k2
177                           return $ fmap (ForAllTy tv . FunTy ty1) mty2
178             Nothing  -> go ty k2
179
180     go ty k
181       | isLiftedTypeKind k
182       = liftM Just (mkPADictType ty)
183
184     go _ _ = return Nothing
185
186 paDictOfType :: Type -> VM CoreExpr
187 paDictOfType ty = paDictOfTyApp ty_fn ty_args
188   where
189     (ty_fn, ty_args) = splitAppTys ty
190
191 paDictOfTyApp :: Type -> [Type] -> VM CoreExpr
192 paDictOfTyApp ty_fn ty_args
193   | Just ty_fn' <- coreView ty_fn = paDictOfTyApp ty_fn' ty_args
194 paDictOfTyApp (TyVarTy tv) ty_args
195   = do
196       dfun <- maybeV (lookupTyVarPA tv)
197       paDFunApply dfun ty_args
198 paDictOfTyApp (TyConApp tc _) ty_args
199   = do
200       dfun <- maybeCantVectoriseM "No PA dictionary for tycon" (ppr tc)
201             $ lookupTyConPA tc
202       paDFunApply (Var dfun) ty_args
203 paDictOfTyApp ty _
204   = cantVectorise "Can't construct PA dictionary for type" (ppr ty)
205
206 paDFunType :: TyCon -> VM Type
207 paDFunType tc
208   = do
209       margs <- mapM paDictArgType tvs
210       res   <- mkPADictType (mkTyConApp tc arg_tys)
211       return . mkForAllTys tvs
212              $ mkFunTys [arg | Just arg <- margs] res
213   where
214     tvs = tyConTyVars tc
215     arg_tys = mkTyVarTys tvs
216
217 paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
218 paDFunApply dfun tys
219   = do
220       dicts <- mapM paDictOfType tys
221       return $ mkApps (mkTyApps dfun tys) dicts
222
223 paMethod :: (Builtins -> Var) -> String -> Type -> VM CoreExpr
224 paMethod _ name ty
225   | Just tycon <- splitPrimTyCon ty
226   = liftM Var
227   . maybeCantVectoriseM "No PA method" (text name <+> text "for" <+> ppr tycon)
228   $ lookupPrimMethod tycon name
229
230 paMethod method _ ty
231   = do
232       fn   <- builtin method
233       dict <- paDictOfType ty
234       return $ mkApps (Var fn) [Type ty, dict]
235
236 prDictOfType :: Type -> VM CoreExpr
237 prDictOfType ty = prDictOfTyApp ty_fn ty_args
238   where
239     (ty_fn, ty_args) = splitAppTys ty
240
241 prDictOfTyApp :: Type -> [Type] -> VM CoreExpr
242 prDictOfTyApp ty_fn ty_args
243   | Just ty_fn' <- coreView ty_fn = prDictOfTyApp ty_fn' ty_args
244 prDictOfTyApp (TyConApp tc _) ty_args
245   = do
246       dfun <- liftM Var $ maybeV (lookupTyConPR tc)
247       prDFunApply dfun ty_args
248 prDictOfTyApp _ _ = noV
249
250 prDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
251 prDFunApply dfun tys
252   = do
253       dicts <- mapM prDictOfType tys
254       return $ mkApps (mkTyApps dfun tys) dicts
255
256 wrapPR :: Type -> VM CoreExpr
257 wrapPR ty
258   = do
259       pa_dict <- paDictOfType ty
260       pr_dfun <- prDFunOfTyCon =<< builtin wrapTyCon
261       return $ mkApps pr_dfun [Type ty, pa_dict]
262
263 replicatePD :: CoreExpr -> CoreExpr -> VM CoreExpr
264 replicatePD len x = liftM (`mkApps` [len,x])
265                           (paMethod replicatePDVar "replicatePD" (exprType x))
266
267 emptyPD :: Type -> VM CoreExpr
268 emptyPD = paMethod emptyPDVar "emptyPD"
269
270 packPD :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> VM CoreExpr
271 packPD ty xs len sel = liftM (`mkApps` [xs, len, sel])
272                              (paMethod packPDVar "packPD" ty)
273
274 packByTagPD :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
275                  -> VM CoreExpr
276 packByTagPD ty xs len tags t
277   = liftM (`mkApps` [xs, len, tags, t])
278           (paMethod packByTagPDVar "packByTagPD" ty)
279
280 combinePD :: Type -> CoreExpr -> CoreExpr -> [CoreExpr]
281           -> VM CoreExpr
282 combinePD ty len sel xs
283   = liftM (`mkApps` (len : sel : xs))
284           (paMethod (combinePDVar n) ("combine" ++ show n ++ "PD") ty)
285   where
286     n = length xs
287
288 liftPD :: CoreExpr -> VM CoreExpr
289 liftPD x
290   = do
291       lc <- builtin liftingContext
292       replicatePD (Var lc) x
293
294 zipScalars :: [Type] -> Type -> VM CoreExpr
295 zipScalars arg_tys res_ty
296   = do
297       scalar <- builtin scalarClass
298       (dfuns, _) <- mapAndUnzipM (\ty -> lookupInst scalar [ty]) ty_args
299       zipf <- builtin (scalarZip $ length arg_tys)
300       return $ Var zipf `mkTyApps` ty_args `mkApps` map Var dfuns
301     where
302       ty_args = arg_tys ++ [res_ty]
303
304 scalarClosure :: [Type] -> Type -> CoreExpr -> CoreExpr -> VM CoreExpr
305 scalarClosure arg_tys res_ty scalar_fun array_fun
306   = do
307       ctr <- builtin (closureCtrFun $ length arg_tys)
308       pas <- mapM paDictOfType (init arg_tys)
309       return $ Var ctr `mkTyApps` (arg_tys ++ [res_ty])
310                        `mkApps`   (pas ++ [scalar_fun, array_fun])
311
312 newLocalVVar :: FastString -> Type -> VM VVar
313 newLocalVVar fs vty
314   = do
315       lty <- mkPDataType vty
316       vv  <- newLocalVar fs vty
317       lv  <- newLocalVar fs lty
318       return (vv,lv)
319
320 polyAbstract :: [TyVar] -> ([Var] -> VM a) -> VM a
321 polyAbstract tvs p
322   = localV
323   $ do
324       mdicts <- mapM mk_dict_var tvs
325       zipWithM_ (\tv -> maybe (defLocalTyVar tv)
326                               (defLocalTyVarWithPA tv . Var)) tvs mdicts
327       p (mk_args mdicts)
328   where
329     mk_dict_var tv = do
330                        r <- paDictArgType tv
331                        case r of
332                          Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
333                          Nothing -> return Nothing
334
335     mk_args mdicts = [dict | Just dict <- mdicts]
336
337 polyArity :: [TyVar] -> VM Int
338 polyArity tvs = do
339                   tys <- mapM paDictArgType tvs
340                   return $ length [() | Just _ <- tys]
341
342 polyApply :: CoreExpr -> [Type] -> VM CoreExpr
343 polyApply expr tys
344   = do
345       dicts <- mapM paDictOfType tys
346       return $ expr `mkTyApps` tys `mkApps` dicts
347
348 polyVApply :: VExpr -> [Type] -> VM VExpr
349 polyVApply expr tys
350   = do
351       dicts <- mapM paDictOfType tys
352       return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr
353
354
355 data Inline = Inline Int -- arity
356             | DontInline
357
358 addInlineArity :: Inline -> Int -> Inline
359 addInlineArity (Inline m) n = Inline (m+n)
360 addInlineArity DontInline _ = DontInline
361
362 inlineMe :: Inline
363 inlineMe = Inline 0
364
365 hoistBinding :: Var -> CoreExpr -> VM ()
366 hoistBinding v e = updGEnv $ \env ->
367   env { global_bindings = (v,e) : global_bindings env }
368
369 hoistExpr :: FastString -> CoreExpr -> Inline -> VM Var
370 hoistExpr fs expr inl
371   = do
372       var <- mk_inline `liftM` newLocalVar fs (exprType expr)
373       hoistBinding var expr
374       return var
375   where
376     mk_inline var = case inl of
377                       Inline arity -> var `setIdUnfolding`
378                                       mkInlineRule InlSat expr arity
379                       DontInline   -> var
380
381 hoistVExpr :: VExpr -> Inline -> VM VVar
382 hoistVExpr (ve, le) inl
383   = do
384       fs <- getBindName
385       vv <- hoistExpr ('v' `consFS` fs) ve inl
386       lv <- hoistExpr ('l' `consFS` fs) le (addInlineArity inl 1)
387       return (vv, lv)
388
389 hoistPolyVExpr :: [TyVar] -> Inline -> VM VExpr -> VM VExpr
390 hoistPolyVExpr tvs inline p
391   = do
392       inline' <- liftM (addInlineArity inline) (polyArity tvs)
393       expr <- closedV . polyAbstract tvs $ \args ->
394               liftM (mapVect (mkLams $ tvs ++ args)) p
395       fn   <- hoistVExpr expr inline'
396       polyVApply (vVar fn) (mkTyVarTys tvs)
397
398 takeHoisted :: VM [(Var, CoreExpr)]
399 takeHoisted
400   = do
401       env <- readGEnv id
402       setGEnv $ env { global_bindings = [] }
403       return $ global_bindings env
404
405 {-
406 boxExpr :: Type -> VExpr -> VM VExpr
407 boxExpr ty (vexpr, lexpr)
408   | Just (tycon, []) <- splitTyConApp_maybe ty
409   , isUnLiftedTyCon tycon
410   = do
411       r <- lookupBoxedTyCon tycon
412       case r of
413         Just tycon' -> let [dc] = tyConDataCons tycon'
414                        in
415                        return (mkConApp dc [vexpr], lexpr)
416         Nothing     -> return (vexpr, lexpr)
417 -}
418
419 mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
420 mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
421   = do
422       dict <- paDictOfType env_ty
423       mkv  <- builtin closureVar
424       mkl  <- builtin liftedClosureVar
425       return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
426               Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
427
428 mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
429 mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
430   = do
431       vapply <- builtin applyVar
432       lapply <- builtin liftedApplyVar
433       lc     <- builtin liftingContext
434       return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
435               Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [Var lc, lclo, larg])
436
437 buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
438 buildClosures _   _    [] _ mk_body
439   = mk_body
440 buildClosures tvs vars [arg_ty] res_ty mk_body
441   = -- liftM vInlineMe $
442       buildClosure tvs vars arg_ty res_ty mk_body
443 buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
444   = do
445       res_ty' <- mkClosureTypes arg_tys res_ty
446       arg <- newLocalVVar (fsLit "x") arg_ty
447       -- liftM vInlineMe
448       buildClosure tvs vars arg_ty res_ty'
449         . hoistPolyVExpr tvs (Inline (length vars + 1))
450         $ do
451             lc <- builtin liftingContext
452             clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
453             return $ vLams lc (vars ++ [arg]) clo
454
455 -- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
456 --   where
457 --     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
458 --     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
459 --
460 buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
461 buildClosure tvs vars arg_ty res_ty mk_body
462   = do
463       (env_ty, env, bind) <- buildEnv vars
464       env_bndr <- newLocalVVar (fsLit "env") env_ty
465       arg_bndr <- newLocalVVar (fsLit "arg") arg_ty
466
467       fn <- hoistPolyVExpr tvs (Inline 2)
468           $ do
469               lc    <- builtin liftingContext
470               body  <- mk_body
471               return -- . vInlineMe
472                      . vLams lc [env_bndr, arg_bndr]
473                      $ bind (vVar env_bndr)
474                             (vVarApps lc body (vars ++ [arg_bndr]))
475
476       mkClosure arg_ty res_ty env_ty fn env
477
478 buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VExpr)
479 buildEnv [] = do
480              ty    <- voidType
481              void  <- builtin voidVar
482              pvoid <- builtin pvoidVar
483              return (ty, vVar (void, pvoid), \_ body -> body)
484
485 buildEnv [v] = return (vVarType v, vVar v,
486                     \env body -> vLet (vNonRec v env) body)
487
488 buildEnv vs
489   = do
490       
491       (lenv_tc, lenv_tyargs) <- pdataReprTyCon ty
492
493       let venv_con   = tupleCon Boxed (length vs) 
494           [lenv_con] = tyConDataCons lenv_tc
495
496           venv       = mkCoreTup (map Var vvs)
497           lenv       = Var (dataConWrapId lenv_con)
498                        `mkTyApps` lenv_tyargs
499                        `mkApps`   map Var lvs
500
501           vbind env body = mkWildCase env ty (exprType body)
502                            [(DataAlt venv_con, vvs, body)]
503
504           lbind env body =
505             let scrut = unwrapFamInstScrut lenv_tc lenv_tyargs env
506             in
507             mkWildCase scrut (exprType scrut) (exprType body)
508               [(DataAlt lenv_con, lvs, body)]
509
510           bind (venv, lenv) (vbody, lbody) = (vbind venv vbody,
511                                               lbind lenv lbody)
512
513       return (ty, (venv, lenv), bind)
514   where
515     (vvs, lvs) = unzip vs
516     tys        = map vVarType vs
517     ty         = mkCoreTupTy tys
518