Do not unnecessarily wrap array components
[ghc-hetmet.git] / compiler / vectorise / VectType.hs
1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2                    PAInstance, buildPADict )
3 where
4
5 #include "HsVersions.h"
6
7 import VectMonad
8 import VectUtils
9 import VectCore
10
11 import HscTypes          ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
12 import CoreSyn
13 import CoreUtils
14 import BuildTyCl
15 import DataCon
16 import TyCon
17 import Type
18 import TypeRep
19 import Coercion
20 import FamInstEnv        ( FamInst, mkLocalFamInst )
21 import InstEnv           ( Instance, mkLocalInstance, instanceDFunId )
22 import OccName
23 import MkId
24 import BasicTypes        ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
25 import Var               ( Var )
26 import Id                ( mkWildId )
27 import Name              ( Name, getOccName )
28 import NameEnv
29 import TysWiredIn        ( unitTy, unitTyCon, intTy, intDataCon, unitDataConId )
30 import TysPrim           ( intPrimTy )
31
32 import Unique
33 import UniqFM
34 import UniqSet
35 import Digraph           ( SCC(..), stronglyConnComp )
36
37 import Outputable
38
39 import Control.Monad  ( liftM, liftM2, zipWithM, zipWithM_, mapAndUnzipM )
40 import Data.List      ( inits, tails, zipWith4, zipWith5 )
41
42 -- ----------------------------------------------------------------------------
43 -- Types
44
45 vectTyCon :: TyCon -> VM TyCon
46 vectTyCon tc
47   | isFunTyCon tc        = builtin closureTyCon
48   | isBoxedTupleTyCon tc = return tc
49   | isUnLiftedTyCon tc   = return tc
50   | otherwise = do
51                   r <- lookupTyCon tc
52                   case r of
53                     Just tc' -> return tc'
54
55                     -- FIXME: just for now
56                     Nothing  -> pprTrace "ccTyCon:" (ppr tc) $ return tc
57
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 _ _)
66   = do
67       mdicts   <- mapM paDictArgType tyvars
68       mono_ty' <- vectType mono_ty
69       return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
70   where
71     (tyvars, mono_ty) = splitForAllTys ty
72
73 vectType ty = pprPanic "vectType:" (ppr ty)
74
75 -- ----------------------------------------------------------------------------
76 -- Type definitions
77
78 type TyConGroup = ([TyCon], UniqSet TyCon)
79
80 data PAInstance = PAInstance {
81                     painstDFun      :: Var
82                   , painstOrigTyCon :: TyCon
83                   , painstVectTyCon :: TyCon
84                   , painstArrTyCon  :: TyCon
85                   }
86
87 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
88 vectTypeEnv env
89   = do
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
96
97       let orig_tcs = keep_tcs ++ conv_tcs
98           vect_tcs  = keep_tcs ++ new_tcs
99
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
105                                                         vect_tcs
106                                                         repr_tcs
107                                                         parr_tcs
108                                                         dfuns)
109
110       let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
111
112       let new_env = extendTypeEnvList env
113                        (map ATyCon all_new_tcs
114                         ++ [ADataCon dc | tc <- all_new_tcs
115                                         , dc <- tyConDataCons tc])
116
117       return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
118   where
119     tycons = typeEnvTyCons env
120     groups = tyConGroups tycons
121
122     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
123
124     keep_tc tc = let dcs = tyConDataCons tc
125                  in
126                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
127
128
129 vectTyConDecls :: [TyCon] -> VM [TyCon]
130 vectTyConDecls tcs = fixV $ \tcs' ->
131   do
132     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
133     mapM vectTyConDecl tcs
134   where
135     lazy_zip [] _ = []
136     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
137
138 vectTyConDecl :: TyCon -> VM TyCon
139 vectTyConDecl tc
140   = do
141       name' <- cloneName mkVectTyConOcc name
142       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
143
144       liftDs $ buildAlgTyCon name'
145                              tyvars
146                              []           -- no stupid theta
147                              rhs'
148                              rec_flag     -- FIXME: is this ok?
149                              False        -- FIXME: no generics
150                              False        -- not GADT syntax
151                              Nothing      -- not a family instance
152   where
153     name   = tyConName tc
154     tyvars = tyConTyVars tc
155     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
156
157 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
158 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
159                            , is_enum   = is_enum
160                            })
161   = do
162       data_cons' <- mapM vectDataCon data_cons
163       zipWithM_ defDataCon data_cons data_cons'
164       return $ DataTyCon { data_cons = data_cons'
165                          , is_enum   = is_enum
166                          }
167
168 vectDataCon :: DataCon -> VM DataCon
169 vectDataCon dc
170   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
171   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
172   | otherwise
173   = do
174       name'    <- cloneName mkVectDataConOcc name
175       tycon'   <- vectTyCon tycon
176       arg_tys  <- mapM vectType rep_arg_tys
177
178       liftDs $ buildDataCon name'
179                             False           -- not infix
180                             (map (const NotMarkedStrict) arg_tys)
181                             []              -- no labelled fields
182                             univ_tvs
183                             []              -- no existential tvs for now
184                             []              -- no eq spec for now
185                             []              -- no context
186                             arg_tys
187                             tycon'
188   where
189     name        = dataConName dc
190     univ_tvs    = dataConUnivTyVars dc
191     rep_arg_tys = dataConRepArgTys dc
192     tycon       = dataConTyCon dc
193
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])
197
198 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
199 buildPReprTyCon orig_tc vect_tc
200   = do
201       name     <- cloneName mkPReprTyConOcc (tyConName orig_tc)
202       rhs_ty   <- buildPReprType vect_tc
203       prepr_tc <- builtin preprTyCon
204       liftDs $ buildSynTyCon name
205                              tyvars
206                              (SynonymTyCon rhs_ty)
207                              (Just $ mk_fam_inst prepr_tc vect_tc)
208   where
209     tyvars = tyConTyVars vect_tc
210
211
212 data Repr = ProdRepr {
213               prod_components   :: [Type]
214             , prod_tycon        :: TyCon
215             , prod_data_con     :: DataCon
216             , prod_arr_tycon    :: TyCon
217             , prod_arr_data_con :: DataCon
218             }
219
220           | SumRepr {
221               sum_components    :: [Repr]
222             , sum_tycon         :: TyCon
223             , sum_arr_tycon     :: TyCon
224             , sum_arr_data_con  :: DataCon
225             }
226
227           | IdRepr Type
228
229 mkProduct :: [Type] -> VM Repr
230 mkProduct tys
231   = do
232       tycon <- builtin (prodTyCon arity)
233       let [data_con] = tyConDataCons tycon
234
235       (arr_tycon, _) <- parrayReprTyCon $ mkTyConApp tycon tys
236       let [arr_data_con] = tyConDataCons arr_tycon
237
238       return $ ProdRepr {
239                  prod_components   = tys
240                , prod_tycon        = tycon
241                , prod_data_con     = data_con
242                , prod_arr_tycon    = arr_tycon
243                , prod_arr_data_con = arr_data_con
244                }
245   where
246     arity = length tys
247
248 mkSubProduct :: [Type] -> VM Repr
249 mkSubProduct [ty] = return $ IdRepr ty
250 mkSubProduct tys  = mkProduct tys
251
252 mkSum :: [Repr] -> VM Repr
253 mkSum [repr] = return repr
254 mkSum reprs
255   = do
256       tycon <- builtin (sumTyCon arity)
257       (arr_tycon, _) <- parrayReprTyCon
258                       . mkTyConApp tycon
259                       $ map reprType reprs
260
261       let [arr_data_con] = tyConDataCons arr_tycon
262
263       return $ SumRepr {
264                  sum_components   = reprs
265                , sum_tycon        = tycon
266                , sum_arr_tycon    = arr_tycon
267                , sum_arr_data_con = arr_data_con
268                }
269   where
270     arity = length reprs
271
272 reprType :: Repr -> Type
273 reprType (ProdRepr { prod_tycon = tycon, prod_components = tys })
274   = mkTyConApp tycon tys
275 reprType (SumRepr { sum_tycon = tycon, sum_components = reprs })
276   = mkTyConApp tycon (map reprType reprs)
277 reprType (IdRepr ty) = ty
278
279 arrReprType :: Repr -> VM Type
280 arrReprType = mkPArrayType . reprType
281
282 arrShapeTys :: Repr -> VM [Type]
283 arrShapeTys (SumRepr  {})
284   = do
285       int_arr <- builtin parrayIntPrimTyCon
286       return [intPrimTy, mkTyConApp int_arr [], mkTyConApp int_arr []]
287 arrShapeTys (ProdRepr {}) = return [intPrimTy]
288 arrShapeTys (IdRepr _)    = return []
289
290 arrShapeVars :: Repr -> VM [Var]
291 arrShapeVars repr = mapM (newLocalVar FSLIT("sh")) =<< arrShapeTys repr
292
293 replicateShape :: Repr -> CoreExpr -> CoreExpr -> VM [CoreExpr]
294 replicateShape (ProdRepr {}) len _ = return [len]
295 replicateShape (SumRepr {})  len tag
296   = do
297       rep <- builtin replicatePAIntPrimVar
298       up  <- builtin upToPAIntPrimVar
299       return [len, Var rep `mkApps` [len, tag], Var up `App` len]
300 replicateShape (IdRepr _) _ _ = return []
301
302 arrReprElemTys :: Repr -> [[Type]]
303 arrReprElemTys (SumRepr { sum_components = prods })
304   = map arrProdElemTys prods
305 arrReprElemTys prod@(ProdRepr {})
306   = [arrProdElemTys prod]
307 arrReprElemTys (IdRepr ty) = [[ty]]
308
309 arrProdElemTys (ProdRepr { prod_components = [] })
310   = [unitTy]
311 arrProdElemTys (ProdRepr { prod_components = tys })
312   = tys
313 arrProdElemTys (IdRepr ty) = [ty]
314
315 arrReprTys :: Repr -> VM [[Type]]
316 arrReprTys = mapM (mapM mkPArrayType) . arrReprElemTys
317
318 arrReprVars :: Repr -> VM [[Var]]
319 arrReprVars repr
320   = mapM (mapM (newLocalVar FSLIT("rs"))) =<< arrReprTys repr
321
322 mkRepr :: TyCon -> VM Repr
323 mkRepr vect_tc
324   | [tys] <- rep_tys = mkProduct tys
325   | otherwise        = mkSum =<< mapM mkSubProduct rep_tys
326   where
327     rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc
328
329 buildPReprType :: TyCon -> VM Type
330 buildPReprType = liftM reprType . mkRepr
331
332 buildToPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
333 buildToPRepr repr vect_tc prepr_tc _
334   = do
335       arg    <- newLocalVar FSLIT("x") arg_ty
336       result <- to_repr repr (Var arg)
337
338       return . Lam arg
339              . wrapFamInstBody prepr_tc var_tys
340              $ result
341   where
342     var_tys = mkTyVarTys $ tyConTyVars vect_tc
343     arg_ty  = mkTyConApp vect_tc var_tys
344     res_ty  = reprType repr
345
346     cons    = tyConDataCons vect_tc
347     [con]   = cons
348
349     to_repr (SumRepr { sum_components = prods
350                      , sum_tycon      = tycon })
351             expr
352       = do
353           (vars, bodies) <- mapAndUnzipM prod_alt prods
354           return . Case expr (mkWildId (exprType expr)) res_ty
355                  $ zipWith4 mk_alt cons vars (tyConDataCons tycon) bodies
356       where
357         mk_alt con vars sum_con body
358           = (DataAlt con, vars, mkConApp sum_con (ty_args ++ [body]))
359
360         ty_args = map (Type . reprType) prods
361
362     to_repr prod expr
363       = do
364           (vars, body) <- prod_alt prod
365           return $ Case expr (mkWildId (exprType expr)) res_ty
366                    [(DataAlt con, vars, body)]
367
368     prod_alt (ProdRepr { prod_components = tys
369                        , prod_data_con   = data_con })
370       = do
371           vars <- mapM (newLocalVar FSLIT("r")) tys
372           return (vars, mkConApp data_con (map Type tys ++ map Var vars))
373
374     prod_alt (IdRepr ty)
375       = do
376           var <- newLocalVar FSLIT("y") ty
377           return ([var], Var var)
378
379 buildFromPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
380 buildFromPRepr repr vect_tc prepr_tc _
381   = do
382       arg_ty <- mkPReprType res_ty
383       arg    <- newLocalVar FSLIT("x") arg_ty
384
385       liftM (Lam arg)
386            . from_repr repr
387            $ unwrapFamInstScrut prepr_tc var_tys (Var arg)
388   where
389     var_tys = mkTyVarTys $ tyConTyVars vect_tc
390     res_ty  = mkTyConApp vect_tc var_tys
391
392     cons    = map (`mkConApp` map Type var_tys) (tyConDataCons vect_tc)
393     [con]   = cons
394
395     from_repr repr@(SumRepr { sum_components = prods
396                             , sum_tycon      = tycon })
397               expr
398       = do
399           vars   <- mapM (newLocalVar FSLIT("x")) (map reprType prods)
400           bodies <- sequence . zipWith3 from_prod prods cons
401                              $ map Var vars
402           return . Case expr (mkWildId (reprType repr)) res_ty
403                  $ zipWith3 sum_alt (tyConDataCons tycon) vars bodies
404       where
405         sum_alt data_con var body = (DataAlt data_con, [var], body)
406
407     from_repr repr expr = from_prod repr con expr
408
409     from_prod prod@(ProdRepr { prod_components = tys
410                              , prod_data_con   = data_con })
411               con
412               expr
413       = do
414           vars <- mapM (newLocalVar FSLIT("y")) tys
415           return $ Case expr (mkWildId (reprType prod)) res_ty
416                    [(DataAlt data_con, vars, con `mkVarApps` vars)]
417
418     from_prod (IdRepr _) con expr
419        = return $ con `App` expr
420
421 buildToArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
422 buildToArrPRepr repr vect_tc prepr_tc arr_tc
423   = do
424       arg_ty     <- mkPArrayType el_ty
425       arg        <- newLocalVar FSLIT("xs") arg_ty
426
427       res_ty     <- mkPArrayType (reprType repr)
428
429       shape_vars <- arrShapeVars repr
430       repr_vars  <- arrReprVars  repr
431
432       parray_co  <- mkBuiltinCo parrayTyCon
433
434       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
435           co           = mkAppCoercion parray_co
436                        . mkSymCoercion
437                        $ mkTyConApp repr_co var_tys
438
439           scrut   = unwrapFamInstScrut arr_tc var_tys (Var arg)
440
441       result <- to_repr shape_vars repr_vars repr
442
443       return . Lam arg
444              . mkCoerce co
445              $ Case scrut (mkWildId (mkTyConApp arr_tc var_tys)) res_ty
446                [(DataAlt arr_dc, shape_vars ++ concat repr_vars, result)]
447   where
448     var_tys = mkTyVarTys $ tyConTyVars vect_tc
449     el_ty   = mkTyConApp vect_tc var_tys
450
451     [arr_dc] = tyConDataCons arr_tc
452
453     to_repr shape_vars@(len_var : _)
454             repr_vars
455             (SumRepr { sum_components   = prods
456                      , sum_arr_tycon    = tycon
457                      , sum_arr_data_con = data_con })
458       = do
459           exprs <- zipWithM to_prod repr_vars prods
460
461           return . wrapFamInstBody tycon tys
462                  . mkConApp data_con
463                  $ map Type tys ++ map Var shape_vars ++ exprs
464       where
465         tys = map reprType prods
466
467     to_repr [len_var]
468             [repr_vars]
469             (ProdRepr { prod_components   = tys
470                       , prod_arr_tycon    = tycon
471                       , prod_arr_data_con = data_con })
472        = return . wrapFamInstBody tycon tys
473                 . mkConApp data_con
474                 $ map Type tys ++ map Var (len_var : repr_vars)
475
476     to_prod repr_vars@(r : _)
477             (ProdRepr { prod_components   = tys
478                       , prod_arr_tycon    = tycon
479                       , prod_arr_data_con = data_con })
480       = do
481           len <- lengthPA (Var r)
482           return . wrapFamInstBody tycon tys
483                  . mkConApp data_con
484                  $ map Type tys ++ len : map Var repr_vars
485
486     to_prod [var] (IdRepr ty)
487       = return (Var var)
488
489 buildFromArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
490 buildFromArrPRepr repr vect_tc prepr_tc arr_tc
491   = do
492       arg_ty     <- mkPArrayType =<< mkPReprType el_ty
493       arg        <- newLocalVar FSLIT("xs") arg_ty
494
495       res_ty     <- mkPArrayType el_ty
496
497       shape_vars <- arrShapeVars repr
498       repr_vars  <- arrReprVars  repr
499
500       parray_co  <- mkBuiltinCo parrayTyCon
501
502       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
503           co           = mkAppCoercion parray_co
504                        $ mkTyConApp repr_co var_tys
505
506           scrut  = mkCoerce co (Var arg)
507
508           result = wrapFamInstBody arr_tc var_tys
509                  . mkConApp arr_dc
510                  $ map Type var_tys ++ map Var (shape_vars ++ concat repr_vars)
511
512       liftM (Lam arg)
513             (from_repr repr scrut shape_vars repr_vars res_ty result)
514   where
515     var_tys = mkTyVarTys $ tyConTyVars vect_tc
516     el_ty   = mkTyConApp vect_tc var_tys
517
518     [arr_dc] = tyConDataCons arr_tc
519
520     from_repr (SumRepr { sum_components   = prods
521                        , sum_arr_tycon    = tycon
522                        , sum_arr_data_con = data_con })
523               expr
524               shape_vars
525               repr_vars
526               res_ty
527               body
528       = do
529           vars <- mapM (newLocalVar FSLIT("xs")) =<< mapM arrReprType prods
530           result <- go prods repr_vars vars body
531
532           let scrut = unwrapFamInstScrut tycon ty_args expr
533           return . Case scrut (mkWildId scrut_ty) res_ty
534                  $ [(DataAlt data_con, shape_vars ++ vars, result)]
535       where
536         ty_args  = map reprType prods
537         scrut_ty = mkTyConApp tycon ty_args
538
539         go [] [] [] body = return body
540         go (prod : prods) (repr_vars : rss) (var : vars) body
541           = do
542               shape_vars <- mapM (newLocalVar FSLIT("s")) =<< arrShapeTys prod
543
544               from_prod prod (Var var) shape_vars repr_vars res_ty
545                 =<< go prods rss vars body
546
547     from_repr repr expr shape_vars [repr_vars] res_ty body
548       = from_prod repr expr shape_vars repr_vars res_ty body
549
550     from_prod prod@(ProdRepr { prod_components = tys
551                              , prod_arr_tycon  = tycon
552                              , prod_arr_data_con = data_con })
553               expr
554               shape_vars
555               repr_vars
556               res_ty
557               body
558       = do
559           let scrut    = unwrapFamInstScrut tycon tys expr
560               scrut_ty = mkTyConApp tycon tys
561           ty <- arrReprType prod
562
563           return $ Case scrut (mkWildId scrut_ty) res_ty
564                    [(DataAlt data_con, shape_vars ++ repr_vars, body)]
565
566     from_prod (IdRepr ty)
567               expr
568               shape_vars
569               [repr_var]
570               res_ty
571               body
572       = return $ Let (NonRec repr_var expr) body
573
574 buildPRDictRepr :: Repr -> VM CoreExpr
575 buildPRDictRepr (IdRepr ty) = mkPR ty
576 buildPRDictRepr (ProdRepr {
577                    prod_components = tys
578                  , prod_tycon      = tycon
579                  })
580   = do
581       prs  <- mapM mkPR tys
582       dfun <- prDFunOfTyCon tycon
583       return $ dfun `mkTyApps` tys `mkApps` prs
584
585 buildPRDictRepr (SumRepr {
586                    sum_components = prods
587                  , sum_tycon      = tycon })
588   = do
589       prs  <- mapM buildPRDictRepr prods
590       dfun <- prDFunOfTyCon tycon
591       return $ dfun `mkTyApps` map reprType prods `mkApps` prs
592
593 buildPRDict :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
594 buildPRDict repr vect_tc prepr_tc _
595   = do
596       dict  <- buildPRDictRepr repr
597
598       pr_co <- mkBuiltinCo prTyCon
599       let co = mkAppCoercion pr_co
600              . mkSymCoercion
601              $ mkTyConApp arg_co var_tys
602
603       return $ mkCoerce co dict
604   where
605     var_tys = mkTyVarTys $ tyConTyVars vect_tc
606
607     Just arg_co = tyConFamilyCoercion_maybe prepr_tc
608
609 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
610 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
611   do
612     name'  <- cloneName mkPArrayTyConOcc orig_name
613     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
614     parray <- builtin parrayTyCon
615
616     liftDs $ buildAlgTyCon name'
617                            tyvars
618                            []          -- no stupid theta
619                            rhs
620                            rec_flag    -- FIXME: is this ok?
621                            False       -- FIXME: no generics
622                            False       -- not GADT syntax
623                            (Just $ mk_fam_inst parray vect_tc)
624   where
625     orig_name = tyConName orig_tc
626     tyvars = tyConTyVars vect_tc
627     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
628
629
630 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
631 buildPArrayTyConRhs orig_name vect_tc repr_tc
632   = do
633       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
634       return $ DataTyCon { data_cons = [data_con], is_enum = False }
635
636 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
637 buildPArrayDataCon orig_name vect_tc repr_tc
638   = do
639       dc_name  <- cloneName mkPArrayDataConOcc orig_name
640       repr     <- mkRepr vect_tc
641
642       shape_tys <- arrShapeTys repr
643       repr_tys  <- arrReprTys  repr
644
645       let tys = shape_tys ++ concat repr_tys
646
647       liftDs $ buildDataCon dc_name
648                             False                  -- not infix
649                             (map (const NotMarkedStrict) tys)
650                             []                     -- no field labels
651                             (tyConTyVars vect_tc)
652                             []                     -- no existentials
653                             []                     -- no eq spec
654                             []                     -- no context
655                             tys
656                             repr_tc
657
658 mkPADFun :: TyCon -> VM Var
659 mkPADFun vect_tc
660   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
661
662 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
663                    -> VM [(Var, CoreExpr)]
664 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
665   = do
666       repr  <- mkRepr vect_tc
667       vectDataConWorkers repr orig_tc vect_tc arr_tc
668       dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
669       binds <- takeHoisted
670       return $ (dfun, dict) : binds
671   where
672     orig_dcs = tyConDataCons orig_tc
673     vect_dcs = tyConDataCons vect_tc
674     [arr_dc] = tyConDataCons arr_tc
675
676     repr_tys = map dataConRepArgTys vect_dcs
677
678 vectDataConWorkers :: Repr -> TyCon -> TyCon -> TyCon
679                    -> VM ()
680 vectDataConWorkers repr orig_tc vect_tc arr_tc
681   = do
682       bs <- sequence
683           . zipWith3 def_worker  (tyConDataCons orig_tc) rep_tys
684           $ zipWith4 mk_data_con (tyConDataCons vect_tc)
685                                  rep_tys
686                                  (inits arr_tys)
687                                  (tail $ tails arr_tys)
688       mapM_ (uncurry hoistBinding) bs
689   where
690     tyvars   = tyConTyVars vect_tc
691     var_tys  = mkTyVarTys tyvars
692     ty_args  = map Type var_tys
693
694     res_ty   = mkTyConApp vect_tc var_tys
695
696     rep_tys  = map dataConRepArgTys $ tyConDataCons vect_tc
697     arr_tys  = arrReprElemTys repr
698
699     [arr_dc] = tyConDataCons arr_tc
700
701     mk_data_con con tys pre post
702       = liftM2 (,) (vect_data_con con)
703                    (lift_data_con tys (concat pre)
704                                       (concat post)
705                                       (mkDataConTag con))
706
707     vect_data_con con = return $ mkConApp con ty_args
708     lift_data_con tys pre_tys post_tys tag
709       = do
710           len  <- builtin liftingContext
711           args <- mapM (newLocalVar FSLIT("xs"))
712                   =<< mapM mkPArrayType tys
713
714           shape <- replicateShape repr (Var len) tag
715           repr  <- mk_arr_repr (Var len) (map Var args)
716
717           pre   <- mapM emptyPA pre_tys
718           post  <- mapM emptyPA post_tys
719
720           return . mkLams (len : args)
721                  . wrapFamInstBody arr_tc var_tys
722                  . mkConApp arr_dc
723                  $ ty_args ++ shape ++ pre ++ repr ++ post
724
725     mk_arr_repr len []
726       = do
727           units <- replicatePA len (Var unitDataConId)
728           return [units]
729
730     mk_arr_repr len arrs = return arrs
731
732     def_worker data_con arg_tys mk_body
733       = do
734           body <- closedV
735                 . inBind orig_worker
736                 . polyAbstract tyvars $ \abstract ->
737                   liftM (abstract . vectorised)
738                 $ buildClosures tyvars [] arg_tys res_ty mk_body
739
740           vect_worker <- cloneId mkVectOcc orig_worker (exprType body)
741           defGlobalVar orig_worker vect_worker
742           return (vect_worker, body)
743       where
744         orig_worker = dataConWorkId data_con
745
746 buildPADict :: Repr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
747 buildPADict repr vect_tc prepr_tc arr_tc dfun
748   = polyAbstract tvs $ \abstract ->
749     do
750       meth_binds <- mapM (mk_method repr) paMethods
751       let meth_exprs = map (Var . fst) meth_binds
752
753       pa_dc <- builtin paDataCon
754       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
755           body = Let (Rec meth_binds) dict
756       return . mkInlineMe $ abstract body
757   where
758     tvs = tyConTyVars arr_tc
759     arg_tys = mkTyVarTys tvs
760
761     mk_method repr (name, build)
762       = localV
763       $ do
764           body <- build repr vect_tc prepr_tc arr_tc
765           var  <- newLocalVar name (exprType body)
766           return (var, mkInlineMe body)
767
768 paMethods = [(FSLIT("toPRepr"),      buildToPRepr),
769              (FSLIT("fromPRepr"),    buildFromPRepr),
770              (FSLIT("toArrPRepr"),   buildToArrPRepr),
771              (FSLIT("fromArrPRepr"), buildFromArrPRepr),
772              (FSLIT("dictPRepr"),    buildPRDict)]
773
774 -- | Split the given tycons into two sets depending on whether they have to be
775 -- converted (first list) or not (second list). The first argument contains
776 -- information about the conversion status of external tycons:
777 --
778 --   * tycons which have converted versions are mapped to True
779 --   * tycons which are not changed by vectorisation are mapped to False
780 --   * tycons which can't be converted are not elements of the map
781 --
782 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
783 classifyTyCons = classify [] []
784   where
785     classify conv keep cs [] = (conv, keep)
786     classify conv keep cs ((tcs, ds) : rs)
787       | can_convert && must_convert
788         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
789       | can_convert
790         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
791       | otherwise
792         = classify conv keep cs rs
793       where
794         refs = ds `delListFromUniqSet` tcs
795
796         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
797         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
798
799         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
800
801 -- | Compute mutually recursive groups of tycons in topological order
802 --
803 tyConGroups :: [TyCon] -> [TyConGroup]
804 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
805   where
806     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
807                                 , let ds = tyConsOfTyCon tc]
808
809     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
810     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
811       where
812         (tcs, dss) = unzip els
813
814 tyConsOfTyCon :: TyCon -> UniqSet TyCon
815 tyConsOfTyCon
816   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
817
818 tyConsOfType :: Type -> UniqSet TyCon
819 tyConsOfType ty
820   | Just ty' <- coreView ty    = tyConsOfType ty'
821 tyConsOfType (TyVarTy v)       = emptyUniqSet
822 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
823   where
824     extend | isUnLiftedTyCon tc
825            || isTupleTyCon   tc = id
826
827            | otherwise          = (`addOneToUniqSet` tc)
828
829 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
830 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
831                                  `addOneToUniqSet` funTyCon
832 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
833 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
834
835 tyConsOfTypes :: [Type] -> UniqSet TyCon
836 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
837