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