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