3 -- Copyright (c) [2001..2002] Manuel M T Chakravarty & Gabriele Keller
5 -- Monad maintaining parallel contexts and substitutions for flattening.
7 --- DESCRIPTION ---------------------------------------------------------------
9 -- The flattening transformation needs to perform a fair amount of plumbing.
10 -- It needs to mainatin a set of variables, called the parallel context for
11 -- lifting, variable substitutions in case alternatives, and so on.
12 -- Moreover, we need to manage uniques to create new variables. The monad
13 -- defined in this module takes care of maintaining this state.
15 --- DOCU ----------------------------------------------------------------------
17 -- Language: Haskell 98
19 -- * a parallel context is a set of variables that get vectorised during a
20 -- lifting transformations (ie, their type changes from `t' to `[:t:]')
22 -- * all vectorised variables in a parallel context have the same size; we
23 -- call this also the size of the parallel context
25 -- * we represent contexts by maps that give the lifted version of a variable
26 -- (remember that in GHC, variables contain type information that changes
29 --- TODO ----------------------------------------------------------------------
31 -- * Assumptions currently made that should (if they turn out to be true) be
32 -- documented in The Commentary:
34 -- - Local bindings can be copied without any need to alpha-rename bound
35 -- variables (or their uniques). Such renaming is only necessary when
36 -- bindings in a recursive group are replicated; implying that this is
37 -- required in the case of top-level bindings). (Note: The CoreTidy path
38 -- generates global uniques before code generation.)
40 -- * One FIXME left to resolve.
49 -- variable generation
53 -- context management & query operations
55 extendContext, packContext, liftVar, liftConst, intersectWithContext,
57 -- construction of prelude functions
59 mk'fst, mk'eq, mk'neq, mk'and, mk'or, mk'lengthP, mk'replicateP, mk'mapP,
60 mk'bpermuteP, mk'bpermuteDftP, mk'indexOfP
68 import Outputable (Outputable(ppr), pprPanic)
69 import UniqSupply (UniqSupply, splitUniqSupply, uniqFromSupply)
70 import Var (Var, idType)
71 import Id (Id, mkSysLocal)
73 import VarSet (VarSet, emptyVarSet, extendVarSet, varSetElems )
74 import VarEnv (VarEnv, emptyVarEnv, zipVarEnv, plusVarEnv,
75 elemVarEnv, lookupVarEnv, lookupVarEnv_NF, delVarEnvList)
76 import Type (Type, tyConAppTyCon)
77 import HscTypes (HomePackageTable,
78 ExternalPackageState(eps_PTE), HscEnv(hsc_HPT),
79 TyThing(..), lookupType)
80 import PrelNames ( fstName, andName, orName,
81 lengthPName, replicatePName, mapPName, bpermutePName,
82 bpermuteDftPName, indexOfPName)
83 import TysPrim ( charPrimTyCon, intPrimTyCon, floatPrimTyCon, doublePrimTyCon )
84 import PrimOp ( PrimOp(..) )
85 import PrelInfo ( primOpId )
86 import CoreSyn (Expr(..), Bind(..), CoreBndr, CoreExpr, CoreBind, mkApps)
87 import CoreUtils (exprType)
88 import FastString (FastString)
91 import NDPCoreUtils (parrElemTy)
94 -- definition of the monad
95 -- -----------------------
97 -- state maintained by the flattening monad
99 data FlattenState = FlattenState {
101 -- our source for uniques
105 -- environment containing all known names (including all
106 -- Prelude functions)
110 -- this variable determines the parallel context; if
111 -- `Nothing', we are in pure vectorisation mode, no
114 ctxtVar :: Maybe Var,
116 -- environment that maps each variable that is
117 -- vectorised in the current parallel context to the
118 -- vectorised version of that variable
120 ctxtEnv :: VarEnv Var,
122 -- those variables from the *domain* of `ctxtEnv' that
123 -- have been used since the last context restriction (cf.
124 -- `restrictContext')
129 -- initial value of the flattening state
131 initialFlattenState :: ExternalPackageState
135 initialFlattenState eps hpt us =
140 ctxtEnv = emptyVarEnv,
141 usedVars = emptyVarSet
145 case lookupType hpt (eps_PTE eps) n of
147 _ -> pprPanic "FlattenMonad: unknown name:" (ppr n)
149 -- the monad representation (EXPORTED ABSTRACTLY)
151 newtype Flatten a = Flatten {
152 unFlatten :: (FlattenState -> (a, FlattenState))
155 instance Monad Flatten where
156 return x = Flatten $ \s -> (x, s)
157 m >>= n = Flatten $ \s -> let
158 (r, s') = unFlatten m s
162 -- execute the given flattening computation (EXPORTED)
165 -> ExternalPackageState
169 runFlatten hsc_env eps us m
170 = fst $ unFlatten m (initialFlattenState eps (hsc_HPT hsc_env) us)
173 -- variable generation
174 -- -------------------
176 -- generate a new local variable whose name is based on the given lexeme and
177 -- whose type is as specified in the second argument (EXPORTED)
179 newVar :: FastString -> Type -> Flatten Var
180 newVar lexeme ty = Flatten $ \state ->
182 (us1, us2) = splitUniqSupply (us state)
183 state' = state {us = us2}
185 (mkSysLocal lexeme (uniqFromSupply us1) ty, state')
187 -- generate a non-recursive binding using a new binder whose name is derived
188 -- from the given lexeme (EXPORTED)
190 mkBind :: FastString -> CoreExpr -> Flatten (CoreBndr, CoreBind)
193 v <- newVar lexeme (exprType e)
194 return (v, NonRec v e)
197 -- context management
198 -- ------------------
200 -- extend the parallel context by the given set of variables (EXPORTED)
202 -- * if there is no parallel context at the moment, the first element of the
203 -- variable list will be used to determine the new parallel context
205 -- * the second argument is executed in the current context extended with the
208 -- * the variables must already have been lifted by transforming their type,
209 -- but they *must* have retained their original name (or, at least, their
210 -- unique); this is needed so that they match the original variable in
211 -- variable environments
213 -- * any trace of the given set of variables has to be removed from the state
214 -- at the end of this operation
216 extendContext :: [Var] -> Flatten a -> Flatten a
217 extendContext [] m = m
218 extendContext vs m = Flatten $ \state ->
221 ctxtVar = ctxtVar state `mplus` Just (head vs),
222 ctxtEnv = ctxtEnv state `plusVarEnv` zipVarEnv vs vs
224 (r, extState') = unFlatten m extState
225 resState = extState' { -- remove `vs' from the result state
226 ctxtVar = ctxtVar state,
227 ctxtEnv = ctxtEnv state,
228 usedVars = usedVars extState' `delVarEnvList` vs
233 -- execute the second argument in a restricted context (EXPORTED)
235 -- * all variables in the current parallel context are packed according to
236 -- the permutation vector associated with the variable passed as the first
237 -- argument (ie, all elements of vectorised context variables that are
238 -- invalid in the restricted context are dropped)
240 -- * the returned list of core binders contains the operations that perform
241 -- the restriction on all variables in the parallel context that *do* occur
242 -- during the execution of the second argument (ie, `liftVar' is executed at
243 -- least once on any such variable)
245 packContext :: Var -> Flatten a -> Flatten (a, [CoreBind])
246 packContext perm m = Flatten $ \state ->
248 -- FIXME: To set the packed environment to the unpacked on is a hack of
249 -- which I am not sure yet (a) whether it works and (b) whether it's
250 -- really worth it. The one advantages is that, we can use a var set,
251 -- after all, instead of a var environment.
253 -- The idea is the following: If we have to pack a variable `x', we
254 -- generate `let{-NonRec-} x = bpermuteP perm x in ...'. As this is a
255 -- non-recursive binding, the lhs `x' overshadows the rhs `x' in the
258 -- NB: If we leave it like this, `mkCoreBind' can be simplified.
259 packedCtxtEnv = ctxtEnv state
260 packedState = state {
262 (lookupVarEnv_NF packedCtxtEnv)
264 ctxtEnv = packedCtxtEnv,
265 usedVars = emptyVarSet
267 (r, packedState') = unFlatten m packedState
268 resState = state { -- revert to the unpacked context
269 ctxtVar = ctxtVar state,
270 ctxtEnv = ctxtEnv state
272 bndrs = map mkCoreBind . varSetElems . usedVars $ packedState'
274 -- generate a binding for the packed variant of a context variable
277 rhs = fst $ unFlatten (mk'bpermuteP (idType var)
282 NonRec (lookupVarEnv_NF packedCtxtEnv var) $ rhs
285 ((r, bndrs), resState)
287 -- lift a single variable in the current context (EXPORTED)
289 -- * if the variable does not occur in the context, it's value is vectorised to
290 -- match the size of the current context
292 -- * otherwise, the variable is replaced by whatever the context environment
293 -- maps it to (this may either be simply the lifted version of the original
294 -- variable or a packed variant of that variable)
296 -- * the monad keeps track of all lifted variables that occur in the parallel
297 -- context, so that `packContext' can determine the correct set of core
300 liftVar :: Var -> Flatten CoreExpr
301 liftVar var = Flatten $ \s ->
304 v'elemType = parrElemTy . idType $ v
305 len = fst $ unFlatten (mk'lengthP v'elemType (Var v)) s
306 replicated = fst $ unFlatten (mk'replicateP (idType var) len (Var var)) s
307 in case lookupVarEnv (ctxtEnv s) var of
308 Just liftedVar -> (Var liftedVar,
309 s {usedVars = usedVars s `extendVarSet` var})
310 Nothing -> (replicated, s)
312 -- lift a constant expression in the current context (EXPORTED)
314 -- * the value of the constant expression is vectorised to match the current
317 liftConst :: CoreExpr -> Flatten CoreExpr
318 liftConst e = Flatten $ \s ->
321 v'elemType = parrElemTy . idType $ v
322 len = fst $ unFlatten (mk'lengthP v'elemType (Var v)) s
324 (fst $ unFlatten (mk'replicateP (exprType e) len e ) s, s)
326 -- pick those variables of the given set that occur (if albeit in lifted form)
327 -- in the current parallel context (EXPORTED)
329 -- * the variables returned are from the given set and *not* the corresponding
332 intersectWithContext :: VarSet -> Flatten [Var]
333 intersectWithContext vs = Flatten $ \s ->
335 vs' = filter (`elemVarEnv` ctxtEnv s) (varSetElems vs)
340 -- construct applications of prelude functions
341 -- -------------------------------------------
343 -- NB: keep all the used names listed in `FlattenInfo.namesNeededForFlattening'
345 -- generate an application of `fst' (EXPORTED)
347 mk'fst :: Type -> Type -> CoreExpr -> Flatten CoreExpr
348 mk'fst ty1 ty2 a = mkFunApp fstName [Type ty1, Type ty2, a]
350 -- generate an application of `&&' (EXPORTED)
352 mk'and :: CoreExpr -> CoreExpr -> Flatten CoreExpr
353 mk'and a1 a2 = mkFunApp andName [a1, a2]
355 -- generate an application of `||' (EXPORTED)
357 mk'or :: CoreExpr -> CoreExpr -> Flatten CoreExpr
358 mk'or a1 a2 = mkFunApp orName [a1, a2]
360 -- generate an application of `==' where the arguments may only be literals
361 -- that may occur in a Core case expression (i.e., `Char', `Int', `Float', and
362 -- `Double') (EXPORTED)
364 mk'eq :: Type -> CoreExpr -> CoreExpr -> Flatten CoreExpr
365 mk'eq ty a1 a2 = return (mkApps (Var eqName) [a1, a2])
367 tc = tyConAppTyCon ty
369 eqName | tc == charPrimTyCon = primOpId CharEqOp
370 | tc == intPrimTyCon = primOpId IntEqOp
371 | tc == floatPrimTyCon = primOpId FloatEqOp
372 | tc == doublePrimTyCon = primOpId DoubleEqOp
374 pprPanic "FlattenMonad.mk'eq: " (ppr ty)
376 -- generate an application of `==' where the arguments may only be literals
377 -- that may occur in a Core case expression (i.e., `Char', `Int', `Float', and
378 -- `Double') (EXPORTED)
380 mk'neq :: Type -> CoreExpr -> CoreExpr -> Flatten CoreExpr
381 mk'neq ty a1 a2 = return (mkApps (Var neqName) [a1, a2])
383 tc = tyConAppTyCon ty
385 neqName {- | name == charPrimTyConName = neqCharName -}
386 | tc == intPrimTyCon = primOpId IntNeOp
387 {- | name == floatPrimTyConName = neqFloatName -}
388 {- | name == doublePrimTyConName = neqDoubleName -}
390 pprPanic "FlattenMonad.mk'neq: " (ppr ty)
392 -- generate an application of `lengthP' (EXPORTED)
394 mk'lengthP :: Type -> CoreExpr -> Flatten CoreExpr
395 mk'lengthP ty a = mkFunApp lengthPName [Type ty, a]
397 -- generate an application of `replicateP' (EXPORTED)
399 mk'replicateP :: Type -> CoreExpr -> CoreExpr -> Flatten CoreExpr
400 mk'replicateP ty a1 a2 = mkFunApp replicatePName [Type ty, a1, a2]
402 -- generate an application of `replicateP' (EXPORTED)
404 mk'mapP :: Type -> Type -> CoreExpr -> CoreExpr -> Flatten CoreExpr
405 mk'mapP ty1 ty2 a1 a2 = mkFunApp mapPName [Type ty1, Type ty2, a1, a2]
407 -- generate an application of `bpermuteP' (EXPORTED)
409 mk'bpermuteP :: Type -> CoreExpr -> CoreExpr -> Flatten CoreExpr
410 mk'bpermuteP ty a1 a2 = mkFunApp bpermutePName [Type ty, a1, a2]
412 -- generate an application of `bpermuteDftP' (EXPORTED)
414 mk'bpermuteDftP :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> Flatten CoreExpr
415 mk'bpermuteDftP ty a1 a2 a3 = mkFunApp bpermuteDftPName [Type ty, a1, a2, a3]
417 -- generate an application of `indexOfP' (EXPORTED)
419 mk'indexOfP :: Type -> CoreExpr -> CoreExpr -> Flatten CoreExpr
420 mk'indexOfP ty a1 a2 = mkFunApp indexOfPName [Type ty, a1, a2]
423 -- auxilliary functions
424 -- --------------------
426 -- obtain the context variable, aborting if it is not available (as this
427 -- signals an internal error in the usage of the `Flatten' monad)
429 ctxtVarErr :: FlattenState -> Var
430 ctxtVarErr s = case ctxtVar s of
431 Nothing -> panic "FlattenMonad.ctxtVarErr: No context variable available!"
434 -- given the name of a known function and a set of arguments (needs to include
435 -- all needed type arguments), build a Core expression that applies the named
436 -- function to those arguments
438 mkFunApp :: Name -> [CoreExpr] -> Flatten CoreExpr
441 fun <- lookupName name
442 return $ mkApps (Var fun) args
444 -- get the `Id' of a known `Name'
446 -- * this can be the `Name' of any function that's visible on the toplevel of
447 -- the current compilation unit
449 lookupName :: Name -> Flatten Id
450 lookupName name = Flatten $ \s ->