2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreRules]{Transformation rules}
8 RuleBase, emptyRuleBase, mkRuleBase, extendRuleBaseList,
9 unionRuleBase, pprRuleBase, ruleCheckProgram,
11 mkSpecInfo, extendSpecInfo, addSpecInfo,
12 rulesOfBinds, addIdSpecialisations,
14 lookupRule, mkLocalRule, roughTopNames
17 #include "HsVersions.h"
19 import CoreSyn -- All of it
20 import OccurAnal ( occurAnalyseExpr )
21 import CoreFVs ( exprFreeVars, exprsFreeVars, rulesRhsFreeVars )
22 import CoreUnfold ( isCheapUnfolding, unfoldingTemplate )
23 import CoreUtils ( tcEqExprX )
24 import PprCore ( pprRules )
25 import Type ( TvSubstEnv )
26 import TcType ( tcSplitTyConApp_maybe )
27 import CoreTidy ( tidyRules )
28 import Id ( Id, idUnfolding, isLocalId, isGlobalId, idName,
29 idSpecialisation, idCoreRules, setIdSpecialisation )
30 import IdInfo ( SpecInfo( SpecInfo ) )
32 import VarEnv ( IdEnv, InScopeSet, emptyTidyEnv,
33 emptyInScopeSet, mkInScopeSet, extendInScopeSetList,
34 emptyVarEnv, lookupVarEnv, extendVarEnv,
35 nukeRnEnvL, mkRnEnv2, rnOccR, rnOccL, inRnEnvR,
36 rnBndrR, rnBndr2, rnBndrL, rnBndrs2 )
38 import Name ( Name, NamedThing(..), nameOccName )
40 import Unify ( ruleMatchTyX, MatchEnv(..) )
41 import BasicTypes ( Activation, CompilerPhase, isActive )
44 import Maybes ( isJust, orElse )
46 import Util ( singleton )
47 import List ( isPrefixOf )
51 %************************************************************************
53 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
55 %************************************************************************
57 A @CoreRule@ holds details of one rule for an @Id@, which
58 includes its specialisations.
60 For example, if a rule for @f@ contains the mapping:
62 forall a b d. [Type (List a), Type b, Var d] ===> f' a b
64 then when we find an application of f to matching types, we simply replace
65 it by the matching RHS:
67 f (List Int) Bool dict ===> f' Int Bool
69 All the stuff about how many dictionaries to discard, and what types
70 to apply the specialised function to, are handled by the fact that the
71 Rule contains a template for the result of the specialisation.
73 There is one more exciting case, which is dealt with in exactly the same
74 way. If the specialised value is unboxed then it is lifted at its
75 definition site and unlifted at its uses. For example:
77 pi :: forall a. Num a => a
79 might have a specialisation
81 [Int#] ===> (case pi' of Lift pi# -> pi#)
83 where pi' :: Lift Int# is the specialised version of pi.
86 mkLocalRule :: RuleName -> Activation
87 -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
88 -- Used to make CoreRule for an Id defined in this module
89 mkLocalRule name act fn bndrs args rhs
90 = Rule { ru_name = name, ru_fn = fn, ru_act = act,
91 ru_bndrs = bndrs, ru_args = args,
92 ru_rhs = rhs, ru_rough = roughTopNames args,
93 ru_orph = Just (nameOccName fn), ru_local = True }
96 roughTopNames :: [CoreExpr] -> [Maybe Name]
97 roughTopNames args = map roughTopName args
99 roughTopName :: CoreExpr -> Maybe Name
100 -- Find the "top" free name of an expression
101 -- a) the function in an App chain (if a GlobalId)
102 -- b) the TyCon in a type
103 -- This is used for the fast-match-check for rules;
104 -- if the top names don't match, the rest can't
105 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
106 Just (tc,_) -> Just (getName tc)
108 roughTopName (App f a) = roughTopName f
109 roughTopName (Var f) | isGlobalId f = Just (idName f)
110 | otherwise = Nothing
111 roughTopName other = Nothing
113 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
114 -- (ruleCantMatch tpl actual) returns True only if 'actual'
115 -- definitely can't match 'tpl' by instantiating 'tpl'.
116 -- It's only a one-way match; unlike instance matching we
117 -- don't consider unification
118 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
119 ruleCantMatch (Just n1 : ts) (Nothing : as) = True
120 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
121 ruleCantMatch ts as = False
125 %************************************************************************
127 SpecInfo: the rules in an IdInfo
129 %************************************************************************
132 mkSpecInfo :: [CoreRule] -> SpecInfo
133 mkSpecInfo rules = SpecInfo rules (rulesRhsFreeVars rules)
135 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
136 extendSpecInfo (SpecInfo rs1 fvs1) rs2
137 = SpecInfo (rs2 ++ rs1) (rulesRhsFreeVars rs2 `unionVarSet` fvs1)
139 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
140 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
141 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
143 addIdSpecialisations :: Id -> [CoreRule] -> Id
144 addIdSpecialisations id rules
145 = setIdSpecialisation id $
146 extendSpecInfo (idSpecialisation id) rules
148 rulesOfBinds :: [CoreBind] -> [CoreRule]
149 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
153 %************************************************************************
157 %************************************************************************
160 type RuleBase = NameEnv [CoreRule]
161 -- Maps (the name of) an Id to its rules
162 -- The rules are are unordered;
163 -- we sort out any overlaps on lookup
165 emptyRuleBase = emptyNameEnv
167 mkRuleBase :: [CoreRule] -> RuleBase
168 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
170 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
171 extendRuleBaseList rule_base new_guys
172 = foldl extendRuleBase rule_base new_guys
174 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
175 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
177 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
178 extendRuleBase rule_base rule
179 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
181 pprRuleBase :: RuleBase -> SDoc
182 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
183 | rs <- nameEnvElts rules ]
187 %************************************************************************
189 \subsection{Matching}
191 %************************************************************************
194 lookupRule :: (Activation -> Bool) -> InScopeSet
195 -> RuleBase -- Imported rules
196 -> Id -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
197 lookupRule is_active in_scope rule_base fn args
198 = matchRules is_active in_scope fn args rules
200 -- The rules for an Id come from two places:
201 -- (a) the ones it is born with (idCoreRules fn)
202 -- (b) rules added in subsequent modules (extra_rules)
203 -- PrimOps, for example, are born with a bunch of rules under (a)
204 rules = extra_rules ++ idCoreRules fn
205 extra_rules | isLocalId fn = []
206 | otherwise = lookupNameEnv rule_base (idName fn) `orElse` []
208 matchRules :: (Activation -> Bool) -> InScopeSet
210 -> [CoreRule] -> Maybe (RuleName, CoreExpr)
211 -- See comments on matchRule
212 matchRules is_active in_scope fn args rules
213 = case go [] rules of
215 (m:ms) -> Just (case findBest (fn,args) m ms of
216 (rule, ans) -> (ru_name rule, ans))
218 rough_args = map roughTopName args
220 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
222 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
223 Just e -> go ((r,e):ms) rs
226 findBest :: (Id, [CoreExpr])
227 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
228 -- All these pairs matched the expression
229 -- Return the pair the the most specific rule
230 -- The (fn,args) is just for overlap reporting
232 findBest target (rule,ans) [] = (rule,ans)
233 findBest target (rule1,ans1) ((rule2,ans2):prs)
234 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
235 | rule2 `isMoreSpecific` rule1 = findBest target (rule1,ans1) prs
237 | otherwise = pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
238 (vcat [ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args),
239 ptext SLIT("Rule 1:") <+> ppr rule1,
240 ptext SLIT("Rule 2:") <+> ppr rule2]) $
241 findBest target (rule1,ans1) prs
243 | otherwise = findBest target (rule1,ans1) prs
248 isMoreSpecific :: CoreRule -> CoreRule -> Bool
249 isMoreSpecific (BuiltinRule {}) r2 = True
250 isMoreSpecific r1 (BuiltinRule {}) = False
251 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
252 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
253 = isJust (matchN in_scope bndrs2 args2 args1)
255 in_scope = mkInScopeSet (mkVarSet bndrs1)
256 -- Actually we should probably include the free vars
257 -- of rule1's args, but I can't be bothered
259 noBlackList :: Activation -> Bool
260 noBlackList act = False -- Nothing is black listed
262 matchRule :: (Activation -> Bool) -> InScopeSet
263 -> [CoreExpr] -> [Maybe Name]
264 -> CoreRule -> Maybe CoreExpr
266 -- If (matchRule rule args) returns Just (name,rhs)
267 -- then (f args) matches the rule, and the corresponding
268 -- rewritten RHS is rhs
270 -- The bndrs and rhs is occurrence-analysed
275 -- forall f g x. map f (map g x) ==> map (f . g) x
277 -- CoreRule "map/map"
278 -- [f,g,x] -- tpl_vars
279 -- [f,map g x] -- tpl_args
280 -- map (f.g) x) -- rhs
282 -- Then the call: matchRule the_rule [e1,map e2 e3]
283 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
285 -- Any 'surplus' arguments in the input are simply put on the end
288 matchRule is_active in_scope args rough_args
289 (BuiltinRule { ru_name = name, ru_try = match_fn })
290 = case match_fn args of
291 Just expr -> Just expr
294 matchRule is_active in_scope args rough_args
295 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
296 ru_bndrs = tpl_vars, ru_args = tpl_args,
298 | not (is_active act) = Nothing
299 | ruleCantMatch tpl_tops rough_args = Nothing
301 = case matchN in_scope tpl_vars tpl_args args of
303 Just (tpl_vals, leftovers) -> Just (rule_fn
307 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
308 -- We could do this when putting things into the rulebase, I guess
313 -> [Var] -- Template tyvars
314 -> [CoreExpr] -- Template
315 -> [CoreExpr] -- Target; can have more elts than template
316 -> Maybe ([CoreExpr], -- What is substituted for each template var
317 [CoreExpr]) -- Leftover target exprs
319 matchN in_scope tmpl_vars tmpl_es target_es
320 = do { (subst, leftover_es) <- go init_menv emptySubstEnv tmpl_es target_es
321 ; return (map (lookup_tmpl subst) tmpl_vars, leftover_es) }
323 init_menv = ME { me_tmpls = mkVarSet tmpl_vars, me_env = init_rn_env }
324 init_rn_env = mkRnEnv2 (extendInScopeSetList in_scope tmpl_vars)
326 go menv subst [] es = Just (subst, es)
327 go menv subst ts [] = Nothing -- Fail if too few actual args
328 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
329 ; go menv subst1 ts es }
331 lookup_tmpl :: (TvSubstEnv, IdSubstEnv) -> Var -> CoreExpr
332 lookup_tmpl (tv_subst, id_subst) tmpl_var
333 | isTyVar tmpl_var = case lookupVarEnv tv_subst tmpl_var of
335 Nothing -> unbound tmpl_var
336 | otherwise = case lookupVarEnv id_subst tmpl_var of
338 other -> unbound tmpl_var
340 unbound var = pprPanic "Template variable unbound in rewrite rule" (ppr var)
344 ---------------------------------------------
345 The inner workings of matching
346 ---------------------------------------------
349 -- These two definitions are not the same as in Subst,
350 -- but they simple and direct, and purely local to this module
351 -- The third, for TvSubstEnv, is the same as in VarEnv, but repeated here
352 -- for uniformity with IdSubstEnv
353 type SubstEnv = (TvSubstEnv, IdSubstEnv)
354 type IdSubstEnv = IdEnv CoreExpr
356 emptySubstEnv :: SubstEnv
357 emptySubstEnv = (emptyVarEnv, emptyVarEnv)
360 -- At one stage I tried to match even if there are more
361 -- template args than real args.
363 -- I now think this is probably a bad idea.
364 -- Should the template (map f xs) match (map g)? I think not.
365 -- For a start, in general eta expansion wastes work.
371 -> CoreExpr -- Template
372 -> CoreExpr -- Target
375 -- See the notes with Unify.match, which matches types
376 -- Everything is very similar for terms
378 -- Interesting examples:
380 -- \x->f against \f->f
381 -- When we meet the lambdas we must remember to rename f to f' in the
382 -- second expresion. The RnEnv2 does that.
385 -- forall a. \b->b against \a->3
386 -- We must rename the \a. Otherwise when we meet the lambdas we
387 -- might substitute [a/b] in the template, and then erroneously
388 -- succeed in matching what looks like the template variable 'a' against 3.
390 -- The Var case follows closely what happens in Unify.match
391 match menv subst@(tv_subst, id_subst) (Var v1) e2
392 | v1 `elemVarSet` me_tmpls menv
393 = case lookupVarEnv id_subst v1' of
394 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
395 -> Nothing -- Occurs check failure
396 -- e.g. match forall a. (\x-> a x) against (\y. y y)
399 -> Just (tv_subst, extendVarEnv id_subst v1 e2)
401 Just e2' | tcEqExprX (nukeRnEnvL rn_env) e2' e2
406 | otherwise -- v1 is not a template variable
408 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
412 v1' = rnOccL rn_env v1
414 -- Here is another important rule: if the term being matched is a
415 -- variable, we expand it so long as its unfolding is a WHNF
416 -- (Its occurrence information is not necessarily up to date,
417 -- so we don't use it.)
418 match menv subst e1 (Var v2)
419 | isCheapUnfolding unfolding
420 = match menv subst e1 (unfoldingTemplate unfolding)
422 unfolding = idUnfolding v2
424 match menv subst (Lit lit1) (Lit lit2)
428 match menv subst (App f1 a1) (App f2 a2)
429 = do { subst' <- match menv subst f1 f2
430 ; match menv subst' a1 a2 }
432 match menv subst (Lam x1 e1) (Lam x2 e2)
433 = match menv' subst e1 e2
435 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
437 -- This rule does eta expansion
438 -- (\x.M) ~ N iff M ~ N x
439 match menv subst (Lam x1 e1) e2
440 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
442 (rn_env', new_x) = rnBndrL (me_env menv) x1
443 menv' = menv { me_env = rn_env' }
445 -- Eta expansion the other way
446 -- M ~ (\y.N) iff M y ~ N
447 match menv subst e1 (Lam x2 e2)
448 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
450 (rn_env', new_x) = rnBndrR (me_env menv) x2
451 menv' = menv { me_env = rn_env' }
453 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
454 = do { subst1 <- match_ty menv subst ty1 ty2
455 ; subst2 <- match menv subst1 e1 e2
456 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x2 x2 }
457 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
460 match menv subst (Type ty1) (Type ty2)
461 = match_ty menv subst ty1 ty2
463 match menv subst (Note (Coerce to1 from1) e1) (Note (Coerce to2 from2) e2)
464 = do { subst1 <- match_ty menv subst to1 to2
465 ; subst2 <- match_ty menv subst1 from1 from2
466 ; match menv subst2 e1 e2 }
468 -- This is an interesting rule: we simply ignore lets in the
469 -- term being matched against! The unfolding inside it is (by assumption)
470 -- already inside any occurrences of the bound variables, so we'll expand
471 -- them when we encounter them.
472 match menv subst e1 (Let (NonRec x2 r2) e2)
473 = match menv' subst e1 e2
475 menv' = menv { me_env = fst (rnBndrR (me_env menv) x2) }
476 -- It's important to do this renaming. For example:
478 -- forall f,x,xs. f (x:xs)
480 -- f (let y = e in (y:[]))
481 -- We must not get success with x->y! Instead, we
482 -- need an occurs check.
484 -- Everything else fails
485 match menv subst e1 e2 = Nothing
487 ------------------------------------------
488 match_alts :: MatchEnv
490 -> [CoreAlt] -- Template
491 -> [CoreAlt] -- Target
493 match_alts menv subst [] []
495 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
497 = do { subst1 <- match menv' subst r1 r2
498 ; match_alts menv subst1 alts1 alts2 }
501 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
503 match_alts menv subst alts1 alts2
507 Matching Core types: use the matcher in TcType.
508 Notice that we treat newtypes as opaque. For example, suppose
509 we have a specialised version of a function at a newtype, say
511 We only want to replace (f T) with f', not (f Int).
514 ------------------------------------------
515 match_ty menv (tv_subst, id_subst) ty1 ty2
516 = do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
517 ; return (tv_subst', id_subst) }
521 %************************************************************************
523 \subsection{Checking a program for failing rule applications}
525 %************************************************************************
527 -----------------------------------------------------
529 -----------------------------------------------------
531 We want to know what sites have rules that could have fired but didn't.
532 This pass runs over the tree (without changing it) and reports such.
534 NB: we assume that this follows a run of the simplifier, so every Id
535 occurrence (including occurrences of imported Ids) is decorated with
536 all its (active) rules. No need to construct a rule base or anything
540 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
541 -- Report partial matches for rules beginning
542 -- with the specified string
543 ruleCheckProgram phase rule_pat binds
545 = text "Rule check results: no rule application sites"
547 = vcat [text "Rule check results:",
549 vcat [ p $$ line | p <- bagToList results ]
552 results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
553 line = text (replicate 20 '-')
555 type RuleCheckEnv = (CompilerPhase, String) -- Phase and Pattern
557 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
558 -- The Bag returned has one SDoc for each call site found
559 ruleCheckBind env (NonRec b r) = ruleCheck env r
560 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
562 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
563 ruleCheck env (Var v) = emptyBag
564 ruleCheck env (Lit l) = emptyBag
565 ruleCheck env (Type ty) = emptyBag
566 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
567 ruleCheck env (Note n e) = ruleCheck env e
568 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
569 ruleCheck env (Lam b e) = ruleCheck env e
570 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
571 unionManyBags [ruleCheck env r | (_,_,r) <- as]
573 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
574 ruleCheckApp env (Var f) as = ruleCheckFun env f as
575 ruleCheckApp env other as = ruleCheck env other
579 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
580 -- Produce a report for all rules matching the predicate
581 -- saying why it doesn't match the specified application
583 ruleCheckFun (phase, pat) fn args
584 | null name_match_rules = emptyBag
585 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
587 name_match_rules = filter match (idCoreRules fn)
588 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
590 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
591 ruleAppCheck_help phase fn args rules
592 = -- The rules match the pattern, so we want to print something
593 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
594 vcat (map check_rule rules)]
597 i_args = args `zip` [1::Int ..]
598 rough_args = map roughTopName args
600 check_rule rule = rule_herald rule <> colon <+> rule_info rule
602 rule_herald (BuiltinRule { ru_name = name })
603 = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
604 rule_herald (Rule { ru_name = name })
605 = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
608 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
609 = text "matches (which is very peculiar!)"
611 rule_info (BuiltinRule {}) = text "does not match"
613 rule_info (Rule { ru_name = name, ru_act = act,
614 ru_bndrs = rule_bndrs, ru_args = rule_args})
615 | not (isActive phase act) = text "active only in later phase"
616 | n_args < n_rule_args = text "too few arguments"
617 | n_mismatches == n_rule_args = text "no arguments match"
618 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
619 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
621 n_rule_args = length rule_args
622 n_mismatches = length mismatches
623 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
624 not (isJust (match_fn rule_arg arg))]
626 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
627 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
629 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
630 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
631 , me_tmpls = mkVarSet rule_bndrs }