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