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