1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2 PAInstance, buildPADict )
5 #include "HsVersions.h"
11 import HscTypes ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
20 import FamInstEnv ( FamInst, mkLocalFamInst )
21 import InstEnv ( Instance, mkLocalInstance, instanceDFunId )
24 import BasicTypes ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
26 import Id ( mkWildId )
27 import Name ( Name, getOccName )
29 import TysWiredIn ( unitTy, intTy, intDataCon, unitDataConId )
30 import TysPrim ( intPrimTy )
35 import Digraph ( SCC(..), stronglyConnComp )
39 import Control.Monad ( liftM, liftM2, zipWithM, zipWithM_ )
40 import Data.List ( inits, tails, zipWith4, zipWith5 )
42 -- ----------------------------------------------------------------------------
45 vectTyCon :: TyCon -> VM TyCon
47 | isFunTyCon tc = builtin closureTyCon
48 | isBoxedTupleTyCon tc = return tc
49 | isUnLiftedTyCon tc = return tc
53 Just tc' -> return tc'
55 -- FIXME: just for now
56 Nothing -> pprTrace "ccTyCon:" (ppr tc) $ return tc
58 vectType :: Type -> VM Type
59 vectType ty | Just ty' <- coreView ty = vectType ty'
60 vectType (TyVarTy tv) = return $ TyVarTy tv
61 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
62 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
63 vectType (FunTy ty1 ty2) = liftM2 TyConApp (builtin closureTyCon)
64 (mapM vectType [ty1,ty2])
65 vectType ty@(ForAllTy _ _)
67 mdicts <- mapM paDictArgType tyvars
68 mono_ty' <- vectType mono_ty
69 return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
71 (tyvars, mono_ty) = splitForAllTys ty
73 vectType ty = pprPanic "vectType:" (ppr ty)
75 -- ----------------------------------------------------------------------------
78 type TyConGroup = ([TyCon], UniqSet TyCon)
80 data PAInstance = PAInstance {
82 , painstOrigTyCon :: TyCon
83 , painstVectTyCon :: TyCon
84 , painstArrTyCon :: TyCon
87 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
90 cs <- readGEnv $ mk_map . global_tycons
91 let (conv_tcs, keep_tcs) = classifyTyCons cs groups
92 keep_dcs = concatMap tyConDataCons keep_tcs
93 zipWithM_ defTyCon keep_tcs keep_tcs
94 zipWithM_ defDataCon keep_dcs keep_dcs
95 new_tcs <- vectTyConDecls conv_tcs
97 let orig_tcs = keep_tcs ++ conv_tcs
98 vect_tcs = keep_tcs ++ new_tcs
100 repr_tcs <- zipWithM buildPReprTyCon orig_tcs vect_tcs
101 parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
102 dfuns <- mapM mkPADFun vect_tcs
103 defTyConPAs (zip vect_tcs dfuns)
104 binds <- sequence (zipWith5 buildTyConBindings orig_tcs
110 let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
112 let new_env = extendTypeEnvList env
113 (map ATyCon all_new_tcs
114 ++ [ADataCon dc | tc <- all_new_tcs
115 , dc <- tyConDataCons tc])
117 return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
119 tycons = typeEnvTyCons env
120 groups = tyConGroups tycons
122 mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
124 keep_tc tc = let dcs = tyConDataCons tc
126 defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
129 vectTyConDecls :: [TyCon] -> VM [TyCon]
130 vectTyConDecls tcs = fixV $ \tcs' ->
132 mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
133 mapM vectTyConDecl tcs
136 lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
138 vectTyConDecl :: TyCon -> VM TyCon
141 name' <- cloneName mkVectTyConOcc name
142 rhs' <- vectAlgTyConRhs (algTyConRhs tc)
144 liftDs $ buildAlgTyCon name'
146 [] -- no stupid theta
148 rec_flag -- FIXME: is this ok?
149 False -- FIXME: no generics
150 False -- not GADT syntax
151 Nothing -- not a family instance
154 tyvars = tyConTyVars tc
155 rec_flag = boolToRecFlag (isRecursiveTyCon tc)
157 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
158 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
162 data_cons' <- mapM vectDataCon data_cons
163 zipWithM_ defDataCon data_cons data_cons'
164 return $ DataTyCon { data_cons = data_cons'
168 vectDataCon :: DataCon -> VM DataCon
170 | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
171 | not . null $ dataConEqSpec dc = pprPanic "vectDataCon: eq spec" (ppr dc)
174 name' <- cloneName mkVectDataConOcc name
175 tycon' <- vectTyCon tycon
176 arg_tys <- mapM vectType rep_arg_tys
178 liftDs $ buildDataCon name'
180 (map (const NotMarkedStrict) arg_tys)
181 [] -- no labelled fields
183 [] -- no existential tvs for now
184 [] -- no eq spec for now
189 name = dataConName dc
190 univ_tvs = dataConUnivTyVars dc
191 rep_arg_tys = dataConRepArgTys dc
192 tycon = dataConTyCon dc
194 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
195 mk_fam_inst fam_tc arg_tc
196 = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
198 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
199 buildPReprTyCon orig_tc vect_tc
201 name <- cloneName mkPReprTyConOcc (tyConName orig_tc)
202 rhs_ty <- buildPReprType vect_tc
203 prepr_tc <- builtin preprTyCon
204 liftDs $ buildSynTyCon name
206 (SynonymTyCon rhs_ty)
207 (Just $ mk_fam_inst prepr_tc vect_tc)
209 tyvars = tyConTyVars vect_tc
211 buildPReprType :: TyCon -> VM Type
212 buildPReprType = liftM repr_type . mkTyConRepr
214 buildToPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
215 buildToPRepr (TyConRepr {
217 , repr_prod_tycons = prod_tycons
218 , repr_prod_tys = prod_tys
219 , repr_sum_tycon = repr_sum_tycon
220 , repr_type = repr_type
224 arg <- newLocalVar FSLIT("x") arg_ty
225 vars <- mapM (mapM (newLocalVar FSLIT("x"))) repr_tys
228 . wrapFamInstBody prepr_tc var_tys
229 . Case (Var arg) (mkWildId arg_ty) repr_type
230 . mk_alts data_cons vars
231 . zipWith3 mk_prod prod_tycons repr_tys $ map (map Var) vars
233 var_tys = mkTyVarTys $ tyConTyVars vect_tc
234 arg_ty = mkTyConApp vect_tc var_tys
235 data_cons = tyConDataCons vect_tc
237 Just sum_tycon = repr_sum_tycon
238 sum_data_cons = tyConDataCons sum_tycon
240 mk_alts _ _ [] = [(DEFAULT, [], Var unitDataConId)]
241 mk_alts [dc] [vars] [expr] = [(DataAlt dc, vars, expr)]
242 mk_alts dcs vars exprs = zipWith4 mk_alt dcs vars sum_data_cons exprs
244 mk_alt dc vars sum_dc expr = (DataAlt dc, vars,
245 mkConApp sum_dc (map Type prod_tys ++ [expr]))
247 mk_prod _ _ [] = Var unitDataConId
248 mk_prod _ _ [expr] = expr
249 mk_prod (Just tc) tys exprs = mkConApp dc (map Type tys ++ exprs)
251 [dc] = tyConDataCons tc
253 buildFromPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
254 buildFromPRepr (TyConRepr {
256 , repr_prod_tycons = prod_tycons
257 , repr_prod_tys = prod_tys
258 , repr_sum_tycon = repr_sum_tycon
259 , repr_type = repr_type
263 arg_ty <- mkPReprType res_ty
264 arg <- newLocalVar FSLIT("x") arg_ty
267 . un_sum (unwrapFamInstScrut prepr_tc var_tys (Var arg)))
268 (sequence $ zipWith4 un_prod data_cons prod_tycons prod_tys repr_tys)
270 var_tys = mkTyVarTys $ tyConTyVars vect_tc
271 ty_args = map Type var_tys
272 res_ty = mkTyConApp vect_tc var_tys
273 data_cons = tyConDataCons vect_tc
275 Just sum_tc = repr_sum_tycon
276 sum_data_cons = tyConDataCons sum_tc
280 var <- newLocalVar FSLIT("u") unitTy
281 return (var, mkConApp dc ty_args)
284 var <- newLocalVar FSLIT("x") ty
285 return (var, mkConApp dc (ty_args ++ [Var var]))
287 un_prod dc (Just prod_tc) prod_ty tys
289 vars <- mapM (newLocalVar FSLIT("x")) tys
290 pv <- newLocalVar FSLIT("p") prod_ty
292 let res = mkConApp dc (ty_args ++ map Var vars)
293 expr = Case (Var pv) (mkWildId prod_ty) res_ty
294 [(DataAlt prod_dc, vars, res)]
298 [prod_dc] = tyConDataCons prod_tc
301 un_sum scrut [(var, expr)] = Let (NonRec var scrut) expr
303 = Case scrut (mkWildId repr_type) res_ty
304 $ zipWith mk_alt sum_data_cons alts
306 mk_alt sum_dc (var, expr) = (DataAlt sum_dc, [var], expr)
309 buildToArrPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
310 buildToArrPRepr _ vect_tc prepr_tc arr_tc
312 arg_ty <- mkPArrayType el_ty
313 rep_tys <- mapM (mapM mkPArrayType) rep_el_tys
315 arg <- newLocalVar FSLIT("xs") arg_ty
316 bndrss <- mapM (mapM (newLocalVar FSLIT("ys"))) rep_tys
317 len <- newLocalVar FSLIT("len") intPrimTy
318 sel <- newLocalVar FSLIT("sel") =<< mkPArrayType intTy
320 let add_sel xs | has_selector = sel : xs
323 all_bndrs = len : add_sel (concat bndrss)
325 res <- parrayCoerce prepr_tc var_tys
326 =<< mkToArrPRepr (Var len) (Var sel) (map (map Var) bndrss)
327 res_ty <- mkPArrayType =<< mkPReprType el_ty
330 $ Case (unwrapFamInstScrut arr_tc var_tys (Var arg))
331 (mkWildId (mkTyConApp arr_tc var_tys))
333 [(DataAlt arr_dc, all_bndrs, res)]
335 var_tys = mkTyVarTys $ tyConTyVars vect_tc
336 el_ty = mkTyConApp vect_tc var_tys
337 data_cons = tyConDataCons vect_tc
338 rep_el_tys = map dataConRepArgTys data_cons
340 [arr_dc] = tyConDataCons arr_tc
342 has_selector | [_] <- data_cons = False
345 buildFromArrPRepr :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
346 buildFromArrPRepr _ vect_tc prepr_tc arr_tc
347 = mkFromArrPRepr undefined undefined undefined undefined undefined undefined
349 buildPRDict :: TyConRepr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
350 buildPRDict _ vect_tc prepr_tc _
351 = prCoerce prepr_tc var_tys
352 =<< prDictOfType (mkTyConApp prepr_tc var_tys)
354 var_tys = mkTyVarTys $ tyConTyVars vect_tc
356 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
357 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
359 name' <- cloneName mkPArrayTyConOcc orig_name
360 rhs <- buildPArrayTyConRhs orig_name vect_tc repr_tc
361 parray <- builtin parrayTyCon
363 liftDs $ buildAlgTyCon name'
365 [] -- no stupid theta
367 rec_flag -- FIXME: is this ok?
368 False -- FIXME: no generics
369 False -- not GADT syntax
370 (Just $ mk_fam_inst parray vect_tc)
372 orig_name = tyConName orig_tc
373 tyvars = tyConTyVars vect_tc
374 rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
377 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
378 buildPArrayTyConRhs orig_name vect_tc repr_tc
380 data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
381 return $ DataTyCon { data_cons = [data_con], is_enum = False }
383 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
384 buildPArrayDataCon orig_name vect_tc repr_tc
386 dc_name <- cloneName mkPArrayDataConOcc orig_name
387 shape <- tyConShape vect_tc
388 repr_tys <- mapM mkPArrayType types
390 liftDs $ buildDataCon dc_name
392 (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
393 [] -- no field labels
394 (tyConTyVars vect_tc)
395 [] -- no existentials
398 (shapeReprTys shape ++ repr_tys)
401 types = [ty | dc <- tyConDataCons vect_tc
402 , ty <- dataConRepArgTys dc]
404 mkPADFun :: TyCon -> VM Var
406 = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
409 shapeReprTys :: [Type]
410 , shapeStrictness :: [StrictnessMark]
411 , shapeLength :: [CoreExpr] -> VM CoreExpr
412 , shapeReplicate :: CoreExpr -> CoreExpr -> VM [CoreExpr]
415 tyConShape :: TyCon -> VM Shape
417 | isProductTyCon vect_tc
419 shapeReprTys = [intPrimTy]
420 , shapeStrictness = [NotMarkedStrict]
421 , shapeLength = \[len] -> return len
422 , shapeReplicate = \len _ -> return [len]
427 repr_ty <- mkPArrayType intTy -- FIXME: we want to unbox this
429 shapeReprTys = [repr_ty]
430 , shapeStrictness = [MarkedStrict]
431 , shapeLength = \[sel] -> lengthPA sel
432 , shapeReplicate = \len n -> do
433 e <- replicatePA len n
437 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
438 -> VM [(Var, CoreExpr)]
439 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
441 shape <- tyConShape vect_tc
442 repr <- mkTyConRepr vect_tc
443 sequence_ (zipWith4 (vectDataConWorker shape vect_tc arr_tc arr_dc)
448 dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
450 return $ (dfun, dict) : binds
452 orig_dcs = tyConDataCons orig_tc
453 vect_dcs = tyConDataCons vect_tc
454 [arr_dc] = tyConDataCons arr_tc
456 repr_tys = map dataConRepArgTys vect_dcs
458 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
459 -> DataCon -> DataCon -> [[Type]] -> [[Type]]
461 vectDataConWorker shape vect_tc arr_tc arr_dc orig_dc vect_dc pre (dc_tys : post)
465 . polyAbstract tvs $ \abstract ->
466 liftM (abstract . vectorised)
467 $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
469 worker <- cloneId mkVectOcc orig_worker (exprType clo)
470 hoistBinding worker clo
471 defGlobalVar orig_worker worker
474 tvs = tyConTyVars vect_tc
475 arg_tys = mkTyVarTys tvs
476 res_ty = mkTyConApp vect_tc arg_tys
478 orig_worker = dataConWorkId orig_dc
480 mk_vect = return . mkConApp vect_dc $ map Type arg_tys
482 len <- newLocalVar FSLIT("n") intPrimTy
483 arr_tys <- mapM mkPArrayType dc_tys
484 args <- mapM (newLocalVar FSLIT("xs")) arr_tys
485 shapes <- shapeReplicate shape
487 (mkDataConTag vect_dc)
489 empty_pre <- mapM emptyPA (concat pre)
490 empty_post <- mapM emptyPA (concat post)
492 return . mkLams (len : args)
493 . wrapFamInstBody arr_tc arg_tys
495 $ map Type arg_tys ++ shapes
500 buildPADict :: TyConRepr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
501 buildPADict repr vect_tc prepr_tc arr_tc dfun
502 = polyAbstract tvs $ \abstract ->
504 meth_binds <- mapM (mk_method repr) paMethods
505 let meth_exprs = map (Var . fst) meth_binds
507 pa_dc <- builtin paDataCon
508 let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
509 body = Let (Rec meth_binds) dict
510 return . mkInlineMe $ abstract body
512 tvs = tyConTyVars arr_tc
513 arg_tys = mkTyVarTys tvs
515 mk_method repr (name, build)
518 body <- build repr vect_tc prepr_tc arr_tc
519 var <- newLocalVar name (exprType body)
520 return (var, mkInlineMe body)
522 paMethods = [(FSLIT("toPRepr"), buildToPRepr),
523 (FSLIT("fromPRepr"), buildFromPRepr),
524 (FSLIT("toArrPRepr"), buildToArrPRepr),
525 (FSLIT("fromArrPRepr"), buildFromArrPRepr),
526 (FSLIT("dictPRepr"), buildPRDict)]
528 -- | Split the given tycons into two sets depending on whether they have to be
529 -- converted (first list) or not (second list). The first argument contains
530 -- information about the conversion status of external tycons:
532 -- * tycons which have converted versions are mapped to True
533 -- * tycons which are not changed by vectorisation are mapped to False
534 -- * tycons which can't be converted are not elements of the map
536 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
537 classifyTyCons = classify [] []
539 classify conv keep cs [] = (conv, keep)
540 classify conv keep cs ((tcs, ds) : rs)
541 | can_convert && must_convert
542 = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
544 = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
546 = classify conv keep cs rs
548 refs = ds `delListFromUniqSet` tcs
550 can_convert = isNullUFM (refs `minusUFM` cs) && all convertable tcs
551 must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
553 convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
555 -- | Compute mutually recursive groups of tycons in topological order
557 tyConGroups :: [TyCon] -> [TyConGroup]
558 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
560 edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
561 , let ds = tyConsOfTyCon tc]
563 mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
564 mk_grp (CyclicSCC els) = (tcs, unionManyUniqSets dss)
566 (tcs, dss) = unzip els
568 tyConsOfTyCon :: TyCon -> UniqSet TyCon
570 = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
572 tyConsOfType :: Type -> UniqSet TyCon
574 | Just ty' <- coreView ty = tyConsOfType ty'
575 tyConsOfType (TyVarTy v) = emptyUniqSet
576 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
578 extend | isUnLiftedTyCon tc
579 || isTupleTyCon tc = id
581 | otherwise = (`addOneToUniqSet` tc)
583 tyConsOfType (AppTy a b) = tyConsOfType a `unionUniqSets` tyConsOfType b
584 tyConsOfType (FunTy a b) = (tyConsOfType a `unionUniqSets` tyConsOfType b)
585 `addOneToUniqSet` funTyCon
586 tyConsOfType (ForAllTy _ ty) = tyConsOfType ty
587 tyConsOfType other = pprPanic "ClosureConv.tyConsOfType" $ ppr other
589 tyConsOfTypes :: [Type] -> UniqSet TyCon
590 tyConsOfTypes = unionManyUniqSets . map tyConsOfType