%
-% (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
+% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section[DsBinds]{Pattern-matching bindings (HsBinds and MonoBinds)}
lower levels it is preserved with @let@/@letrec@s).
\begin{code}
-#include "HsVersions.h"
+module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, AutoScc(..) ) where
-module DsBinds ( dsBinds, dsInstBinds ) where
+#include "HsVersions.h"
-IMP_Ubiq()
-IMPORT_DELOOPER(DsLoop) -- break dsExpr-ish loop
-import HsSyn -- lots of things
- hiding ( collectBinders{-also in CoreSyn-} )
-import CoreSyn -- lots of things
-import TcHsSyn ( SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr),
- SYN_IE(TypecheckedBind), SYN_IE(TypecheckedMonoBinds),
- SYN_IE(TypecheckedPat)
- )
-import DsHsSyn ( collectTypedBinders, collectTypedPatBinders )
+import {-# SOURCE #-} DsExpr( dsLExpr, dsExpr )
+import {-# SOURCE #-} Match( matchWrapper )
import DsMonad
import DsGRHSs ( dsGuarded )
import DsUtils
-import Match ( matchWrapper )
-
-import CmdLineOpts ( opt_SccProfilingOn, opt_AutoSccsOnAllToplevs, opt_CompilingGhcInternals )
-import CostCentre ( mkAutoCC, IsCafCC(..), mkAllDictsCC, preludeDictsCostCentre )
-import Id ( idType, SYN_IE(DictVar), GenId )
-import ListSetOps ( minusList, intersectLists )
-import Name ( isExported )
-import PprType ( GenType )
-import PprStyle ( PprStyle(..) )
-import Pretty ( ppShow )
-import Type ( mkTyVarTys, mkForAllTys, splitSigmaTy,
- tyVarsOfType, tyVarsOfTypes, isDictTy
- )
-import TyVar ( tyVarSetToList, GenTyVar{-instance Eq-} )
-import Util ( isIn, panic{-, pprTrace ToDo:rm-} )
---import PprCore--ToDo:rm
---import PprType ( GenTyVar ) --ToDo:rm
---import Usage--ToDo:rm
---import Unique--ToDo:rm
+
+import HsSyn -- lots of things
+import CoreSyn -- lots of things
+import CoreUtils ( exprType, mkInlineMe, mkSCC )
+
+import StaticFlags ( opt_AutoSccsOnAllToplevs,
+ opt_AutoSccsOnExportedToplevs )
+import OccurAnal ( occurAnalyseExpr )
+import CostCentre ( mkAutoCC, IsCafCC(..) )
+import Id ( Id, idType, idName, isExportedId, mkLocalId, setInlinePragma )
+import Rules ( addIdSpecialisations, mkLocalRule )
+import Var ( Var, isGlobalId, setIdNotExported )
+import VarEnv
+import Type ( mkTyVarTy, substTyWith )
+import TysWiredIn ( voidTy )
+import Outputable
+import SrcLoc ( Located(..) )
+import Maybes ( isJust, catMaybes, orElse )
+import Bag ( bagToList )
+import BasicTypes ( Activation(..), isAlwaysActive )
+import Monad ( foldM )
+import FastString ( mkFastString )
+import List ( (\\) )
+import Util ( mapSnd )
\end{code}
%************************************************************************
%* *
-\subsection[toplevel-and-regular-DsBinds]{Regular and top-level @dsBinds@}
+\subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
%* *
%************************************************************************
-Like @dsBinds@, @dsBind@ returns a @[CoreBinding]@, but it may be
-that some of the binders are of unboxed type. This is sorted out when
-the caller wraps the bindings round an expression.
-
-\begin{code}
-dsBinds :: Bool -> TypecheckedHsBinds -> DsM [CoreBinding]
-\end{code}
-
-All ``real'' bindings are expressed in terms of the
-@AbsBinds@ construct, which is a massively-complicated ``shorthand'',
-and its desugaring is the subject of section~9.1 in the static
-semantics paper.
-
-(ToDo) For:
-\begin{verbatim}
-AbsBinds [a1, ... ,aj] -- type variables
- [d1, ... ,dk] -- dict variables
- [(l1,g1), ..., (lm,gm)] -- overloaded equivs [Id pairs] (later...)
- [db1=..., ..., dbn=...] -- dict binds
- [vb1=..., ..., vbm=...] -- val binds; note: vb_i = l_i
-\end{verbatim}
-we want to make, in the general case (non-Fozzie translation):
-\begin{verbatim}
- -- tupler-upper:
- tup a1...aj d1...dk =
- let <dict-binds> in
- let(rec) <val-binds> in (vb1,...,vbm) -- NB: == ... in (l1,...,lm)
-
- -- a bunch of selectors:
- g1 a1...aj d1...dk = case (_tup a1...aj d1...dk) of (x1,x2,...,xm) -> x1
- ...
- gm a1...aj d1...dk = case (_tup a1...aj d1...dk) of (x1,x2,...,xm) -> xm
-\end{verbatim}
-But there are lots of special cases.
-
-
-%==============================================
-\subsubsection{Structure cases}
-%==============================================
-
-\begin{code}
-dsBinds auto_scc (BindWith _ _) = panic "dsBinds:BindWith"
-dsBinds auto_scc EmptyBinds = returnDs []
-dsBinds auto_scc (SingleBind bind) = dsBind auto_scc [] [] id [] bind
-
-dsBinds auto_scc (ThenBinds binds_1 binds_2)
- = andDs (++) (dsBinds auto_scc binds_1) (dsBinds auto_scc binds_2)
-\end{code}
-
-
-%==============================================
-\subsubsection{AbsBind case: no overloading}
-%==============================================
-
-Special case: no overloading.
-\begin{verbatim}
- x1 = e1
- x2 = e2
-\end{verbatim}
-We abstract each wrt the type variables, giving
-\begin{verbatim}
- x1' = /\tyvars -> e1[x1' tyvars/x1, x2' tyvars/x2]
- x2' = /\tyvars -> e2[x1' tyvars/x1, x2' tyvars/x2]
-\end{verbatim}
-There are some complications.
-
-(i) The @val_binds@ might mention variable not in @local_global_prs@.
-In this case we need to make up new polymorphic versions of them.
-
-(ii) Exactly the same applies to any @inst_binds@ which may be
-present. However, here we expect that mostly they will be simple constant
-definitions, which don't mention the type variables at all, so making them
-polymorphic is really overkill. @dsInstBinds@ deals with this case.
-
-\begin{code}
-dsBinds auto_scc (AbsBinds tyvars [] local_global_prs inst_binds val_binds)
- = mapDs mk_poly_private_binder private_binders
- `thenDs` \ poly_private_binders ->
- let
- full_local_global_prs = (private_binders `zip` poly_private_binders)
- ++ local_global_prs
- in
- listDs [ mkSatTyApp global tyvar_tys `thenDs` \ app ->
- returnDs (local, app)
- | (local,global) <- full_local_global_prs
- ] `thenDs` \ env ->
-
--- pprTrace "AbsBinds1:" (ppr PprDebug env) $
-
- extendEnvDs env (
-
- dsInstBinds tyvars inst_binds `thenDs` \ (inst_bind_pairs, inst_env) ->
- extendEnvDs inst_env (
-
- dsBind auto_scc tyvars [] (lookupId full_local_global_prs) inst_bind_pairs val_binds
- ))
- where
- -- "private_binders" is the list of binders in val_binds
- -- which don't appear in the local_global_prs list
- -- These only really show up in stuff produced from compiling
- -- class and instance declarations.
- -- We need to add suitable polymorphic versions of them to the
- -- local_global_prs.
- private_binders = binders `minusList` [local | (local,_) <- local_global_prs]
- binders = collectTypedBinders val_binds
- mk_poly_private_binder id = newSysLocalDs (mkForAllTys tyvars (idType id))
-
- tyvar_tys = mkTyVarTys tyvars
-\end{code}
-
-
-%==============================================
-\subsubsection{AbsBind case: overloading}
-%==============================================
-
-If there is overloading we go for the general case.
-
-We want the global identifiers to be abstracted wrt all types and
-dictionaries; and the local identifiers wrt the non-overloaded types.
-That is, we try to avoid global scoping of type abstraction. Example
-
- f :: Eq a => a -> [(a,b)] -> b
- f = ...f...
-
-Here, f is fully polymorphic in b. So we generate
-
- f ab d = let ...dict defns...
- in
- letrec f' b = ...(f' b)...
- in f' b
-
-*Notice* that we don't clone type variables, and *do* make use of
-shadowing. It is possible to do cloning, but it makes the code quite
-a bit more complicated, and the simplifier will clone it all anyway.
-
-Why bother with this gloss? Because it makes it more likely that
-the defn of f' can get floated out, notably if f gets specialised
-to a particular type for a.
-
\begin{code}
-dsBinds auto_scc (AbsBinds all_tyvars dicts local_global_prs dict_binds val_binds)
- = -- If there is any non-overloaded polymorphism, make new locals with
- -- appropriate polymorphism
- (if null non_overloaded_tyvars
- then
- -- No non-overloaded polymorphism, so stay with current envt
- returnDs (id, [], [])
- else
- -- Some local, non-overloaded polymorphism
- cloneTyVarsDs non_overloaded_tyvars `thenDs` \ local_tyvars ->
-
- mapDs mk_binder binders `thenDs` \ new_binders ->
- let
- old_new_pairs = binders `zip` new_binders
- in
-
- listDs [ mkSatTyApp new non_ov_tyvar_tys `thenDs` \ app ->
- returnDs (old, app)
- | (old,new) <- old_new_pairs
- ] `thenDs` \ extra_env ->
- let
- local_binds = [NonRec old app | (old,app) <- extra_env, old `is_elem` locals]
- is_elem = isIn "dsBinds"
- in
- returnDs (lookupId old_new_pairs, extra_env, local_binds)
- )
- `thenDs` \ (binder_subst_fn, local_env, local_binds) ->
-
--- pprTrace "AbsBinds:all:" (ppAbove (ppr PprDebug local_binds) (ppr PprDebug local_env)) $
-
- extendEnvDs local_env (
-
- dsInstBinds non_overloaded_tyvars dict_binds `thenDs` \ (inst_bind_pairs, inst_env) ->
-
- extendEnvDs inst_env (
-
- dsBind auto_scc non_overloaded_tyvars [] binder_subst_fn inst_bind_pairs val_binds
- )) `thenDs` \ core_binds ->
-
+dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
+dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
+
+dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
+dsLHsBinds binds = ds_lhs_binds NoSccs binds
+
+
+------------------------
+ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
+ -- scc annotation policy (see below)
+ds_lhs_binds auto_scc binds = foldM (dsLHsBind auto_scc) [] (bagToList binds)
+
+dsLHsBind :: AutoScc
+ -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
+ -> LHsBind Id
+ -> DsM [(Id,CoreExpr)] -- Result
+dsLHsBind auto_scc rest (L loc bind)
+ = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
+
+dsHsBind :: AutoScc
+ -> [(Id,CoreExpr)] -- Put this on the end (avoid quadratic append)
+ -> HsBind Id
+ -> DsM [(Id,CoreExpr)] -- Result
+
+dsHsBind auto_scc rest (VarBind var expr)
+ = dsLExpr expr `thenDs` \ core_expr ->
+
+ -- Dictionary bindings are always VarMonoBinds, so
+ -- we only need do this here
+ addDictScc var core_expr `thenDs` \ core_expr' ->
+ returnDs ((var, core_expr') : rest)
+
+dsHsBind auto_scc rest (FunBind (L _ fun) _ matches _)
+ = matchWrapper (FunRhs (idName fun)) matches `thenDs` \ (args, body) ->
+ addAutoScc auto_scc (fun, mkLams args body) `thenDs` \ pair ->
+ returnDs (pair : rest)
+
+dsHsBind auto_scc rest (PatBind pat grhss ty _)
+ = dsGuarded grhss ty `thenDs` \ body_expr ->
+ mkSelectorBinds pat body_expr `thenDs` \ sel_binds ->
+ mappM (addAutoScc auto_scc) sel_binds `thenDs` \ sel_binds ->
+ returnDs (sel_binds ++ rest)
+
+ -- Common special case: no type or dictionary abstraction
+ -- For the (rare) case when there are some mixed-up
+ -- dictionary bindings (for which a Rec is convenient)
+ -- we reply on the enclosing dsBind to wrap a Rec around.
+dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
+ = ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
let
- tuple_rhs = mkCoLetsAny core_binds (
- mkCoLetsAny local_binds (
- mkTupleExpr locals ))
+ core_prs' = addLocalInlines exports core_prs
+ exports' = [(global, Var local) | (_, global, local, _) <- exports]
in
- mkTupleBind all_tyvars dicts local_global_prs tuple_rhs `thenDs` \ core_bind_prs ->
-
- returnDs [ NonRec binder rhs | (binder,rhs) <- core_bind_prs ]
- where
- locals = [local | (local,global) <- local_global_prs]
- non_ov_tyvar_tys = mkTyVarTys non_overloaded_tyvars
-
- overloaded_tyvars = tyVarsOfTypes (map idType dicts)
- non_overloaded_tyvars = all_tyvars `minusList` (tyVarSetToList{-????-} overloaded_tyvars)
-
- binders = collectTypedBinders val_binds
- mk_binder id = newSysLocalDs (mkForAllTys non_overloaded_tyvars (idType id))
-\end{code}
-
-@mkSatTyApp id tys@ constructs an expression whose value is (id tys).
-However, sometimes id takes more type args than are in tys, and the
-specialiser hates that, so we have to eta expand, to
-@(/\ a b -> id tys a b)@.
-
-\begin{code}
-mkSatTyApp :: Id -- Id to apply to the types
- -> [Type] -- Types to apply it to
- -> DsM CoreExpr
-
-mkSatTyApp id [] = returnDs (Var id)
-
-mkSatTyApp id tys
- | null tvs
- = returnDs ty_app -- Common case
- | otherwise
- = newTyVarsDs (drop (length tys) tvs) `thenDs` \ tyvars ->
- returnDs (mkTyLam tyvars (mkTyApp ty_app (mkTyVarTys tyvars)))
- where
- (tvs, theta, tau_ty) = splitSigmaTy (idType id)
- ty_app = mkTyApp (Var id) tys
-\end{code}
-
-There are several places where we encounter ``inst binds,''
-@(Id, TypecheckedHsExpr)@ pairs. Many of these are ``trivial'' binds
-(a var to a var or literal), which we want to substitute away; so we
-return both some desugared bindings {\em and} a substitution
-environment for the subbed-away ones.
-
-These dictionary bindings are non-recursive, and ordered, so that
-later ones may mention earlier ones, but not vice versa.
-
-\begin{code}
-dsInstBinds :: [TyVar] -- Abstract wrt these
- -> [(Id, TypecheckedHsExpr)] -- From AbsBinds
- -> DsM ([(Id,CoreExpr)], -- Non-trivial bindings
- [(Id,CoreExpr)]) -- Trivial ones to be substituted away
-
-do_nothing = ([], []) -- out here to avoid dsInstBinds CAF (sigh)
-prel_dicts_cc = preludeDictsCostCentre False{-not dupd-} -- ditto
-
-dsInstBinds tyvars [] = returnDs do_nothing
-
-dsInstBinds tyvars ((inst, expr@(HsVar _)) : bs)
- = dsExpr expr `thenDs` \ rhs ->
- let -- Need to apply dsExpr to the variable in case it
- -- has a substitution in the current environment
- subst_item = (inst, rhs)
+ returnDs (core_prs' ++ exports' ++ rest)
+
+ -- Another common case: one exported variable
+ -- Non-recursive bindings come through this way
+dsHsBind auto_scc rest
+ (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
+ = ASSERT( all (`elem` tyvars) all_tyvars )
+ ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
+ let
+ -- Always treat the binds as recursive, because the typechecker
+ -- makes rather mixed-up dictionary bindings
+ core_bind = Rec core_prs
+ inline_env = mkVarEnv [(global, prag) | prag <- prags, isInlinePrag prag]
in
- extendEnvDs [subst_item] (
- dsInstBinds tyvars bs
- ) `thenDs` \ (binds, subst_env) ->
- returnDs (binds, subst_item : subst_env)
-
-dsInstBinds tyvars ((inst, expr@(HsLit _)) : bs)
- = dsExpr expr `thenDs` \ core_lit ->
+ mappM (dsSpec all_tyvars dicts tyvars global local core_bind)
+ prags `thenDs` \ mb_specs ->
let
- subst_item = (inst, core_lit)
+ (spec_binds, rules) = unzip (catMaybes mb_specs)
+ global' = addIdSpecialisations global rules
+ rhs' = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
in
- extendEnvDs [subst_item] (
- dsInstBinds tyvars bs
- ) `thenDs` \ (binds, subst_env) ->
- returnDs (binds, subst_item : subst_env)
-
-dsInstBinds tyvars ((inst, expr) : bs)
- | null abs_tyvars
- = dsExpr expr `thenDs` \ core_expr ->
- ds_dict_cc core_expr `thenDs` \ dict_expr ->
- dsInstBinds tyvars bs `thenDs` \ (core_rest, subst_env) ->
- returnDs ((inst, dict_expr) : core_rest, subst_env)
-
- | otherwise
- = -- Obscure case.
- -- The inst mentions the type vars wrt which we are abstracting,
- -- so we have to invent a new polymorphic version, and substitute
- -- appropriately.
- -- This can occur in, for example:
- -- leftPoll :: [FeedBack a] -> FeedBack a
- -- leftPoll xs = take poll xs
- -- Here there is an instance of take at the type of elts of xs,
- -- as well as the type of poll.
-
- dsExpr expr `thenDs` \ core_expr ->
- ds_dict_cc core_expr `thenDs` \ dict_expr ->
- newSysLocalDs poly_inst_ty `thenDs` \ poly_inst_id ->
+ returnDs (addInlineInfo inline_env (global', rhs') : spec_binds ++ rest)
+
+dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
+ = ds_lhs_binds (addSccs auto_scc exports) binds `thenDs` \ core_prs ->
+ let
+ -- Rec because of mixed-up dictionary bindings
+ core_bind = Rec (addLocalInlines exports core_prs)
+
+ tup_expr = mkTupleExpr locals
+ tup_ty = exprType tup_expr
+ poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
+ Let core_bind tup_expr
+ locals = [local | (_, _, local, _) <- exports]
+ local_tys = map idType locals
+ in
+ newSysLocalDs (exprType poly_tup_expr) `thenDs` \ poly_tup_id ->
let
- subst_item = (inst, mkTyApp (Var poly_inst_id) abs_tys)
+ dict_args = map Var dicts
+
+ mk_bind ((tyvars, global, local, prags), n) -- locals !! n == local
+ = -- Need to make fresh locals to bind in the selector, because
+ -- some of the tyvars will be bound to voidTy
+ newSysLocalsDs (map substitute local_tys) `thenDs` \ locals' ->
+ newSysLocalDs (substitute tup_ty) `thenDs` \ tup_id ->
+ mapM (dsSpec all_tyvars dicts tyvars global local core_bind)
+ prags `thenDs` \ mb_specs ->
+ let
+ (spec_binds, rules) = unzip (catMaybes mb_specs)
+ global' = addIdSpecialisations global rules
+ rhs = mkLams tyvars $ mkLams dicts $
+ mkTupleSelector locals' (locals' !! n) tup_id $
+ mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
+ in
+ returnDs ((global', rhs) : spec_binds)
+ where
+ mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
+ | otherwise = voidTy
+ ty_args = map mk_ty_arg all_tyvars
+ substitute = substTyWith all_tyvars ty_args
in
- extendEnvDs [subst_item] (
- dsInstBinds tyvars bs
- ) `thenDs` \ (core_rest, subst_env) ->
- returnDs ((poly_inst_id, mkTyLam abs_tyvars dict_expr) : core_rest,
- subst_item : subst_env)
+ mappM mk_bind (exports `zip` [0..]) `thenDs` \ export_binds_s ->
+ -- don't scc (auto-)annotate the tuple itself.
+
+ returnDs ((poly_tup_id, poly_tup_expr) : (concat export_binds_s ++ rest))
+
+-- Example:
+-- f :: (Eq a, Ix b) => a -> b -> b
+--
+-- AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
+--
+-- SpecPrag (/\b.\(d:Ix b). f Int b dInt d)
+-- (forall b. Ix b => Int -> b -> b)
+--
+-- Rule: forall b,(d:Ix b). f Int b dInt d = f_spec b d
+--
+-- Spec bind: f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono
+-- /\b.\(d:Ix b). in f Int b dInt d
+-- The idea is that f occurs just once, so it'll be
+-- inlined and specialised
+
+dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
+ = return Nothing
+
+dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
+ (SpecPrag spec_expr spec_ty const_dicts)
+ = do { let poly_name = idName poly_id
+ ; spec_name <- newLocalName (idName poly_id)
+ ; ds_spec_expr <- dsExpr spec_expr
+ ; let (bndrs, body) = collectBinders ds_spec_expr
+ mb_lhs = decomposeRuleLhs (bndrs ++ const_dicts) body
+
+ ; case mb_lhs of
+ Nothing -> do { dsWarn msg; return Nothing }
+
+ Just (bndrs', var, args) -> return (Just ((spec_id, spec_rhs), rule))
+ where
+ local_poly = setIdNotExported poly_id
+ -- Very important to make the 'f' non-exported,
+ -- else it won't be inlined!
+ spec_id = mkLocalId spec_name spec_ty
+ spec_rhs = Let (NonRec local_poly poly_f_body) ds_spec_expr
+ poly_f_body = mkLams (tvs ++ dicts) $
+ fix_up (Let mono_bind (Var mono_id))
+
+ -- Quantify over constant dicts on the LHS, since
+ -- their value depends only on their type
+ -- The ones we are interested in may even be imported
+ -- e.g. GHC.Base.dEqInt
+
+ rule = mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
+ AlwaysActive poly_name
+ bndrs' -- Includes constant dicts
+ args
+ (mkVarApps (Var spec_id) bndrs)
+ }
where
- inst_ty = idType inst
- abs_tyvars = tyVarSetToList{-???sigh-} (tyVarsOfType inst_ty) `intersectLists` tyvars
- abs_tys = mkTyVarTys abs_tyvars
- poly_inst_ty = mkForAllTys abs_tyvars inst_ty
-
- ------------------------
- -- Wrap a desugared expression in `_scc_ "DICT" <expr>' if
- -- appropriate. Uses "inst"'s type.
-
- -- if profiling, wrap the dict in "_scc_ DICT <dict>":
- ds_dict_cc expr
- | not ( opt_SccProfilingOn || opt_AutoSccsOnAllToplevs)
- -- the latter is so that -unprof-auto-scc-all adds dict sccs
- || not (isDictTy inst_ty)
- = returnDs expr -- that's easy: do nothing
-
- | opt_CompilingGhcInternals
- = returnDs (SCC prel_dicts_cc expr)
-
- | otherwise
- = getModuleAndGroupDs `thenDs` \ (mod, grp) ->
-
- -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
-
- returnDs (SCC (mkAllDictsCC mod grp False) expr)
+ -- Bind to voidTy any of all_ptvs that aren't
+ -- relevant for this particular function
+ fix_up body | null void_tvs = body
+ | otherwise = mkTyApps (mkLams void_tvs body)
+ (map (const voidTy) void_tvs)
+ void_tvs = all_tvs \\ tvs
+
+ msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
+ 2 (ppr spec_expr)
\end{code}
+
%************************************************************************
%* *
-\subsection[dsBind]{Desugaring a @Bind@}
+\subsection{Adding inline pragmas}
%* *
%************************************************************************
-Like @dsBinds@, @dsBind@ returns a @[CoreBinding]@, but it may be that
-some of the binders are of unboxed type.
+\begin{code}
+decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
+-- Returns Nothing if the LHS isn't of the expected shape
+-- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
+-- and they may be GlobalIds, which we can't forall-ify.
+-- So we substitute them out instead
+decomposeRuleLhs all_bndrs lhs
+ = go init_env (occurAnalyseExpr lhs) -- Occurrence analysis sorts out the dict
+ -- bindings so we know if they are recursive
+ where
-For an explanation of the first three args, see @dsMonoBinds@.
+ -- all_bndrs may include top-level imported dicts,
+ -- imported things with a for-all.
+ -- So we localise them and subtitute them out
+ bndr_prs = [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
+ localise d = mkLocalId (idName d) (idType d)
+
+ init_env = mkVarEnv bndr_prs
+ all_bndrs' = map subst_bndr all_bndrs
+ subst_bndr bndr = case lookupVarEnv init_env bndr of
+ Just (Var bndr') -> bndr'
+ Just other -> panic "decomposeRuleLhs"
+ Nothing -> bndr
+
+ -- Substitute dicts in the LHS args, so that there
+ -- aren't any lets getting in the way
+ go env (Let (NonRec dict rhs) body)
+ = go (extendVarEnv env dict (simpleSubst env rhs)) body
+ go env body
+ = case collectArgs body of
+ (Var fn, args) -> Just (all_bndrs', fn, map (simpleSubst env) args)
+ other -> Nothing
+
+simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
+-- Similar to CoreSubst.substExpr, except that
+-- (a) takes no account of capture; dictionary bindings use new names
+-- (b) can have a GlobalId (imported) in its domain
+-- (c) Ids only; no types are substituted
+
+simpleSubst subst expr
+ = go expr
+ where
+ go (Var v) = lookupVarEnv subst v `orElse` Var v
+ go (Type ty) = Type ty
+ go (Lit lit) = Lit lit
+ go (App fun arg) = App (go fun) (go arg)
+ go (Note note e) = Note note (go e)
+ go (Lam bndr body) = Lam bndr (go body)
+ go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
+ go (Let (Rec pairs) body) = Let (Rec (mapSnd go pairs)) (go body)
+ go (Case scrut bndr ty alts) = Case (go scrut) bndr ty
+ [(c,bs,go r) | (c,bs,r) <- alts]
+
+addLocalInlines exports core_prs
+ = map (addInlineInfo inline_env) core_prs
+ where
+ inline_env = mkVarEnv [(mono_id, prag)
+ | (_, _, mono_id, prags) <- exports,
+ prag <- prags, isInlinePrag prag]
+
+addInlineInfo :: IdEnv Prag -> (Id,CoreExpr) -> (Id,CoreExpr)
+addInlineInfo inline_env (bndr,rhs)
+ | Just (InlinePrag is_inline phase) <- lookupVarEnv inline_env bndr
+ = (attach_phase bndr phase, wrap_inline is_inline rhs)
+ | otherwise
+ = (bndr, rhs)
+ where
+ attach_phase bndr phase
+ | isAlwaysActive phase = bndr -- Default phase
+ | otherwise = bndr `setInlinePragma` phase
-\begin{code}
-dsBind :: Bool -- Add auto sccs to binds
- -> [TyVar] -> [DictVar] -- Abstract wrt these
- -> (Id -> Id) -- Binder substitution
- -> [(Id,CoreExpr)] -- Inst bindings already dealt with
- -> TypecheckedBind
- -> DsM [CoreBinding]
-
-dsBind auto_scc tyvars dicts binder_subst inst_bind_pairs EmptyBind
- = returnDs [NonRec binder rhs | (binder,rhs) <- inst_bind_pairs]
-
-dsBind auto_scc tyvars dicts binder_subst inst_bind_pairs (NonRecBind monobinds)
- = dsMonoBinds auto_scc False tyvars dicts binder_subst monobinds `thenDs` \ val_bind_pairs ->
- returnDs [NonRec binder rhs | (binder,rhs) <- inst_bind_pairs ++ val_bind_pairs]
-
-dsBind auto_scc tyvars dicts binder_subst inst_bind_pairs (RecBind monobinds)
- = dsMonoBinds auto_scc True tyvars dicts binder_subst monobinds `thenDs` \ val_bind_pairs ->
- returnDs [Rec (inst_bind_pairs ++ val_bind_pairs)]
+ wrap_inline True body = mkInlineMe body
+ wrap_inline False body = body
\end{code}
%************************************************************************
%* *
-\subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
+\subsection[addAutoScc]{Adding automatic sccs}
%* *
%************************************************************************
-@dsMonoBinds@ transforms @TypecheckedMonoBinds@ into @CoreBinds@.
-In addition to desugaring pattern matching, @dsMonoBinds@ takes
-a list of type variables and dicts, and adds abstractions for these
-to the front of every binding. That requires that the
-binders be altered too (their type has changed,
-so @dsMonoBinds@ also takes a function which maps binders into binders.
-This mapping gives the binder the correct new type.
-
-Remember, there's also a substitution in the monad which maps occurrences
-of these binders into applications of the new binder to suitable type variables
-and dictionaries.
-
-\begin{code}
-dsMonoBinds :: Bool -- True <=> add auto sccs
- -> Bool -- True <=> recursive binding group
- -> [TyVar] -> [DictVar] -- Abstract wrt these
- -> (Id -> Id) -- Binder substitution
- -> TypecheckedMonoBinds
- -> DsM [(Id,CoreExpr)]
-\end{code}
-
-
-
-%==============================================
-\subsubsection{Structure cases}
-%==============================================
-
-\begin{code}
-dsMonoBinds auto_scc is_rec tyvars dicts binder_subst EmptyMonoBinds = returnDs []
-
-dsMonoBinds auto_scc is_rec tyvars dicts binder_subst (AndMonoBinds binds_1 binds_2)
- = andDs (++) (dsMonoBinds auto_scc is_rec tyvars dicts binder_subst binds_1)
- (dsMonoBinds auto_scc is_rec tyvars dicts binder_subst binds_2)
-\end{code}
-
-
-%==============================================
-\subsubsection{Simple base cases: function and variable bindings}
-%==============================================
-
\begin{code}
-dsMonoBinds auto_scc is_rec tyvars dicts binder_subst (CoreMonoBind var core_expr)
- = doSccAuto auto_scc [var] core_expr `thenDs` \ sccd_core_expr ->
- returnDs [(binder_subst var, mkLam tyvars dicts sccd_core_expr)]
-
-dsMonoBinds auto_scc is_rec tyvars dicts binder_subst (VarMonoBind var expr)
- = dsExpr expr `thenDs` \ core_expr ->
- doSccAuto auto_scc [var] core_expr `thenDs` \ sccd_core_expr ->
- returnDs [(binder_subst var, mkLam tyvars dicts sccd_core_expr)]
-
-dsMonoBinds auto_scc is_rec tyvars dicts binder_subst (FunMonoBind fun _ matches locn)
- = putSrcLocDs locn $
- let
- new_fun = binder_subst fun
- error_string = "function " ++ showForErr fun
- in
- matchWrapper (FunMatch fun) matches error_string `thenDs` \ (args, body) ->
- doSccAuto auto_scc [fun] body `thenDs` \ sccd_body ->
- returnDs [(new_fun,
- mkLam tyvars (dicts ++ args) sccd_body)]
-
-dsMonoBinds auto_scc is_rec tyvars dicts binder_subst (PatMonoBind (VarPat v) grhss_and_binds locn)
- = putSrcLocDs locn $
- dsGuarded grhss_and_binds `thenDs` \ body_expr ->
- doSccAuto auto_scc [v] body_expr `thenDs` \ sccd_body_expr ->
- returnDs [(binder_subst v, mkLam tyvars dicts sccd_body_expr)]
+data AutoScc
+ = TopLevel
+ | TopLevelAddSccs (Id -> Maybe Id)
+ | NoSccs
+
+addSccs :: AutoScc -> [(a,Id,Id,[Prag])] -> AutoScc
+addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
+addSccs NoSccs exports = NoSccs
+addSccs TopLevel exports
+ = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc,_) <- exports, loc == id ] of
+ (exp:_) | opt_AutoSccsOnAllToplevs ||
+ (isExportedId exp &&
+ opt_AutoSccsOnExportedToplevs)
+ -> Just exp
+ _ -> Nothing)
+
+addAutoScc :: AutoScc -- if needs be, decorate toplevs?
+ -> (Id, CoreExpr)
+ -> DsM (Id, CoreExpr)
+
+addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr)
+ | do_auto_scc
+ = getModuleDs `thenDs` \ mod ->
+ returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
+ where do_auto_scc = isJust maybe_auto_scc
+ maybe_auto_scc = auto_scc_fn bndr
+ (Just top_bndr) = maybe_auto_scc
+
+addAutoScc _ pair
+ = returnDs pair
\end{code}
-%==============================================
-\subsubsection{The general base case}
-%==============================================
-
-Now the general case of a pattern binding. The monomorphism restriction
-should ensure that if there is a non-simple pattern binding in the
-group, then there is no overloading involved, so the dictionaries should
-be empty. (Simple pattern bindings were handled above.)
-First, the paranoia check.
+If profiling and dealing with a dict binding,
+wrap the dict in @_scc_ DICT <dict>@:
\begin{code}
-dsMonoBinds auto_scc is_rec tyvars (_:_) binder_subst (PatMonoBind pat grhss_and_binds locn)
- = panic "Non-empty dict list in for pattern binding"
-\end{code}
-
-We handle three cases for the binding
- pat = rhs
-
-\begin{description}
-\item[pat has no binders.]
-Then all this is dead code and we return an empty binding.
+addDictScc var rhs = returnDs rhs
-\item[pat has exactly one binder, v.]
-Then we can transform to:
-\begin{verbatim}
- v' = /\ tyvars -> case rhs of { pat -> v }
-\end{verbatim}
-where \tr{v'} is gotten by looking up \tr{v} in the \tr{binder_subst}.
+{- DISABLED for now (need to somehow make up a name for the scc) -- SDM
+ | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
+ || not (isDictId var)
+ = returnDs rhs -- That's easy: do nothing
-\item[pat has more than one binder.]
-Then we transform to:
-\begin{verbatim}
- t = /\ tyvars -> case rhs of { pat -> (v1, ..., vn) }
-
- vi = /\ tyvars -> case (t tyvars) of { (v1, ..., vn) -> vi }
-\end{verbatim}
-\end{description}
-
-\begin{code}
-dsMonoBinds auto_scc is_rec tyvars [] binder_subst (PatMonoBind pat grhss_and_binds locn)
- = putSrcLocDs locn $
-
- dsGuarded grhss_and_binds `thenDs` \ body_expr ->
- doSccAuto auto_scc pat_binders body_expr `thenDs` \ sccd_body_expr ->
-
-{- KILLED by Sansom. 95/05
- -- make *sure* there are no primitive types in the pattern
- if any_con_w_prim_arg pat then
- error ( "ERROR: Pattern-bindings cannot involve unboxed/primitive types!\n\t"
- ++ (ppShow 80 (ppr PprForUser pat)) ++ "\n"
- ++ "(We apologise for not reporting this more `cleanly')\n" )
-
- -- Check whether the pattern already is a simple tuple; if so,
- -- we can just use the rhs directly
- else
+ | otherwise
+ = getModuleAndGroupDs `thenDs` \ (mod, grp) ->
+ -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
+ returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
-}
--- pprTrace "dsMonoBinds:PatMonoBind:" (ppr PprDebug sccd_body_expr) $
-
- mkSelectorBinds tyvars pat
- [(binder, binder_subst binder) | binder <- pat_binders]
- sccd_body_expr
- where
- pat_binders = collectTypedPatBinders pat
- -- NB For a simple tuple pattern, these binders
- -- will appear in the right order!
-\end{code}
-
-Wild-card patterns could be made acceptable here, but it involves some
-extra work to benefit only rather unusual constructs like
-\begin{verbatim}
- let (_,a,b) = ... in ...
-\end{verbatim}
-Better to extend the whole thing for any irrefutable constructor, at least.
-
-%************************************************************************
-%* *
-\subsection[doSccAuto]{Adding automatic sccs}
-%* *
-%************************************************************************
-
-\begin{code}
-doSccAuto :: Bool -> [Id] -> CoreExpr -> DsM CoreExpr
-
-doSccAuto False binders core_expr
- = returnDs core_expr
-
-doSccAuto True [] core_expr -- no binders
- = returnDs core_expr
-
-doSccAuto True _ core_expr@(SCC _ _) -- already sccd
- = returnDs core_expr
-
-doSccAuto True _ core_expr@(Con _ _) -- dont bother for simple Con
- = returnDs core_expr
-
-doSccAuto True binders core_expr
- = let
- scc_all = opt_AutoSccsOnAllToplevs
- scc_export = not (null export_binders)
-
- export_binders = filter isExported binders
-
- scc_binder = head (if scc_all then binders else export_binders)
- in
- if scc_all || scc_export then
- getModuleAndGroupDs `thenDs` \ (mod,grp) ->
- returnDs (SCC (mkAutoCC scc_binder mod grp IsNotCafCC) core_expr)
- else
- returnDs core_expr
\end{code}