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