92a19d562c9c6271cf247e77bf812026e6716280
[ghc-hetmet.git] / compiler / vectorise / Vectorise.hs
1
2 module Vectorise( vectorise )
3 where
4
5 import VectMonad
6 import VectUtils
7 import VectType
8 import VectCore
9
10 import DynFlags
11 import HscTypes hiding      ( MonadThings(..) )
12
13 import Module               ( PackageId )
14 import CoreLint             ( showPass, endPass )
15 import CoreSyn
16 import CoreUtils
17 import CoreFVs
18 import SimplMonad           ( SimplCount, zeroSimplCount )
19 import Rules                ( RuleBase )
20 import DataCon
21 import TyCon
22 import Type
23 import FamInstEnv           ( extendFamInstEnvList )
24 import Var
25 import VarEnv
26 import VarSet
27 import Id
28 import OccName
29
30 import DsMonad
31
32 import Literal              ( Literal, mkMachInt )
33 import TysWiredIn
34
35 import Outputable
36 import FastString
37 import Control.Monad        ( liftM, liftM2, zipWithM )
38 import Data.List            ( sortBy, unzip4 )
39
40 vectorise :: PackageId -> HscEnv -> UniqSupply -> RuleBase -> ModGuts
41           -> IO (SimplCount, ModGuts)
42 vectorise backend hsc_env _ _ guts
43   = do
44       showPass dflags "Vectorisation"
45       eps <- hscEPS hsc_env
46       let info = hptVectInfo hsc_env `plusVectInfo` eps_vect_info eps
47       Just (info', guts') <- initV backend hsc_env guts info (vectModule guts)
48       endPass dflags "Vectorisation" Opt_D_dump_vect (mg_binds guts')
49       return (zeroSimplCount dflags, guts' { mg_vect_info = info' })
50   where
51     dflags = hsc_dflags hsc_env
52
53 vectModule :: ModGuts -> VM ModGuts
54 vectModule guts
55   = do
56       (types', fam_insts, tc_binds) <- vectTypeEnv (mg_types guts)
57
58       let fam_inst_env' = extendFamInstEnvList (mg_fam_inst_env guts) fam_insts
59       updGEnv (setFamInstEnv fam_inst_env')
60
61       -- dicts   <- mapM buildPADict pa_insts
62       -- workers <- mapM vectDataConWorkers pa_insts
63       binds'  <- mapM vectTopBind (mg_binds guts)
64       return $ guts { mg_types        = types'
65                     , mg_binds        = Rec tc_binds : binds'
66                     , mg_fam_inst_env = fam_inst_env'
67                     , mg_fam_insts    = mg_fam_insts guts ++ fam_insts
68                     }
69
70 vectTopBind :: CoreBind -> VM CoreBind
71 vectTopBind b@(NonRec var expr)
72   = do
73       var'  <- vectTopBinder var
74       expr' <- vectTopRhs var expr
75       hs    <- takeHoisted
76       cexpr <- tryConvert var var' expr
77       return . Rec $ (var, cexpr) : (var', expr') : hs
78   `orElseV`
79     return b
80
81 vectTopBind b@(Rec bs)
82   = do
83       vars'  <- mapM vectTopBinder vars
84       exprs' <- zipWithM vectTopRhs vars exprs
85       hs     <- takeHoisted
86       cexprs <- sequence $ zipWith3 tryConvert vars vars' exprs
87       return . Rec $ zip vars cexprs ++ zip vars' exprs' ++ hs
88   `orElseV`
89     return b
90   where
91     (vars, exprs) = unzip bs
92
93 vectTopBinder :: Var -> VM Var
94 vectTopBinder var
95   = do
96       vty  <- vectType (idType var)
97       var' <- cloneId mkVectOcc var vty
98       defGlobalVar var var'
99       return var'
100
101 vectTopRhs :: Var -> CoreExpr -> VM CoreExpr
102 vectTopRhs var expr
103   = do
104       closedV . liftM vectorised
105               . inBind var
106               $ vectPolyExpr (freeVars expr)
107
108 tryConvert :: Var -> Var -> CoreExpr -> VM CoreExpr
109 tryConvert var vect_var rhs
110   = fromVect (idType var) (Var vect_var) `orElseV` return rhs
111
112 -- ----------------------------------------------------------------------------
113 -- Bindings
114
115 vectBndr :: Var -> VM VVar
116 vectBndr v
117   = do
118       (vty, lty) <- vectAndLiftType (idType v)
119       let vv = v `Id.setIdType` vty
120           lv = v `Id.setIdType` lty
121       updLEnv (mapTo vv lv)
122       return (vv, lv)
123   where
124     mapTo vv lv env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv) }
125
126 vectBndrNew :: Var -> FastString -> VM VVar
127 vectBndrNew v fs
128   = do
129       vty <- vectType (idType v)
130       vv  <- newLocalVVar fs vty
131       updLEnv (upd vv)
132       return vv
133   where
134     upd vv env = env { local_vars = extendVarEnv (local_vars env) v vv }
135
136 vectBndrIn :: Var -> VM a -> VM (VVar, a)
137 vectBndrIn v p
138   = localV
139   $ do
140       vv <- vectBndr v
141       x <- p
142       return (vv, x)
143
144 vectBndrNewIn :: Var -> FastString -> VM a -> VM (VVar, a)
145 vectBndrNewIn v fs p
146   = localV
147   $ do
148       vv <- vectBndrNew v fs
149       x  <- p
150       return (vv, x)
151
152 vectBndrsIn :: [Var] -> VM a -> VM ([VVar], a)
153 vectBndrsIn vs p
154   = localV
155   $ do
156       vvs <- mapM vectBndr vs
157       x <- p
158       return (vvs, x)
159
160 -- ----------------------------------------------------------------------------
161 -- Expressions
162
163 vectVar :: Var -> VM VExpr
164 vectVar v
165   = do
166       r <- lookupVar v
167       case r of
168         Local (vv,lv) -> return (Var vv, Var lv)
169         Global vv     -> do
170                            let vexpr = Var vv
171                            lexpr <- liftPA vexpr
172                            return (vexpr, lexpr)
173
174 vectPolyVar :: Var -> [Type] -> VM VExpr
175 vectPolyVar v tys
176   = do
177       vtys <- mapM vectType tys
178       r <- lookupVar v
179       case r of
180         Local (vv, lv) -> liftM2 (,) (polyApply (Var vv) vtys)
181                                      (polyApply (Var lv) vtys)
182         Global poly    -> do
183                             vexpr <- polyApply (Var poly) vtys
184                             lexpr <- liftPA vexpr
185                             return (vexpr, lexpr)
186
187 vectLiteral :: Literal -> VM VExpr
188 vectLiteral lit
189   = do
190       lexpr <- liftPA (Lit lit)
191       return (Lit lit, lexpr)
192
193 vectPolyExpr :: CoreExprWithFVs -> VM VExpr
194 vectPolyExpr (_, AnnNote note expr)
195   = liftM (vNote note) $ vectPolyExpr expr
196 vectPolyExpr expr
197   = polyAbstract tvs $ \abstract ->
198     do
199       mono' <- vectExpr mono
200       return $ mapVect abstract mono'
201   where
202     (tvs, mono) = collectAnnTypeBinders expr
203
204 vectExpr :: CoreExprWithFVs -> VM VExpr
205 vectExpr (_, AnnType ty)
206   = liftM vType (vectType ty)
207
208 vectExpr (_, AnnVar v) = vectVar v
209
210 vectExpr (_, AnnLit lit) = vectLiteral lit
211
212 vectExpr (_, AnnNote note expr)
213   = liftM (vNote note) (vectExpr expr)
214
215 vectExpr e@(_, AnnApp _ arg)
216   | isAnnTypeArg arg
217   = vectTyAppExpr fn tys
218   where
219     (fn, tys) = collectAnnTypeArgs e
220
221 vectExpr (_, AnnApp (_, AnnVar v) (_, AnnLit lit))
222   | Just con <- isDataConId_maybe v
223   , is_special_con con
224   = do
225       let vexpr = App (Var v) (Lit lit)
226       lexpr <- liftPA vexpr
227       return (vexpr, lexpr)
228   where
229     is_special_con con = con `elem` [intDataCon, floatDataCon, doubleDataCon]
230
231
232 vectExpr (_, AnnApp fn arg)
233   = do
234       arg_ty' <- vectType arg_ty
235       res_ty' <- vectType res_ty
236       fn'     <- vectExpr fn
237       arg'    <- vectExpr arg
238       mkClosureApp arg_ty' res_ty' fn' arg'
239   where
240     (arg_ty, res_ty) = splitFunTy . exprType $ deAnnotate fn
241
242 vectExpr (_, AnnCase scrut bndr ty alts)
243   | Just (tycon, ty_args) <- splitTyConApp_maybe scrut_ty
244   , isAlgTyCon tycon
245   = vectAlgCase tycon ty_args scrut bndr ty alts
246   where
247     scrut_ty = exprType (deAnnotate scrut)
248
249 vectExpr (_, AnnLet (AnnNonRec bndr rhs) body)
250   = do
251       vrhs <- localV . inBind bndr $ vectPolyExpr rhs
252       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
253       return $ vLet (vNonRec vbndr vrhs) vbody
254
255 vectExpr (_, AnnLet (AnnRec bs) body)
256   = do
257       (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs
258                                 $ liftM2 (,)
259                                   (zipWithM vect_rhs bndrs rhss)
260                                   (vectPolyExpr body)
261       return $ vLet (vRec vbndrs vrhss) vbody
262   where
263     (bndrs, rhss) = unzip bs
264
265     vect_rhs bndr rhs = localV
266                       . inBind bndr
267                       $ vectExpr rhs
268
269 vectExpr e@(fvs, AnnLam bndr _)
270   | isId bndr = vectLam fvs bs body
271   where
272     (bs,body) = collectAnnValBinders e
273
274 vectExpr e = cantVectorise "Can't vectorise expression" (ppr $ deAnnotate e)
275
276 vectLam :: VarSet -> [Var] -> CoreExprWithFVs -> VM VExpr
277 vectLam fvs bs body
278   = do
279       tyvars <- localTyVars
280       (vs, vvs) <- readLEnv $ \env ->
281                    unzip [(var, vv) | var <- varSetElems fvs
282                                     , Just vv <- [lookupVarEnv (local_vars env) var]]
283
284       arg_tys <- mapM (vectType . idType) bs
285       res_ty  <- vectType (exprType $ deAnnotate body)
286
287       buildClosures tyvars vvs arg_tys res_ty
288         . hoistPolyVExpr tyvars
289         $ do
290             lc <- builtin liftingContext
291             (vbndrs, vbody) <- vectBndrsIn (vs ++ bs)
292                                            (vectExpr body)
293             return $ vLams lc vbndrs vbody
294
295 vectTyAppExpr :: CoreExprWithFVs -> [Type] -> VM VExpr
296 vectTyAppExpr (_, AnnVar v) tys = vectPolyVar v tys
297 vectTyAppExpr e tys = cantVectorise "Can't vectorise expression"
298                         (ppr $ deAnnotate e `mkTyApps` tys)
299
300 -- We convert
301 --
302 --   case e :: t of v { ... }
303 --
304 -- to
305 --
306 --   V:    let v' = e in case v' of _ { ... }
307 --   L:    let v' = e in case v' `cast` ... of _ { ... }
308 --
309 -- When lifting, we have to do it this way because v must have the type
310 -- [:V(T):] but the scrutinee must be cast to the representation type. We also
311 -- have to handle the case where v is a wild var correctly.
312 --
313
314 -- FIXME: this is too lazy
315 vectAlgCase :: TyCon -> [Type] -> CoreExprWithFVs -> Var -> Type
316             -> [(AltCon, [Var], CoreExprWithFVs)]
317             -> VM VExpr
318 vectAlgCase _tycon _ty_args scrut bndr ty [(DEFAULT, [], body)]
319   = do
320       vscrut         <- vectExpr scrut
321       (vty, lty)     <- vectAndLiftType ty
322       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
323       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
324
325 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt _, [], body)]
326   = do
327       vscrut         <- vectExpr scrut
328       (vty, lty)     <- vectAndLiftType ty
329       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
330       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
331
332 vectAlgCase tycon _ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
333   = do
334       vect_tc    <- maybeV (lookupTyCon tycon)
335       (vty, lty) <- vectAndLiftType ty
336       vexpr      <- vectExpr scrut
337       (vbndr, (vbndrs, vbody)) <- vect_scrut_bndr
338                                 . vectBndrsIn bndrs
339                                 $ vectExpr body
340
341       (vscrut, arr_tc, _arg_tys) <- mkVScrut (vVar vbndr)
342       vect_dc <- maybeV (lookupDataCon dc)
343       let [arr_dc] = tyConDataCons arr_tc
344       repr <- mkRepr vect_tc
345       shape_bndrs <- arrShapeVars repr
346       return . vLet (vNonRec vbndr vexpr)
347              $ vCaseProd vscrut vty lty vect_dc arr_dc shape_bndrs vbndrs vbody
348   where
349     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
350                     | otherwise         = vectBndrIn bndr
351
352 vectAlgCase tycon _ty_args scrut bndr ty alts
353   = do
354       vect_tc     <- maybeV (lookupTyCon tycon)
355       (vty, lty)  <- vectAndLiftType ty
356       repr        <- mkRepr vect_tc
357       shape_bndrs <- arrShapeVars repr
358       (len, sel, indices) <- arrSelector repr (map Var shape_bndrs)
359
360       (vbndr, valts) <- vect_scrut_bndr $ mapM (proc_alt sel vty lty) alts'
361       let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
362
363       vexpr <- vectExpr scrut
364       (vscrut, arr_tc, _arg_tys) <- mkVScrut (vVar vbndr)
365       let [arr_dc] = tyConDataCons arr_tc
366
367       let (vect_scrut,  lift_scrut)  = vscrut
368           (vect_bodies, lift_bodies) = unzip vbodies
369
370       vdummy <- newDummyVar (exprType vect_scrut)
371       ldummy <- newDummyVar (exprType lift_scrut)
372       let vect_case = Case vect_scrut vdummy vty
373                            (zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
374
375       lbody <- combinePA vty len sel indices lift_bodies
376       let lift_case = Case lift_scrut ldummy lty
377                            [(DataAlt arr_dc, shape_bndrs ++ concat lift_bndrss,
378                              lbody)]
379
380       return . vLet (vNonRec vbndr vexpr)
381              $ (vect_case, lift_case)
382   where
383     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
384                     | otherwise         = vectBndrIn bndr
385
386     alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
387
388     cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
389     cmp DEFAULT       DEFAULT       = EQ
390     cmp DEFAULT       _             = LT
391     cmp _             DEFAULT       = GT
392     cmp _             _             = panic "vectAlgCase/cmp"
393
394     proc_alt sel vty lty (DataAlt dc, bndrs, body)
395       = do
396           vect_dc <- maybeV (lookupDataCon dc)
397           let tag = mkDataConTag vect_dc
398               fvs = freeVarsOf body `delVarSetList` bndrs
399           (vect_bndrs, lift_bndrs, vbody)
400             <- vect_alt_bndrs bndrs
401              $ \len -> packLiftingContext len sel tag fvs vty lty
402              $ vectExpr body
403
404           return (vect_dc, vect_bndrs, lift_bndrs, vbody)
405     proc_alt _ _ _ _ = panic "vectAlgCase/proc_alt"
406
407     vect_alt_bndrs [] p
408       = do
409           void_tc <- builtin voidTyCon
410           let void_ty = mkTyConApp void_tc []
411           arr_ty <- mkPArrayType void_ty
412           bndr   <- newLocalVar (fsLit "voids") arr_ty
413           len    <- lengthPA void_ty (Var bndr)
414           e      <- p len
415           return ([], [bndr], e)
416
417     vect_alt_bndrs bndrs p
418        = localV
419        $ do
420            vbndrs <- mapM vectBndr bndrs
421            let (vect_bndrs, lift_bndrs) = unzip vbndrs
422                vv : _ = vect_bndrs
423                lv : _ = lift_bndrs
424            len <- lengthPA (idType vv) (Var lv)
425            e   <- p len
426            return (vect_bndrs, lift_bndrs, e)
427
428     mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
429
430 packLiftingContext :: CoreExpr -> CoreExpr -> CoreExpr -> VarSet
431                    -> Type -> Type -> VM VExpr -> VM VExpr
432 packLiftingContext len shape tag fvs vty lty p
433   = do
434       select <- builtin selectPAIntPrimVar
435       let sel_expr = mkApps (Var select) [shape, tag]
436       sel_var <- newLocalVar (fsLit "sel#") (exprType sel_expr)
437       lc_var <- builtin liftingContext
438       localV $
439         do
440           bnds <- mapM (packFreeVar (Var lc_var) (Var sel_var))
441                 . filter isLocalId
442                 $ varSetElems fvs
443           (vexpr, lexpr) <- p
444           empty <- emptyPA vty
445           return (vexpr, Let (NonRec sel_var sel_expr)
446                          $ Case len lc_var lty
447                              [(DEFAULT, [], mkLets (concat bnds) lexpr),
448                               (LitAlt (mkMachInt 0), [], empty)])
449
450 packFreeVar :: CoreExpr -> CoreExpr -> Var -> VM [CoreBind]
451 packFreeVar len sel v
452   = do
453       r <- lookupVar v
454       case r of
455         Local (vv,lv) ->
456           do
457             lv' <- cloneVar lv
458             expr <- packPA (idType vv) (Var lv) len sel
459             updLEnv (upd vv lv')
460             return [(NonRec lv' expr)]
461
462         _  -> return []
463   where
464     upd vv lv' env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv') }
465