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