2 -- | Vectorisation of expressions.
7 import Vectorise.Type.Type
11 import Vectorise.Monad
12 import Vectorise.Builtins
25 import BasicTypes( isLoopBreaker )
35 -- | Vectorise a polymorphic expression.
37 vectPolyExpr :: Bool -- ^ When vectorising the RHS of a binding, whether that
38 -- binding is a loop breaker.
41 -> VM (Inline, Bool, VExpr)
42 vectPolyExpr loop_breaker recFns (_, AnnNote note expr)
43 = do (inline, isScalarFn, expr') <- vectPolyExpr loop_breaker recFns expr
44 return (inline, isScalarFn, vNote note expr')
45 vectPolyExpr loop_breaker recFns expr
47 arity <- polyArity tvs
48 polyAbstract tvs $ \args ->
50 (inline, isScalarFn, mono') <- vectFnExpr False loop_breaker recFns mono
51 return (addInlineArity inline arity, isScalarFn,
52 mapVect (mkLams $ tvs ++ args) mono')
54 (tvs, mono) = collectAnnTypeBinders expr
57 -- | Vectorise an expression.
58 vectExpr :: CoreExprWithFVs -> VM VExpr
59 vectExpr (_, AnnType ty)
60 = liftM vType (vectType ty)
62 vectExpr (_, AnnVar v)
65 vectExpr (_, AnnLit lit)
68 vectExpr (_, AnnNote note expr)
69 = liftM (vNote note) (vectExpr expr)
71 vectExpr e@(_, AnnApp _ arg)
73 = vectTyAppExpr fn tys
75 (fn, tys) = collectAnnTypeArgs e
77 vectExpr (_, AnnApp (_, AnnVar v) (_, AnnLit lit))
78 | Just con <- isDataConId_maybe v
81 let vexpr = App (Var v) (Lit lit)
85 is_special_con con = con `elem` [intDataCon, floatDataCon, doubleDataCon]
88 -- TODO: Avoid using closure application for dictionaries.
89 -- vectExpr (_, AnnApp fn arg)
90 -- | if is application of dictionary
91 -- just use regular app instead of closure app.
93 -- for lifted version.
94 -- do liftPD (sub a dNumber)
95 -- lift the result of the selection, not sub and dNumber seprately.
97 vectExpr (_, AnnApp fn arg)
99 arg_ty' <- vectType arg_ty
100 res_ty' <- vectType res_ty
105 mkClosureApp arg_ty' res_ty' fn' arg'
107 (arg_ty, res_ty) = splitFunTy . exprType $ deAnnotate fn
109 vectExpr (_, AnnCase scrut bndr ty alts)
110 | Just (tycon, ty_args) <- splitTyConApp_maybe scrut_ty
112 = vectAlgCase tycon ty_args scrut bndr ty alts
113 | otherwise = cantVectorise "Can't vectorise expression" (ppr scrut_ty)
115 scrut_ty = exprType (deAnnotate scrut)
117 vectExpr (_, AnnLet (AnnNonRec bndr rhs) body)
119 vrhs <- localV . inBind bndr . liftM (\(_,_,z)->z) $ vectPolyExpr False [] rhs
120 (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
121 return $ vLet (vNonRec vbndr vrhs) vbody
123 vectExpr (_, AnnLet (AnnRec bs) body)
125 (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs
127 (zipWithM vect_rhs bndrs rhss)
129 return $ vLet (vRec vbndrs vrhss) vbody
131 (bndrs, rhss) = unzip bs
133 vect_rhs bndr rhs = localV
135 . liftM (\(_,_,z)->z)
136 $ vectPolyExpr (isLoopBreaker $ idOccInfo bndr) [] rhs
138 vectExpr e@(_, AnnLam bndr _)
139 | isId bndr = liftM (\(_,_,z) ->z) $ vectFnExpr True False [] e
141 onlyIfV (isEmptyVarSet fvs) (vectScalarLam bs $ deAnnotate body)
142 `orElseV` vectLam True fvs bs body
144 (bs,body) = collectAnnValBinders e
147 vectExpr e = cantVectorise "Can't vectorise expression (vectExpr)" (ppr $ deAnnotate e)
149 -- | Vectorise an expression with an outer lambda abstraction.
151 vectFnExpr :: Bool -- ^ When the RHS of a binding, whether that binding should be inlined.
152 -> Bool -- ^ Whether the binding is a loop breaker.
154 -> CoreExprWithFVs -- ^ Expression to vectorise. Must have an outer `AnnLam`.
155 -> VM (Inline, Bool, VExpr)
156 vectFnExpr inline loop_breaker recFns e@(fvs, AnnLam bndr _)
157 | isId bndr = onlyIfV True -- (isEmptyVarSet fvs) -- we check for free variables later. TODO: clean up
158 (mark DontInline True . vectScalarLam bs recFns $ deAnnotate body)
159 `orElseV` mark inlineMe False (vectLam inline loop_breaker fvs bs body)
161 (bs,body) = collectAnnValBinders e
162 vectFnExpr _ _ _ e = mark DontInline False $ vectExpr e
164 mark :: Inline -> Bool -> VM a -> VM (Inline, Bool, a)
165 mark b isScalarFn p = do { x <- p; return (b, isScalarFn, x) }
168 -- | Vectorise a function where are the args have scalar type,
169 -- that is Int, Float, Double etc.
171 :: [Var] -- ^ Bound variables of function
173 -> CoreExpr -- ^ Function body.
176 vectScalarLam args recFns body
177 = do scalars' <- globalScalars
178 let scalars = unionVarSet (mkVarSet recFns) scalars'
179 onlyIfV (all is_prim_ty arg_tys
181 && is_scalar (extendVarSetList scalars args) body
182 && uses scalars body)
184 fn_var <- hoistExpr (fsLit "fn") (mkLams args body) DontInline
185 zipf <- zipScalars arg_tys res_ty
186 clo <- scalarClosure arg_tys res_ty (Var fn_var)
187 (zipf `App` Var fn_var)
188 clo_var <- hoistExpr (fsLit "clo") clo DontInline
189 lclo <- liftPD (Var clo_var)
190 return (Var clo_var, lclo)
192 arg_tys = map idType args
193 res_ty = exprType body
196 | Just (tycon, []) <- splitTyConApp_maybe ty
198 || tycon == floatTyCon
199 || tycon == doubleTyCon
203 cantbe_parr_expr expr = not $ maybe_parr_ty $ exprType expr
205 maybe_parr_ty ty = maybe_parr_ty' [] ty
207 maybe_parr_ty' _ ty | Nothing <- splitTyConApp_maybe ty = False -- TODO: is this really what we want to do with polym. types?
208 maybe_parr_ty' alreadySeen ty
209 | isPArrTyCon tycon = True
210 | isPrimTyCon tycon = False
211 | isAbstractTyCon tycon = True
212 | isFunTyCon tycon || isProductTyCon tycon || isTupleTyCon tycon = any (maybe_parr_ty' alreadySeen) args
213 | isDataTyCon tycon = any (maybe_parr_ty' alreadySeen) args ||
214 hasParrDataCon alreadySeen tycon
217 Just (tycon, args) = splitTyConApp_maybe ty
220 hasParrDataCon alreadySeen tycon
221 | tycon `elem` alreadySeen = False
223 any (maybe_parr_ty' $ tycon : alreadySeen) $ concat $ map dataConOrigArgTys $ tyConDataCons tycon
225 -- checks to make sure expression can't contain a non-scalar subexpression. Might err on the side of caution whenever
226 -- an external (non data constructor) variable is used, or anonymous data constructor
227 is_scalar vs e@(Var v)
228 | Just _ <- isDataConId_maybe v = cantbe_parr_expr e
229 | otherwise = cantbe_parr_expr e && (v `elemVarSet` vs)
230 is_scalar _ e@(Lit _) = cantbe_parr_expr e
232 is_scalar vs e@(App e1 e2) = cantbe_parr_expr e &&
233 is_scalar vs e1 && is_scalar vs e2
234 is_scalar vs e@(Let (NonRec b letExpr) body)
235 = cantbe_parr_expr e &&
236 is_scalar vs letExpr && is_scalar (extendVarSet vs b) body
237 is_scalar vs e@(Let (Rec bnds) body)
238 = let vs' = extendVarSetList vs (map fst bnds)
239 in cantbe_parr_expr e &&
240 all (is_scalar vs') (map snd bnds) && is_scalar vs' body
241 is_scalar vs e@(Case eC eId ty alts)
242 = let vs' = extendVarSet vs eId
243 in cantbe_parr_expr e &&
246 (all (is_scalar_alt vs') alts)
248 is_scalar _ _ = False
250 is_scalar_alt vs (_, bs, e)
251 = is_scalar (extendVarSetList vs bs) e
253 -- A scalar function has to actually compute something. Without the check,
254 -- we would treat (\(x :: Int) -> x) as a scalar function and lift it to
255 -- (map (\x -> x)) which is very bad. Normal lifting transforms it to
256 -- (\n# x -> x) which is what we want.
257 uses funs (Var v) = v `elemVarSet` funs
258 uses funs (App e1 e2) = uses funs e1 || uses funs e2
259 uses funs (Let (NonRec _b letExpr) body)
260 = uses funs letExpr || uses funs body
261 uses funs (Case e _eId _ty alts)
262 = uses funs e || any (uses_alt funs) alts
265 uses_alt funs (_, _bs, e)
268 -- | Vectorise a lambda abstraction.
270 :: Bool -- ^ When the RHS of a binding, whether that binding should be inlined.
271 -> Bool -- ^ Whether the binding is a loop breaker.
272 -> VarSet -- ^ The free variables in the body.
273 -> [Var] -- ^ Binding variables.
274 -> CoreExprWithFVs -- ^ Body of abstraction.
277 vectLam inline loop_breaker fvs bs body
278 = do tyvars <- localTyVars
279 (vs, vvs) <- readLEnv $ \env ->
280 unzip [(var, vv) | var <- varSetElems fvs
281 , Just vv <- [lookupVarEnv (local_vars env) var]]
283 arg_tys <- mapM (vectType . idType) bs
284 res_ty <- vectType (exprType $ deAnnotate body)
286 buildClosures tyvars vvs arg_tys res_ty
287 . hoistPolyVExpr tyvars (maybe_inline (length vs + length bs))
289 lc <- builtin liftingContext
290 (vbndrs, vbody) <- vectBndrsIn (vs ++ bs) (vectExpr body)
292 vbody' <- break_loop lc res_ty vbody
293 return $ vLams lc vbndrs vbody'
295 maybe_inline n | inline = Inline n
296 | otherwise = DontInline
298 break_loop lc ty (ve, le)
302 lty <- mkPDataType ty
303 return (ve, mkWildCase (Var lc) intPrimTy lty
305 (LitAlt (mkMachInt 0), [], empty)])
307 | otherwise = return (ve, le)
310 vectTyAppExpr :: CoreExprWithFVs -> [Type] -> VM VExpr
311 vectTyAppExpr (_, AnnVar v) tys = vectPolyVar v tys
312 vectTyAppExpr e tys = cantVectorise "Can't vectorise expression (vectTyExpr)"
313 (ppr $ deAnnotate e `mkTyApps` tys)
316 -- | Vectorise an algebraic case expression.
319 -- case e :: t of v { ... }
323 -- V: let v' = e in case v' of _ { ... }
324 -- L: let v' = e in case v' `cast` ... of _ { ... }
326 -- When lifting, we have to do it this way because v must have the type
327 -- [:V(T):] but the scrutinee must be cast to the representation type. We also
328 -- have to handle the case where v is a wild var correctly.
331 -- FIXME: this is too lazy
332 vectAlgCase :: TyCon -> [Type] -> CoreExprWithFVs -> Var -> Type
333 -> [(AltCon, [Var], CoreExprWithFVs)]
335 vectAlgCase _tycon _ty_args scrut bndr ty [(DEFAULT, [], body)]
337 vscrut <- vectExpr scrut
338 (vty, lty) <- vectAndLiftType ty
339 (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
340 return $ vCaseDEFAULT vscrut vbndr vty lty vbody
342 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt _, [], body)]
344 vscrut <- vectExpr scrut
345 (vty, lty) <- vectAndLiftType ty
346 (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
347 return $ vCaseDEFAULT vscrut vbndr vty lty vbody
349 vectAlgCase _tycon _ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
351 (vty, lty) <- vectAndLiftType ty
352 vexpr <- vectExpr scrut
353 (vbndr, (vbndrs, (vect_body, lift_body)))
357 let (vect_bndrs, lift_bndrs) = unzip vbndrs
358 (vscrut, lscrut, pdata_tc, _arg_tys) <- mkVScrut (vVar vbndr)
359 vect_dc <- maybeV (lookupDataCon dc)
360 let [pdata_dc] = tyConDataCons pdata_tc
362 let vcase = mk_wild_case vscrut vty vect_dc vect_bndrs vect_body
363 lcase = mk_wild_case lscrut lty pdata_dc lift_bndrs lift_body
365 return $ vLet (vNonRec vbndr vexpr) (vcase, lcase)
367 vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
368 | otherwise = vectBndrIn bndr
370 mk_wild_case expr ty dc bndrs body
371 = mkWildCase expr (exprType expr) ty [(DataAlt dc, bndrs, body)]
373 vectAlgCase tycon _ty_args scrut bndr ty alts
375 vect_tc <- maybeV (lookupTyCon tycon)
376 (vty, lty) <- vectAndLiftType ty
378 let arity = length (tyConDataCons vect_tc)
379 sel_ty <- builtin (selTy arity)
380 sel_bndr <- newLocalVar (fsLit "sel") sel_ty
381 let sel = Var sel_bndr
383 (vbndr, valts) <- vect_scrut_bndr
384 $ mapM (proc_alt arity sel vty lty) alts'
385 let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
387 vexpr <- vectExpr scrut
388 (vect_scrut, lift_scrut, pdata_tc, _arg_tys) <- mkVScrut (vVar vbndr)
389 let [pdata_dc] = tyConDataCons pdata_tc
391 let (vect_bodies, lift_bodies) = unzip vbodies
393 vdummy <- newDummyVar (exprType vect_scrut)
394 ldummy <- newDummyVar (exprType lift_scrut)
395 let vect_case = Case vect_scrut vdummy vty
396 (zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
398 lc <- builtin liftingContext
399 lbody <- combinePD vty (Var lc) sel lift_bodies
400 let lift_case = Case lift_scrut ldummy lty
401 [(DataAlt pdata_dc, sel_bndr : concat lift_bndrss,
404 return . vLet (vNonRec vbndr vexpr)
405 $ (vect_case, lift_case)
407 vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr (fsLit "scrut")
408 | otherwise = vectBndrIn bndr
410 alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
412 cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
413 cmp DEFAULT DEFAULT = EQ
416 cmp _ _ = panic "vectAlgCase/cmp"
418 proc_alt arity sel _ lty (DataAlt dc, bndrs, body)
420 vect_dc <- maybeV (lookupDataCon dc)
421 let ntag = dataConTagZ vect_dc
422 tag = mkDataConTag vect_dc
423 fvs = freeVarsOf body `delVarSetList` bndrs
425 sel_tags <- liftM (`App` sel) (builtin (selTags arity))
426 lc <- builtin liftingContext
427 elems <- builtin (selElements arity ntag)
433 binds <- mapM (pack_var (Var lc) sel_tags tag)
436 (ve, le) <- vectExpr body
437 return (ve, Case (elems `App` sel) lc lty
438 [(DEFAULT, [], (mkLets (concat binds) le))])
439 -- empty <- emptyPD vty
440 -- return (ve, Case (elems `App` sel) lc lty
441 -- [(DEFAULT, [], Let (NonRec flags_var flags_expr)
442 -- $ mkLets (concat binds) le),
443 -- (LitAlt (mkMachInt 0), [], empty)])
444 let (vect_bndrs, lift_bndrs) = unzip vbndrs
445 return (vect_dc, vect_bndrs, lift_bndrs, vbody)
447 proc_alt _ _ _ _ _ = panic "vectAlgCase/proc_alt"
449 mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
451 pack_var len tags t v
458 expr <- packByTagPD (idType vv) (Var lv) len tags t
459 updLEnv (\env -> env { local_vars = extendVarEnv
460 (local_vars env) v (vv, lv') })
461 return [(NonRec lv' expr)]