aa47275437353cbeb7f242c7b3fdfa8da5b472bb
[ghc-hetmet.git] / ghc / compiler / specialise / Rules.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreRules]{Transformation rules}
5
6 \begin{code}
7 module Rules (
8         RuleBase, prepareLocalRuleBase, prepareOrphanRuleBase,
9         unionRuleBase, lookupRule, addRule, addIdSpecialisations,
10         ProtoCoreRule(..), pprProtoCoreRule, pprRuleBase,
11         localRule, orphanRule
12     ) where
13
14 #include "HsVersions.h"
15
16 import CoreSyn          -- All of it
17 import OccurAnal        ( occurAnalyseRule )
18 import CoreFVs          ( exprFreeVars, idRuleVars, ruleRhsFreeVars, ruleSomeLhsFreeVars )
19 import CoreUnfold       ( isCheapUnfolding, unfoldingTemplate )
20 import CoreUtils        ( eqExpr )
21 import PprCore          ( pprCoreRule )
22 import Subst            ( Subst, InScopeSet, mkInScopeSet, lookupSubst, extendSubst,
23                           substEnv, setSubstEnv, emptySubst, isInScope,
24                           bindSubstList, unBindSubstList, substInScope, uniqAway
25                         )
26 import Id               ( Id, idUnfolding, zapLamIdInfo, 
27                           idSpecialisation, setIdSpecialisation,
28                           setIdNoDiscard
29                         ) 
30 import Name             ( isLocallyDefined )
31 import Var              ( isTyVar, isId )
32 import VarSet
33 import VarEnv
34 import Type             ( mkTyVarTy )
35 import qualified Unify  ( match )
36
37 import UniqFM
38 import Outputable
39 import Maybes           ( maybeToBool )
40 import Util             ( sortLt )
41 \end{code}
42
43
44 %************************************************************************
45 %*                                                                      *
46 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
47 %*                                                                      *
48 %************************************************************************
49
50 A @CoreRule@ holds details of one rule for an @Id@, which
51 includes its specialisations.
52
53 For example, if a rule for @f@ contains the mapping:
54 \begin{verbatim}
55         forall a b d. [Type (List a), Type b, Var d]  ===>  f' a b
56 \end{verbatim}
57 then when we find an application of f to matching types, we simply replace
58 it by the matching RHS:
59 \begin{verbatim}
60         f (List Int) Bool dict ===>  f' Int Bool
61 \end{verbatim}
62 All the stuff about how many dictionaries to discard, and what types
63 to apply the specialised function to, are handled by the fact that the
64 Rule contains a template for the result of the specialisation.
65
66 There is one more exciting case, which is dealt with in exactly the same
67 way.  If the specialised value is unboxed then it is lifted at its
68 definition site and unlifted at its uses.  For example:
69
70         pi :: forall a. Num a => a
71
72 might have a specialisation
73
74         [Int#] ===>  (case pi' of Lift pi# -> pi#)
75
76 where pi' :: Lift Int# is the specialised version of pi.
77
78
79 %************************************************************************
80 %*                                                                      *
81 \subsection{Matching}
82 %*                                                                      *
83 %************************************************************************
84
85 \begin{code}
86 matchRules :: InScopeSet -> [CoreRule] -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
87 -- See comments on matchRule
88 matchRules in_scope [] args = Nothing
89 matchRules in_scope (rule:rules) args
90   = case matchRule in_scope rule args of
91         Just result -> Just result
92         Nothing     -> matchRules in_scope rules args
93
94
95 matchRule :: InScopeSet -> CoreRule -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
96
97 -- If (matchRule rule args) returns Just (name,rhs)
98 -- then (f args) matches the rule, and the corresponding
99 -- rewritten RHS is rhs
100 --
101 -- The bndrs and rhs is occurrence-analysed
102 --
103 --      Example
104 --
105 -- The rule
106 --      forall f g x. map f (map g x) ==> map (f . g) x
107 -- is stored
108 --      CoreRule "map/map" 
109 --               [f,g,x]                -- tpl_vars
110 --               [f,map g x]            -- tpl_args
111 --               map (f.g) x)           -- rhs
112 --        
113 -- Then the call: matchRule the_rule [e1,map e2 e3]
114 --        = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
115 --
116 -- Any 'surplus' arguments in the input are simply put on the end
117 -- of the output.
118 --
119 -- ASSUMPTION (A):
120 --      A1. No top-level variable is bound in the target
121 --      A2. No template variable  is bound in the target
122 --      A3. No lambda bound template variable is free in any subexpression of the target
123 --
124 -- To see why A1 is necessary, consider matching
125 --      \x->f      against    \f->f
126 -- When we meet the lambdas we substitute [f/x] in the template (a no-op),
127 -- and then erroneously succeed in matching f against f.
128 --
129 -- To see why A2 is needed consider matching 
130 --      forall a. \b->b    against   \a->3
131 -- When we meet the lambdas we substitute [a/b] in the template, and then
132 -- erroneously succeed in matching what looks like the template variable 'a' against 3.
133 --
134 -- A3 is needed to validate the rule that says
135 --      (\x->E) matches F
136 -- if
137 --      (\x->E) matches (\x->F x)
138
139
140 matchRule in_scope rule@(BuiltinRule match_fn) args = match_fn args
141
142 matchRule in_scope rule@(Rule rn tpl_vars tpl_args rhs) args
143   = go tpl_args args emptySubst
144         -- We used to use the in_scope set, but I don't think that's necessary
145         -- After all, the result is going to be simplified again with that in_scope set
146  where
147    tpl_var_set = mkVarSet tpl_vars
148
149    -----------------------
150         -- Do the business
151    go (tpl_arg:tpl_args) (arg:args) subst = match tpl_arg arg tpl_var_set (go tpl_args args) subst
152
153         -- Two easy ways to terminate
154    go [] []         subst = Just (rn, app_match subst (mkLams tpl_vars rhs) tpl_vars)
155    go [] args       subst = Just (rn, app_match subst (mkLams tpl_vars rhs) tpl_vars `mkApps` args)
156
157         -- One tiresome way to terminate: check for excess unmatched
158         -- template arguments
159    go tpl_args []   subst = Nothing     -- Failure
160
161
162    -----------------------
163    app_match subst fn vs = foldl go fn vs
164         where   
165           senv    = substEnv subst
166           go fn v = case lookupSubstEnv senv v of
167                         Just (DoneEx ex)  -> fn `App` ex 
168                         Just (DoneTy ty)  -> fn `App` Type ty
169                         -- Substitution should bind them all!
170
171
172    -----------------------
173 {-      The code below tries to match even if there are more 
174         template args than real args.
175
176         I now think this is probably a bad idea.
177         Should the template (map f xs) match (map g)?  I think not.
178         For a start, in general eta expansion wastes work.
179         SLPJ July 99
180
181       = case eta_complete tpl_args (mkVarSet leftovers) of
182             Just leftovers' -> Just (rn, mkLams done (mkLams leftovers' rhs), 
183                                      mk_result_args subst done)
184             Nothing         -> Nothing  -- Failure
185       where
186         (done, leftovers) = partition (\v -> maybeToBool (lookupSubstEnv subst_env v))
187                                       (map zapOccInfo tpl_vars)
188                 -- Zap the occ info 
189         subst_env = substEnv subst
190                                                 
191    -----------------------
192    eta_complete [] vars = ASSERT( isEmptyVarSet vars )
193                           Just []
194    eta_complete (Type ty:tpl_args) vars
195         = case getTyVar_maybe ty of
196                 Just tv |  tv `elemVarSet` vars
197                         -> case eta_complete tpl_args (vars `delVarSet` tv) of
198                                 Just vars' -> Just (tv:vars')
199                                 Nothing    -> Nothing
200                 other   -> Nothing
201
202    eta_complete (Var v:tpl_args) vars
203         | v `elemVarSet` vars
204         = case eta_complete tpl_args (vars `delVarSet` v) of
205                 Just vars' -> Just (v:vars')
206                 Nothing    -> Nothing
207
208    eta_complete other vars = Nothing
209 -}
210
211
212 zapOccInfo bndr | isTyVar bndr = bndr
213                 | otherwise    = zapLamIdInfo bndr
214 \end{code}
215
216 \begin{code}
217 type Matcher result =  VarSet                   -- Template variables
218                     -> (Subst -> Maybe result)  -- Continuation if success
219                     -> Subst  -> Maybe result   -- Substitution so far -> result
220 -- The *SubstEnv* in these Substs apply to the TEMPLATE only 
221
222 -- The *InScopeSet* in these Substs gives variables bound so far in the
223 --      target term.  So when matching forall a. (\x. a x) against (\y. y y)
224 --      while processing the body of the lambdas, the in-scope set will be {y}.
225 --      That lets us do the occurs-check when matching 'a' against 'y'
226
227 match :: CoreExpr               -- Template
228       -> CoreExpr               -- Target
229       -> Matcher result
230
231 match_fail = Nothing
232
233 match (Var v1) e2 tpl_vars kont subst
234   = case lookupSubst subst v1 of
235         Nothing | v1 `elemVarSet` tpl_vars      -- v1 is a template variable
236                 -> if (any (`isInScope` subst) (varSetElems (exprFreeVars e2))) then
237                          match_fail             -- Occurs check failure
238                                                 -- e.g. match forall a. (\x-> a x) against (\y. y y)
239                    else
240                          kont (extendSubst subst v1 (DoneEx e2))
241
242
243                 | eqExpr (Var v1) e2             -> kont subst
244                         -- v1 is not a template variable, so it must be a global constant
245
246         Just (DoneEx e2')  | eqExpr e2'       e2 -> kont subst
247
248         other -> match_fail
249
250 match (Lit lit1) (Lit lit2) tpl_vars kont subst
251   | lit1 == lit2
252   = kont subst
253
254 match (App f1 a1) (App f2 a2) tpl_vars kont subst
255   = match f1 f2 tpl_vars (match a1 a2 tpl_vars kont) subst
256
257 match (Lam x1 e1) (Lam x2 e2) tpl_vars kont subst
258   = bind [x1] [x2] (match e1 e2) tpl_vars kont subst
259
260 -- This rule does eta expansion
261 --              (\x.M)  ~  N    iff     M  ~  N x
262 -- See assumption A3
263 match (Lam x1 e1) e2 tpl_vars kont subst
264   = bind [x1] [x1] (match e1 (App e2 (mkVarArg x1))) tpl_vars kont subst
265
266 -- Eta expansion the other way
267 --      M  ~  (\y.N)    iff   \y.M y  ~  \y.N
268 --                      iff   M y     ~  N
269 -- Remembering that by (A), y can't be free in M, we get this
270 match e1 (Lam x2 e2) tpl_vars kont subst
271   = bind [new_id] [x2] (match (App e1 (mkVarArg new_id)) e2) tpl_vars kont subst
272   where
273     new_id = uniqAway (substInScope subst) x2
274         -- This uniqAway is actually needed.  Here's the example:
275         --  rule:       foldr (mapFB (:) f) [] = mapList
276         --  target:     foldr (\x. mapFB k f x) []
277         --            where
278         --              k = \x. mapFB ... x
279         -- The first \x is ok, but when we inline k, hoping it might
280         -- match (:) we find a second \x.
281
282 match (Case e1 x1 alts1) (Case e2 x2 alts2) tpl_vars kont subst
283   = match e1 e2 tpl_vars case_kont subst
284   where
285     case_kont subst = bind [x1] [x2] (match_alts alts1 (sortLt lt_alt alts2))
286                                      tpl_vars kont subst
287
288 match (Type ty1) (Type ty2) tpl_vars kont subst
289   = match_ty ty1 ty2 tpl_vars kont subst
290
291 match (Note (Coerce to1 from1) e1) (Note (Coerce to2 from2) e2)
292       tpl_vars kont subst
293   = (match_ty to1   to2   tpl_vars $
294      match_ty from1 from2 tpl_vars $
295      match e1 e2 tpl_vars kont) subst
296
297
298 {-      I don't buy this let-rule any more
299         The let rule fails on matching
300                 forall f,x,xs. f (x:xs)
301         against
302                 f (let y = e in (y:[]))
303         because we just get x->y, which is bogus.
304
305 -- This is an interesting rule: we simply ignore lets in the 
306 -- term being matched against!  The unfolding inside it is (by assumption)
307 -- already inside any occurrences of the bound variables, so we'll expand
308 -- them when we encounter them.  Meanwhile, we can't get false matches because
309 -- (also by assumption) the term being matched has no shadowing.
310 match e1 (Let bind e2) tpl_vars kont subst
311   = match e1 e2 tpl_vars kont subst
312 -}
313
314 -- Here is another important rule: if the term being matched is a
315 -- variable, we expand it so long as its unfolding is a WHNF
316 -- (Its occurrence information is not necessarily up to date,
317 --  so we don't use it.)
318 match e1 (Var v2) tpl_vars kont subst
319   | isCheapUnfolding unfolding
320   = match e1 (unfoldingTemplate unfolding) tpl_vars kont subst
321   where
322     unfolding = idUnfolding v2
323
324
325 -- We can't cope with lets in the template
326
327 match e1 e2 tpl_vars kont subst = match_fail
328
329
330 ------------------------------------------
331 match_alts [] [] tpl_vars kont subst
332   = kont subst
333 match_alts ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2) tpl_vars kont subst
334   | c1 == c2
335   = bind vs1 vs2 (match r1 r2) tpl_vars
336                  (match_alts alts1 alts2 tpl_vars kont)
337                  subst
338 match_alts alts1 alts2 tpl_vars kont subst = match_fail
339
340 lt_alt (con1, _, _) (con2, _, _) = con1 < con2
341
342 ----------------------------------------
343 bind :: [CoreBndr]      -- Template binders
344      -> [CoreBndr]      -- Target binders
345      -> Matcher result
346      -> Matcher result
347 -- This makes uses of assumption (A) above.  For example,
348 -- this would fail:
349 --      Template: (\x.y)        (y is free)
350 --      Target  : (\y.y)        (y is bound)
351 -- We rename x to y in the template... but then erroneously
352 -- match y against y.  But this can't happen because of (A)
353 bind vs1 vs2 matcher tpl_vars kont subst
354   = WARN( not (all not_in_subst vs1), bug_msg )
355     matcher tpl_vars kont' subst'
356   where
357     kont' subst'' = kont (unBindSubstList subst'' vs1 vs2)
358     subst'        = bindSubstList subst vs1 vs2
359
360         -- The unBindSubst relies on no shadowing in the template
361     not_in_subst v = not (maybeToBool (lookupSubst subst v))
362     bug_msg = sep [ppr vs1, ppr vs2]
363
364 ----------------------------------------
365 match_ty ty1 ty2 tpl_vars kont subst
366   = case Unify.match ty1 ty2 tpl_vars Just (substEnv subst) of
367         Nothing    -> match_fail
368         Just senv' -> kont (setSubstEnv subst senv') 
369
370 ----------------------------------------
371 matches [] [] tpl_vars kont subst 
372   = kont subst
373 matches (e:es) (e':es') tpl_vars kont subst
374   = match e e' tpl_vars (matches es es' tpl_vars kont) subst
375 matches es es' tpl_vars kont subst 
376   = match_fail
377
378 ----------------------------------------
379 mkVarArg :: CoreBndr -> CoreArg
380 mkVarArg v | isId v    = Var v
381            | otherwise = Type (mkTyVarTy v)
382 \end{code}
383
384 %************************************************************************
385 %*                                                                      *
386 \subsection{Adding a new rule}
387 %*                                                                      *
388 %************************************************************************
389
390 \begin{code}
391 addRule :: Id -> CoreRules -> CoreRule -> CoreRules
392
393 -- Insert the new rule just before a rule that is *less specific*
394 -- than the new one; or at the end if there isn't such a one.
395 -- In this way we make sure that when looking up, the first match
396 -- is the most specific.
397 --
398 -- We make no check for rules that unify without one dominating
399 -- the other.   Arguably this would be a bug.
400
401 addRule id (Rules rules rhs_fvs) rule@(BuiltinRule _)
402   = Rules (rule:rules) rhs_fvs
403         -- Put it at the start for lack of anything better
404
405 addRule id (Rules rules rhs_fvs) rule
406   = Rules (insertRule rules new_rule) (rhs_fvs `unionVarSet` new_rhs_fvs)
407   where
408     new_rule    = occurAnalyseRule rule
409     new_rhs_fvs = ruleRhsFreeVars new_rule `delVarSet` id
410         -- Hack alert!
411         -- Don't include the Id in its own rhs free-var set.
412         -- Otherwise the occurrence analyser makes bindings recursive
413         -- that shoudn't be.  E.g.
414         --      RULE:  f (f x y) z  ==>  f x (f y z)
415
416 insertRule rules new_rule@(Rule _ tpl_vars tpl_args _)
417   = go rules
418   where
419     tpl_var_set = mkInScopeSet (mkVarSet tpl_vars)
420         -- Actually we should probably include the free vars of tpl_args,
421         -- but I can't be bothered
422
423     go []                                       = [new_rule]
424     go (rule:rules) | new_is_more_specific rule = (new_rule:rule:rules)
425                     | otherwise                 = rule : go rules
426
427     new_is_more_specific rule = maybeToBool (matchRule tpl_var_set rule tpl_args)
428
429 addIdSpecialisations :: Id -> [([CoreBndr], [CoreExpr], CoreExpr)] -> Id
430 addIdSpecialisations id spec_stuff
431   = setIdSpecialisation id new_rules
432   where
433     rule_name = _PK_ ("SPEC " ++ showSDoc (ppr id))
434     new_rules = foldr add (idSpecialisation id) spec_stuff
435     add (vars, args, rhs) rules = addRule id rules (Rule rule_name vars args rhs)
436 \end{code}
437
438
439 %************************************************************************
440 %*                                                                      *
441 \subsection{Preparing the rule base
442 %*                                                                      *
443 %************************************************************************
444
445 \begin{code}
446 data ProtoCoreRule 
447   = ProtoCoreRule 
448         Bool            -- True <=> this rule was defined in this module,
449         Id              -- What Id is it for
450         CoreRule        -- The rule itself
451         
452
453 pprProtoCoreRule (ProtoCoreRule _ fn rule) = pprCoreRule (ppr fn) rule
454
455 lookupRule :: InScopeSet -> Id -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
456 lookupRule in_scope fn args
457   = case idSpecialisation fn of
458         Rules rules _ -> matchRules in_scope rules args
459
460 localRule :: ProtoCoreRule -> Bool
461 localRule (ProtoCoreRule local _ _) = local
462
463 orphanRule :: ProtoCoreRule -> Bool
464 -- An "orphan rule" is one that is defined in this 
465 -- module, but for an *imported* function.  We need
466 -- to track these separately when generating the interface file
467 orphanRule (ProtoCoreRule local fn _)
468   = local && not (isLocallyDefined fn)
469 \end{code}
470
471
472 %************************************************************************
473 %*                                                                      *
474 \subsection{Getting the rules ready}
475 %*                                                                      *
476 %************************************************************************
477
478 \begin{code}
479 type RuleBase = (IdSet,         -- Imported Ids that have rules attached
480                  IdSet)         -- Ids (whether local or imported) mentioned on 
481                                 -- LHS of some rule; these should be black listed
482
483 unionRuleBase (rule_ids1, black_ids1) (rule_ids2, black_ids2)
484   = (plusUFM_C merge_rules rule_ids1 rule_ids2,
485      unionVarSet black_ids1 black_ids2)
486   where
487     merge_rules id1 id2 = let rules1 = idSpecialisation id1
488                               rules2 = idSpecialisation id2
489                               new_rules = foldl (addRule id1) rules1 (rulesRules rules2)
490                           in
491                           setIdSpecialisation id1 new_rules
492
493 pprRuleBase :: RuleBase -> SDoc
494 pprRuleBase (rules,_) = vcat [ pprCoreRule (ppr id) rs
495                              | id <- varSetElems rules,
496                                rs <- rulesRules $ idSpecialisation id ]
497
498 -- prepareLocalRuleBase takes the CoreBinds and rules defined in this module.
499 -- It attaches those rules that are for local Ids to their binders, and
500 -- returns the remainder attached to Ids in an IdSet.  It also returns
501 -- Ids mentioned on LHS of some rule; these should be blacklisted.
502
503 -- The rule Ids and LHS Ids are black-listed; that is, they aren't inlined
504 -- so that the opportunity to apply the rule isn't lost too soon
505
506 prepareLocalRuleBase :: [CoreBind] -> [ProtoCoreRule] -> ([CoreBind], RuleBase)
507 prepareLocalRuleBase binds local_rules
508   = (map zap_bind binds, (imported_id_rule_ids, rule_lhs_fvs))
509   where
510     (rule_ids, rule_lhs_fvs) = foldr add_rule (emptyVarSet, emptyVarSet) local_rules
511     imported_id_rule_ids = filterVarSet (not . isLocallyDefined) rule_ids
512
513         -- rule_fvs is the set of all variables mentioned in this module's rules
514     rule_fvs = foldVarSet (unionVarSet . idRuleVars) rule_lhs_fvs rule_ids
515
516         -- Attach the rules for each locally-defined Id to that Id.
517         --      - This makes the rules easier to look up
518         --      - It means that transformation rules and specialisations for
519         --        locally defined Ids are handled uniformly
520         --      - It keeps alive things that are referred to only from a rule
521         --        (the occurrence analyser knows about rules attached to Ids)
522         --      - It makes sure that, when we apply a rule, the free vars
523         --        of the RHS are more likely to be in scope
524         --
525         -- The LHS and RHS Ids are marked 'no-discard'. 
526         -- This means that the binding won't be discarded EVEN if the binding
527         -- ends up being trivial (v = w) -- the simplifier would usually just 
528         -- substitute w for v throughout, but we don't apply the substitution to
529         -- the rules (maybe we should?), so this substitution would make the rule
530         -- bogus.
531     zap_bind (NonRec b r) = NonRec (zap_bndr b) r
532     zap_bind (Rec prs)    = Rec [(zap_bndr b, r) | (b,r) <- prs]
533
534     zap_bndr bndr = case lookupVarSet rule_ids bndr of
535                           Just bndr'                           -> setIdNoDiscard bndr'
536                           Nothing | bndr `elemVarSet` rule_fvs -> setIdNoDiscard bndr
537                                   | otherwise                  -> bndr
538                   
539 add_rule (ProtoCoreRule _ id rule)
540          (rule_id_set, rule_fvs)
541   = (rule_id_set `extendVarSet` new_id,
542      rule_fvs `unionVarSet` extendVarSet lhs_fvs id)
543   where
544     new_id = case lookupVarSet rule_id_set id of
545                 Just id' -> addRuleToId id' rule
546                 Nothing  -> addRuleToId id  rule
547     lhs_fvs = ruleSomeLhsFreeVars isId rule
548         -- Find *all* the free Ids of the LHS, not just
549         -- locally defined ones!!
550
551 addRuleToId id rule = setIdSpecialisation id (addRule id (idSpecialisation id) rule)
552
553 -- prepareOrphanRuleBase does exactly the same as prepareLocalRuleBase, except that
554 -- it assumes that none of the rules can be attached to local Ids.
555
556 prepareOrphanRuleBase :: [ProtoCoreRule] -> RuleBase
557 prepareOrphanRuleBase imported_rules
558   = foldr add_rule (emptyVarSet, emptyVarSet) imported_rules
559 \end{code}