Separate length from data in DPH arrays
[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,
9   mkPADictType, mkPArrayType, mkPDataType, mkPReprType, mkPArray,
10
11   pdataReprTyCon, pdataReprDataCon, mkVScrut,
12   prDFunOfTyCon,
13   paDictArgType, paDictOfType, paDFunType,
14   paMethod, mkPR, replicatePD, emptyPD, packPD,
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 voidTyCon []
102
103 mkClosureTypes :: [Type] -> Type -> VM Type
104 mkClosureTypes = mkBuiltinTyConApps closureTyCon
105
106 mkPReprType :: Type -> VM Type
107 mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]
108
109 mkPADictType :: Type -> VM Type
110 mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
111
112 mkPArrayType :: Type -> VM Type
113 mkPArrayType ty
114   | Just tycon <- splitPrimTyCon ty
115   = do
116       r <- lookupPrimPArray tycon
117       case r of
118         Just arr -> return $ mkTyConApp arr []
119         Nothing  -> cantVectorise "Primitive tycon not vectorised" (ppr tycon)
120 mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
121
122 mkPDataType :: Type -> VM Type
123 mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty]
124
125 mkPArray :: Type -> CoreExpr -> CoreExpr -> VM CoreExpr
126 mkPArray ty len dat = do
127                         tc <- builtin parrayTyCon
128                         let [dc] = tyConDataCons tc
129                         return $ mkConApp dc [Type ty, len, dat]
130
131 mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
132 mkBuiltinCo get_tc
133   = do
134       tc <- builtin get_tc
135       return $ mkTyConApp tc []
136
137 pdataReprTyCon :: Type -> VM (TyCon, [Type])
138 pdataReprTyCon ty = builtin pdataTyCon >>= (`lookupFamInst` [ty])
139
140 pdataReprDataCon :: Type -> VM (DataCon, [Type])
141 pdataReprDataCon ty
142   = do
143       (tc, arg_tys) <- pdataReprTyCon ty
144       let [dc] = tyConDataCons tc
145       return (dc, arg_tys)
146
147 mkVScrut :: VExpr -> VM (CoreExpr, CoreExpr, TyCon, [Type])
148 mkVScrut (ve, le)
149   = do
150       (tc, arg_tys) <- pdataReprTyCon ty
151       return (ve, unwrapFamInstScrut tc arg_tys le, tc, arg_tys)
152   where
153     ty = exprType ve
154
155 prDFunOfTyCon :: TyCon -> VM CoreExpr
156 prDFunOfTyCon tycon
157   = liftM Var
158   . maybeCantVectoriseM "No PR dictionary for tycon" (ppr tycon)
159   $ lookupTyConPR tycon
160
161 paDictArgType :: TyVar -> VM (Maybe Type)
162 paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
163   where
164     go ty k | Just k' <- kindView k = go ty k'
165     go ty (FunTy k1 k2)
166       = do
167           tv   <- newTyVar (fsLit "a") k1
168           mty1 <- go (TyVarTy tv) k1
169           case mty1 of
170             Just ty1 -> do
171                           mty2 <- go (AppTy ty (TyVarTy tv)) k2
172                           return $ fmap (ForAllTy tv . FunTy ty1) mty2
173             Nothing  -> go ty k2
174
175     go ty k
176       | isLiftedTypeKind k
177       = liftM Just (mkPADictType ty)
178
179     go _ _ = return Nothing
180
181 paDictOfType :: Type -> VM CoreExpr
182 paDictOfType ty = paDictOfTyApp ty_fn ty_args
183   where
184     (ty_fn, ty_args) = splitAppTys ty
185
186 paDictOfTyApp :: Type -> [Type] -> VM CoreExpr
187 paDictOfTyApp ty_fn ty_args
188   | Just ty_fn' <- coreView ty_fn = paDictOfTyApp ty_fn' ty_args
189 paDictOfTyApp (TyVarTy tv) ty_args
190   = do
191       dfun <- maybeV (lookupTyVarPA tv)
192       paDFunApply dfun ty_args
193 paDictOfTyApp (TyConApp tc _) ty_args
194   = do
195       dfun <- maybeCantVectoriseM "No PA dictionary for tycon" (ppr tc)
196             $ lookupTyConPA tc
197       paDFunApply (Var dfun) ty_args
198 paDictOfTyApp ty _
199   = cantVectorise "Can't construct PA dictionary for type" (ppr ty)
200
201 paDFunType :: TyCon -> VM Type
202 paDFunType tc
203   = do
204       margs <- mapM paDictArgType tvs
205       res   <- mkPADictType (mkTyConApp tc arg_tys)
206       return . mkForAllTys tvs
207              $ mkFunTys [arg | Just arg <- margs] res
208   where
209     tvs = tyConTyVars tc
210     arg_tys = mkTyVarTys tvs
211
212 paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
213 paDFunApply dfun tys
214   = do
215       dicts <- mapM paDictOfType tys
216       return $ mkApps (mkTyApps dfun tys) dicts
217
218 type PAMethod = (Builtins -> Var, String)
219
220 paMethod :: (Builtins -> Var) -> String -> Type -> VM CoreExpr
221 paMethod _ name ty
222   | Just tycon <- splitPrimTyCon ty
223   = liftM Var
224   . maybeCantVectoriseM "No PA method" (text name <+> text "for" <+> ppr tycon)
225   $ lookupPrimMethod tycon name
226
227 paMethod method _ ty
228   = do
229       fn   <- builtin method
230       dict <- paDictOfType ty
231       return $ mkApps (Var fn) [Type ty, dict]
232
233 mkPR :: Type -> VM CoreExpr
234 mkPR ty
235   = do
236       fn   <- builtin mkPRVar
237       dict <- paDictOfType ty
238       return $ mkApps (Var fn) [Type ty, dict]
239
240 replicatePD :: CoreExpr -> CoreExpr -> VM CoreExpr
241 replicatePD len x = liftM (`mkApps` [len,x])
242                           (paMethod replicatePDVar "replicatePD" (exprType x))
243
244 emptyPD :: Type -> VM CoreExpr
245 emptyPD = paMethod emptyPDVar "emptyPD"
246
247 packPD :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> VM CoreExpr
248 packPD ty xs len sel = liftM (`mkApps` [xs, len, sel])
249                              (paMethod packPDVar "packPD" ty)
250
251 combinePD :: Type -> CoreExpr -> CoreExpr -> [CoreExpr]
252           -> VM CoreExpr
253 combinePD ty len sel xs
254   = liftM (`mkApps` (len : sel : xs))
255           (paMethod (combinePDVar n) ("combine" ++ show n ++ "PD") ty)
256   where
257     n = length xs
258
259 liftPD :: CoreExpr -> VM CoreExpr
260 liftPD x
261   = do
262       lc <- builtin liftingContext
263       replicatePD (Var lc) x
264
265 zipScalars :: [Type] -> Type -> VM CoreExpr
266 zipScalars arg_tys res_ty
267   = do
268       scalar <- builtin scalarClass
269       (dfuns, _) <- mapAndUnzipM (\ty -> lookupInst scalar [ty]) ty_args
270       zipf <- builtin (scalarZip $ length arg_tys)
271       return $ Var zipf `mkTyApps` ty_args `mkApps` map Var dfuns
272     where
273       ty_args = arg_tys ++ [res_ty]
274
275 scalarClosure :: [Type] -> Type -> CoreExpr -> CoreExpr -> VM CoreExpr
276 scalarClosure arg_tys res_ty scalar_fun array_fun
277   = do
278       ctr <- builtin (closureCtrFun $ length arg_tys)
279       pas <- mapM paDictOfType (init arg_tys)
280       return $ Var ctr `mkTyApps` (arg_tys ++ [res_ty])
281                        `mkApps`   (pas ++ [scalar_fun, array_fun])
282
283 newLocalVVar :: FastString -> Type -> VM VVar
284 newLocalVVar fs vty
285   = do
286       lty <- mkPDataType vty
287       vv  <- newLocalVar fs vty
288       lv  <- newLocalVar fs lty
289       return (vv,lv)
290
291 polyAbstract :: [TyVar] -> ((CoreExpr -> CoreExpr) -> VM a) -> VM a
292 polyAbstract tvs p
293   = localV
294   $ do
295       mdicts <- mapM mk_dict_var tvs
296       zipWithM_ (\tv -> maybe (defLocalTyVar tv) (defLocalTyVarWithPA tv . Var)) tvs mdicts
297       p (mk_lams mdicts)
298   where
299     mk_dict_var tv = do
300                        r <- paDictArgType tv
301                        case r of
302                          Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
303                          Nothing -> return Nothing
304
305     mk_lams mdicts = mkLams (tvs ++ [dict | Just dict <- mdicts])
306
307 polyApply :: CoreExpr -> [Type] -> VM CoreExpr
308 polyApply expr tys
309   = do
310       dicts <- mapM paDictOfType tys
311       return $ expr `mkTyApps` tys `mkApps` dicts
312
313 polyVApply :: VExpr -> [Type] -> VM VExpr
314 polyVApply expr tys
315   = do
316       dicts <- mapM paDictOfType tys
317       return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr
318
319 hoistBinding :: Var -> CoreExpr -> VM ()
320 hoistBinding v e = updGEnv $ \env ->
321   env { global_bindings = (v,e) : global_bindings env }
322
323 hoistExpr :: FastString -> CoreExpr -> VM Var
324 hoistExpr fs expr
325   = do
326       var <- newLocalVar fs (exprType expr)
327       hoistBinding var expr
328       return var
329
330 hoistVExpr :: VExpr -> VM VVar
331 hoistVExpr (ve, le)
332   = do
333       fs <- getBindName
334       vv <- hoistExpr ('v' `consFS` fs) ve
335       lv <- hoistExpr ('l' `consFS` fs) le
336       return (vv, lv)
337
338 hoistPolyVExpr :: [TyVar] -> VM VExpr -> VM VExpr
339 hoistPolyVExpr tvs p
340   = do
341       expr <- closedV . polyAbstract tvs $ \abstract ->
342               liftM (mapVect abstract) p
343       fn   <- hoistVExpr expr
344       polyVApply (vVar fn) (mkTyVarTys tvs)
345
346 takeHoisted :: VM [(Var, CoreExpr)]
347 takeHoisted
348   = do
349       env <- readGEnv id
350       setGEnv $ env { global_bindings = [] }
351       return $ global_bindings env
352
353 {-
354 boxExpr :: Type -> VExpr -> VM VExpr
355 boxExpr ty (vexpr, lexpr)
356   | Just (tycon, []) <- splitTyConApp_maybe ty
357   , isUnLiftedTyCon tycon
358   = do
359       r <- lookupBoxedTyCon tycon
360       case r of
361         Just tycon' -> let [dc] = tyConDataCons tycon'
362                        in
363                        return (mkConApp dc [vexpr], lexpr)
364         Nothing     -> return (vexpr, lexpr)
365 -}
366
367 mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
368 mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
369   = do
370       dict <- paDictOfType env_ty
371       mkv  <- builtin closureVar
372       mkl  <- builtin liftedClosureVar
373       return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
374               Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
375
376 mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
377 mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
378   = do
379       vapply <- builtin applyVar
380       lapply <- builtin liftedApplyVar
381       lc     <- builtin liftingContext
382       return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
383               Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [Var lc, lclo, larg])
384
385 buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
386 buildClosures _   _    [] _ mk_body
387   = mk_body
388 buildClosures tvs vars [arg_ty] res_ty mk_body
389   = liftM vInlineMe (buildClosure tvs vars arg_ty res_ty mk_body)
390 buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
391   = do
392       res_ty' <- mkClosureTypes arg_tys res_ty
393       arg <- newLocalVVar (fsLit "x") arg_ty
394       liftM vInlineMe
395         . buildClosure tvs vars arg_ty res_ty'
396         . hoistPolyVExpr tvs
397         $ do
398             lc <- builtin liftingContext
399             clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
400             return $ vLams lc (vars ++ [arg]) clo
401
402 -- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
403 --   where
404 --     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
405 --     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
406 --
407 buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
408 buildClosure tvs vars arg_ty res_ty mk_body
409   = do
410       (env_ty, env, bind) <- buildEnv vars
411       env_bndr <- newLocalVVar (fsLit "env") env_ty
412       arg_bndr <- newLocalVVar (fsLit "arg") arg_ty
413
414       fn <- hoistPolyVExpr tvs
415           $ do
416               lc    <- builtin liftingContext
417               body  <- mk_body
418               return . vInlineMe
419                      . vLams lc [env_bndr, arg_bndr]
420                      $ bind (vVar env_bndr)
421                             (vVarApps lc body (vars ++ [arg_bndr]))
422
423       mkClosure arg_ty res_ty env_ty fn env
424
425 buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VExpr)
426 buildEnv [] = do
427              ty    <- voidType
428              void  <- builtin voidVar
429              pvoid <- builtin pvoidVar
430              return (ty, vVar (void, pvoid), \_ body -> body)
431
432 buildEnv [v] = return (vVarType v, vVar v,
433                     \env body -> vLet (vNonRec v env) body)
434
435 buildEnv vs
436   = do
437       
438       (lenv_tc, lenv_tyargs) <- pdataReprTyCon ty
439
440       let venv_con   = tupleCon Boxed (length vs) 
441           [lenv_con] = tyConDataCons lenv_tc
442
443           venv       = mkCoreTup (map Var vvs)
444           lenv       = Var (dataConWrapId lenv_con)
445                        `mkTyApps` lenv_tyargs
446                        `mkApps`   map Var lvs
447
448           vbind env body = mkWildCase venv ty (exprType body)
449                              [(DataAlt venv_con, vvs, body)]
450
451           lbind env body =
452             let scrut = unwrapFamInstScrut lenv_tc lenv_tyargs lenv
453             in
454             mkWildCase scrut (exprType scrut) (exprType body)
455               [(DataAlt lenv_con, lvs, body)]
456
457           bind (venv, lenv) (vbody, lbody) = (vbind venv vbody,
458                                               lbind lenv lbody)
459
460       return (ty, (venv, lenv), bind)
461   where
462     (vvs, lvs) = unzip vs
463     tys        = map vVarType vs
464     ty         = mkCoreTupTy tys
465