[project @ 2003-12-10 14:15:16 by simonmar]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsBinds.lhs
index abffcb1..0d5cb7e 100644 (file)
@@ -1,5 +1,5 @@
 %
-% (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)}
 
@@ -8,74 +8,37 @@ in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
 lower levels it is preserved with @let@/@letrec@s).
 
 \begin{code}
-#include "HsVersions.h"
+module DsBinds ( dsHsBinds, AutoScc(..) ) where
 
-module DsBinds ( dsBinds ) where
+#include "HsVersions.h"
 
-IMP_Ubiq()
-#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
-IMPORT_DELOOPER(DsLoop)                -- break dsExpr-ish loop
-#else
-import {-# SOURCE #-} DsExpr
-#endif
 
-import HsSyn           -- lots of things
-import CoreSyn         -- lots of things
-import CoreUtils       ( coreExprType )
-import TcHsSyn         ( SYN_IE(TypecheckedHsBinds), SYN_IE(TypecheckedHsExpr),
-                         SYN_IE(TypecheckedMonoBinds),
-                         SYN_IE(TypecheckedPat)
-                       )
+import {-# SOURCE #-}  DsExpr( dsLExpr )
 import DsMonad
 import DsGRHSs         ( dsGuarded )
 import DsUtils
-import Match           ( matchWrapper )
-
-import BasicTypes       ( SYN_IE(Module) )
-import CmdLineOpts     ( opt_SccProfilingOn, opt_AutoSccsOnAllToplevs, 
-                         opt_AutoSccsOnExportedToplevs, opt_CompilingGhcInternals )
-import CostCentre      ( mkAutoCC, IsCafCC(..), mkAllDictsCC, preludeDictsCostCentre )
-import Id              ( idType, SYN_IE(DictVar), GenId, SYN_IE(Id) )
-import ListSetOps      ( minusList, intersectLists )
-import Name            ( isExported )
-import PprType         ( GenType )
-import Outputable      ( PprStyle(..) )
-import Type            ( mkTyVarTy, isDictTy, instantiateTy
-                       )
-import TyVar           ( tyVarSetToList, GenTyVar{-instance Eq-} )
-import TysPrim         ( voidTy )
-import Util            ( isIn, panic, assertPanic  )
-\end{code}
-
-%************************************************************************
-%*                                                                     *
-\subsection[toplevel-and-regular-DsBinds]{Regular and top-level @dsBinds@}
-%*                                                                     *
-%************************************************************************
-
-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}
-type Group = FAST_STRING
-
-dsBinds :: Maybe (Module, Group) -> TypecheckedHsBinds -> DsM [CoreBinding]
 
-dsBinds _ EmptyBinds                = returnDs []
-dsBinds mb_mod_grp (ThenBinds binds_1 binds_2) 
-  = andDs (++) (dsBinds mb_mod_grp binds_1) (dsBinds mb_mod_grp binds_2)
+import HsSyn           -- lots of things
+import CoreSyn         -- lots of things
+import CoreUtils       ( exprType, mkInlineMe, mkSCC )
+import Match           ( matchWrapper )
 
-dsBinds mb_mod_grp (MonoBind binds sigs is_rec)
-  = dsMonoBinds mb_mod_grp is_rec binds  `thenDs` \ prs ->
-    returnDs (if is_rec then
-               [Rec prs]
-             else
-               [NonRec binder rhs | (binder,rhs) <- prs]
-    )
+import CmdLineOpts     ( opt_AutoSccsOnAllToplevs, opt_AutoSccsOnExportedToplevs )
+import CostCentre      ( mkAutoCC, IsCafCC(..) )
+import Id              ( idType, idName, isExportedId, isSpecPragmaId, Id )
+import NameSet
+import VarSet
+import TcType          ( mkTyVarTy )
+import Subst           ( substTyWith )
+import TysWiredIn      ( voidTy )
+import Outputable
+import SrcLoc          ( Located(..) )
+import Maybe           ( isJust )
+import Bag             ( Bag, bagToList )
+
+import Monad           ( foldM )
 \end{code}
 
-
 %************************************************************************
 %*                                                                     *
 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
@@ -83,90 +46,140 @@ dsBinds mb_mod_grp (MonoBind binds sigs is_rec)
 %************************************************************************
 
 \begin{code}
-dsMonoBinds :: Maybe (Module, Group)   -- Nothing => don't (auto-)annotate scc on toplevs.
-           -> RecFlag 
-           -> TypecheckedMonoBinds 
-           -> DsM [(Id,CoreExpr)]
+dsHsBinds :: AutoScc            -- scc annotation policy (see below)
+         -> Bag (LHsBind Id)
+         -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
+         -> DsM [(Id,CoreExpr)] -- Result
 
-dsMonoBinds _ is_rec EmptyMonoBinds = returnDs []
+dsHsBinds auto_scc binds rest = 
+  foldM (dsLHsBind auto_scc) rest (bagToList binds)
 
-dsMonoBinds mb_mod_grp is_rec (AndMonoBinds  binds_1 binds_2)
-  = andDs (++) (dsMonoBinds mb_mod_grp is_rec binds_1) (dsMonoBinds mb_mod_grp is_rec binds_2)
+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
 
-dsMonoBinds _ is_rec (CoreMonoBind var core_expr)
-  = returnDs [(var, core_expr)]
+dsHsBind :: AutoScc
+        -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
+        -> HsBind Id
+        -> DsM [(Id,CoreExpr)] -- Result
 
-dsMonoBinds _ is_rec (VarMonoBind var expr)
-  = dsExpr expr                        `thenDs` \ core_expr ->
+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')]
-
-dsMonoBinds mb_mod_grp is_rec (FunMonoBind fun _ matches locn)
-  = putSrcLocDs locn   $
-    matchWrapper (FunMatch fun) matches error_string   `thenDs` \ (args, body) ->
-    returnDs [addAutoScc mb_mod_grp (fun, mkValLam args body)]
-  where
-    error_string = "function " ++ showForErr fun
-
-dsMonoBinds mb_mod_grp is_rec (PatMonoBind pat grhss_and_binds locn)
-  = putSrcLocDs locn $
-    dsGuarded grhss_and_binds          `thenDs` \ body_expr ->
-    mkSelectorBinds pat body_expr
+    let
+       -- Gross hack to prevent inlining into SpecPragmaId rhss
+       -- Consider     fromIntegral = fromInteger . toInteger
+       --              spec1 = fromIntegral Int Float
+       -- Even though fromIntegral is small we don't want to inline
+       -- it inside spec1, so that we collect the specialised call
+       -- Solution: make spec1 an INLINE thing.  
+       core_expr'' = mkInline (isSpecPragmaId var) core_expr'
+    in  
+
+    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)
+  = dsGuarded grhss                            `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
-dsMonoBinds mb_mod_grp is_rec (AbsBinds [] [] exports binds)
-  = dsMonoBinds Nothing is_rec binds                   `thenDs` \ prs ->
-    returnDs (prs ++ [ addAutoScc mb_mod_grp (global, Var local) | (_, global, local) <- exports])
+       -- 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 inlines binds)
+  = dsHsBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
+    let
+       core_prs' = addLocalInlines exports inlines core_prs
+       exports'  = [(global, Var local) | (_, global, local) <- exports]
+    in
+    returnDs (core_prs' ++ exports' ++ rest)
 
        -- Another common case: one exported variable
-       -- All non-recursive bindings come through this way
-dsMonoBinds mb_mod_grp is_rec (AbsBinds all_tyvars dicts [(tyvars, global, local)] binds)
+       -- Non-recursive bindings come through this way
+dsHsBind auto_scc rest
+     (AbsBinds all_tyvars dicts exps@[(tyvars, global, local)] inlines binds)
   = ASSERT( all (`elem` tyvars) all_tyvars )
-    dsMonoBinds Nothing is_rec binds                   `thenDs` \ core_prs ->
+    dsHsBinds (addSccs auto_scc exps) binds [] `thenDs` \ core_prs ->
     let 
-       core_binds | is_rec    = [Rec core_prs]
-                  | otherwise = [NonRec b e | (b,e) <- core_prs]
+       -- Always treat the binds as recursive, because the typechecker
+       -- makes rather mixed-up dictionary bindings
+       core_bind = Rec core_prs
+
+       -- The mkInline does directly what the 
+       -- addLocalInlines do in the other cases
+       export'    = (global, mkInline (idName global `elemNameSet` inlines) $
+                             mkLams tyvars $ mkLams dicts $ 
+                             Let core_bind (Var local))
     in
-    returnDs [addAutoScc mb_mod_grp (global, mkLam tyvars dicts $ 
-                                            mkCoLetsAny core_binds (Var local))]
+    returnDs (export' : rest)
 
-dsMonoBinds mb_mod_grp is_rec (AbsBinds all_tyvars dicts exports binds)
-  = dsMonoBinds Nothing is_rec binds                   `thenDs` \ core_prs ->
+dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports inlines binds)
+  = dsHsBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
     let 
-       core_binds | is_rec    = [Rec core_prs]
-                  | otherwise = [NonRec b e | (b,e) <- core_prs]
-
-       tup_expr = mkLam all_tyvars dicts $
-                  mkCoLetsAny core_binds $
-                  mkTupleExpr locals
-       locals    = [local | (_, _, local) <- exports]
-       local_tys = map idType locals
+       -- Rec because of mixed-up dictionary bindings
+       core_bind = Rec (addLocalInlines exports inlines 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 (coreExprType tup_expr)              `thenDs` \ tup_id ->
+    newSysLocalDs (exprType poly_tup_expr)             `thenDs` \ poly_tup_id ->
     let
-       dict_args    = map VarArg dicts
+       dict_args = map Var dicts
 
-       mk_bind (tyvars, global, local) n       -- locals !! n == local
+       mk_bind ((tyvars, global, local), 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 (instantiateTy env) local_tys)  `thenDs` \ locals' ->
-           returnDs (addAutoScc mb_mod_grp $
-                       (global, mkLam tyvars dicts $
-                                mkTupleSelector locals' (locals' !! n) $
-                                mkValApp (mkTyApp (Var tup_id) ty_args) dict_args))
+           newSysLocalsDs (map substitute local_tys)   `thenDs` \ locals' ->
+           newSysLocalDs  (substitute tup_ty)          `thenDs` \ tup_id ->
+           returnDs (global, mkLams tyvars $ mkLams dicts $
+                             mkTupleSelector locals' (locals' !! n) tup_id $
+                             mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args)
          where
            mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
                                | otherwise               = voidTy
-           ty_args = map mk_ty_arg all_tyvars
-           env     = all_tyvars `zip` ty_args
+           ty_args    = map mk_ty_arg all_tyvars
+           substitute = substTyWith all_tyvars ty_args
     in
-    zipWithDs mk_bind exports [0..]            `thenDs` \ export_binds ->
+    mappM mk_bind (exports `zip` [0..])                `thenDs` \ export_binds ->
      -- don't scc (auto-)annotate the tuple itself.
-    returnDs ((tup_id, tup_expr) : export_binds)
+    returnDs ((poly_tup_id, poly_tup_expr) : (export_binds ++ rest))
+\end{code}
+
+
+%************************************************************************
+%*                                                                     *
+\subsection{Adding inline pragmas}
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
+mkInline :: Bool -> CoreExpr -> CoreExpr
+mkInline True  body = mkInlineMe body
+mkInline False body = body
+
+addLocalInlines :: [(a, Id, Id)] -> NameSet -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
+addLocalInlines exports inlines pairs
+  = [(bndr, mkInline (bndr `elemVarSet` local_inlines) rhs) | (bndr,rhs) <- pairs]
+  where
+    local_inlines = mkVarSet [l | (_,g,l) <- exports, idName g `elemNameSet` inlines]
 \end{code}
 
 
@@ -177,41 +190,52 @@ dsMonoBinds mb_mod_grp is_rec (AbsBinds all_tyvars dicts exports binds)
 %************************************************************************
 
 \begin{code}
-addAutoScc :: Maybe (Module, Group)    -- Module and group
-          -> (Id, CoreExpr)
+data AutoScc
+       = TopLevel
+       | TopLevelAddSccs (Id -> Maybe Id)
+       | NoSccs
+
+addSccs :: AutoScc -> [(a,Id,Id)] -> 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)
-
-addAutoScc mb_mod_grp pair@(bndr, core_expr) 
-  = case mb_mod_grp of
-      Just (mod,grp) 
-       | worthSCC core_expr &&
-         (opt_AutoSccsOnAllToplevs ||
-          (isExported bndr && opt_AutoSccsOnExportedToplevs))
-        -> (bndr, SCC (mkAutoCC bndr mod grp IsNotCafCC) core_expr)
-      _ -> pair -- no auto-annotation.
-
-worthSCC (SCC _ _) = False
-worthSCC (Con _ _) = False
-worthSCC core_expr = True
+          -> 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}
 
-If profiling and dealing with a dict binding, wrap the dict in "_scc_ DICT <dict>":
+If profiling and dealing with a dict binding,
+wrap the dict in @_scc_ DICT <dict>@:
 
 \begin{code}
-addDictScc var rhs
-  | not ( opt_SccProfilingOn || opt_AutoSccsOnAllToplevs)
-           -- the latter is so that -unprof-auto-scc-all adds dict sccs
+addDictScc var rhs = returnDs rhs
+
+{- DISABLED for now (need to somehow make up a name for the scc) -- SDM
+  | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
     || not (isDictTy (idType var))
   = returnDs rhs                               -- That's easy: do nothing
 
-  | opt_CompilingGhcInternals
-  = returnDs (SCC prel_dicts_cc rhs)
-
   | otherwise
   = getModuleAndGroupDs        `thenDs` \ (mod, grp) ->
-
        -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
-    returnDs (SCC (mkAllDictsCC mod grp False) rhs)
-
-prel_dicts_cc = preludeDictsCostCentre False{-not dupd-} -- ditto
+    returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
+-}
 \end{code}