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 )
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, TyVarEnv, 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 ( tcMatchTyX, MatchEnv(..) )
41 import BasicTypes ( Activation, CompilerPhase, isActive )
45 import Maybe ( isJust )
47 import Util ( singleton )
48 import List ( isPrefixOf )
52 %************************************************************************
54 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
56 %************************************************************************
58 A @CoreRule@ holds details of one rule for an @Id@, which
59 includes its specialisations.
61 For example, if a rule for @f@ contains the mapping:
63 forall a b d. [Type (List a), Type b, Var d] ===> f' a b
65 then when we find an application of f to matching types, we simply replace
66 it by the matching RHS:
68 f (List Int) Bool dict ===> f' Int Bool
70 All the stuff about how many dictionaries to discard, and what types
71 to apply the specialised function to, are handled by the fact that the
72 Rule contains a template for the result of the specialisation.
74 There is one more exciting case, which is dealt with in exactly the same
75 way. If the specialised value is unboxed then it is lifted at its
76 definition site and unlifted at its uses. For example:
78 pi :: forall a. Num a => a
80 might have a specialisation
82 [Int#] ===> (case pi' of Lift pi# -> pi#)
84 where pi' :: Lift Int# is the specialised version of pi.
87 mkLocalRule :: RuleName -> Activation
88 -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
89 -- Used to make CoreRule for an Id defined in this module
90 mkLocalRule name act fn bndrs args rhs
91 = Rule { ru_name = name, ru_fn = fn, ru_act = act,
92 ru_bndrs = bndrs, ru_args = args,
93 ru_rhs = rhs, ru_rough = roughTopNames args,
94 ru_orph = Just (nameOccName fn), ru_local = True }
97 roughTopNames :: [CoreExpr] -> [Maybe Name]
98 roughTopNames args = map roughTopName args
100 roughTopName :: CoreExpr -> Maybe Name
101 -- Find the "top" free name of an expression
102 -- a) the function in an App chain (if a GlobalId)
103 -- b) the TyCon in a type
104 -- This is used for the fast-match-check for rules;
105 -- if the top names don't match, the rest can't
106 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
107 Just (tc,_) -> Just (getName tc)
109 roughTopName (App f a) = roughTopName f
110 roughTopName (Var f) | isGlobalId f = Just (idName f)
111 | otherwise = Nothing
112 roughTopName other = Nothing
114 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
115 -- (ruleCantMatch tpl actual) returns True only if 'actual'
116 -- definitely can't match 'tpl' by instantiating 'tpl'.
117 -- It's only a one-way match; unlike instance matching we
118 -- don't consider unification
119 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
120 ruleCantMatch (Just n1 : ts) (Nothing : as) = True
121 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
122 ruleCantMatch ts as = False
126 %************************************************************************
128 SpecInfo: the rules in an IdInfo
130 %************************************************************************
133 mkSpecInfo :: [CoreRule] -> SpecInfo
134 mkSpecInfo rules = SpecInfo rules (rulesRhsFreeVars rules)
136 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
137 extendSpecInfo (SpecInfo rs1 fvs1) rs2
138 = SpecInfo (rs2 ++ rs1) (rulesRhsFreeVars rs2 `unionVarSet` fvs1)
140 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
141 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
142 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
144 addIdSpecialisations :: Id -> [CoreRule] -> Id
145 addIdSpecialisations id rules
146 = setIdSpecialisation id $
147 extendSpecInfo (idSpecialisation id) rules
149 rulesOfBinds :: [CoreBind] -> [CoreRule]
150 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
154 %************************************************************************
158 %************************************************************************
161 type RuleBase = NameEnv [CoreRule]
162 -- Maps (the name of) an Id to its rules
163 -- The rules are are unordered;
164 -- we sort out any overlaps on lookup
166 emptyRuleBase = emptyNameEnv
168 mkRuleBase :: [CoreRule] -> RuleBase
169 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
171 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
172 extendRuleBaseList rule_base new_guys
173 = foldl extendRuleBase rule_base new_guys
175 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
176 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
178 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
179 extendRuleBase rule_base rule
180 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
182 pprRuleBase :: RuleBase -> SDoc
183 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
184 | rs <- nameEnvElts rules ]
188 %************************************************************************
190 \subsection{Matching}
192 %************************************************************************
195 lookupRule :: (Activation -> Bool) -> InScopeSet
196 -> RuleBase -- Imported rules
197 -> Id -> [CoreExpr] -> Maybe (RuleName, CoreExpr)
198 lookupRule is_active in_scope rule_base fn args
199 = matchRules is_active in_scope fn args rules
201 rules | isLocalId fn = idCoreRules fn
202 | otherwise = case lookupNameEnv rule_base (idName fn) of
206 matchRules :: (Activation -> Bool) -> InScopeSet
208 -> [CoreRule] -> Maybe (RuleName, CoreExpr)
209 -- See comments on matchRule
210 matchRules is_active in_scope fn args rules
211 = case go [] rules of
213 (m:ms) -> Just (case findBest (fn,args) m ms of
214 (rule, ans) -> (ru_name rule, ans))
216 rough_args = map roughTopName args
218 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
220 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
221 Just e -> go ((r,e):ms) rs
224 findBest :: (Id, [CoreExpr])
225 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
226 -- All these pairs matched the expression
227 -- Return the pair the the most specific rule
228 -- The (fn,args) is just for overlap reporting
230 findBest target (rule,ans) [] = (rule,ans)
231 findBest target (rule1,ans1) ((rule2,ans2):prs)
232 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
233 | rule2 `isMoreSpecific` rule1 = findBest target (rule1,ans1) prs
235 | otherwise = pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
236 (vcat [ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args),
237 ptext SLIT("Rule 1:") <+> ppr rule1,
238 ptext SLIT("Rule 2:") <+> ppr rule2]) $
239 findBest target (rule1,ans1) prs
241 | otherwise = findBest target (rule1,ans1) prs
246 isMoreSpecific :: CoreRule -> CoreRule -> Bool
247 isMoreSpecific (BuiltinRule {}) r2 = True
248 isMoreSpecific r1 (BuiltinRule {}) = False
249 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
250 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
251 = isJust (matchN in_scope bndrs2 args2 args1)
253 in_scope = mkInScopeSet (mkVarSet bndrs1)
254 -- Actually we should probably include the free vars
255 -- of rule1's args, but I can't be bothered
257 noBlackList :: Activation -> Bool
258 noBlackList act = False -- Nothing is black listed
260 matchRule :: (Activation -> Bool) -> InScopeSet
261 -> [CoreExpr] -> [Maybe Name]
262 -> CoreRule -> Maybe CoreExpr
264 -- If (matchRule rule args) returns Just (name,rhs)
265 -- then (f args) matches the rule, and the corresponding
266 -- rewritten RHS is rhs
268 -- The bndrs and rhs is occurrence-analysed
273 -- forall f g x. map f (map g x) ==> map (f . g) x
275 -- CoreRule "map/map"
276 -- [f,g,x] -- tpl_vars
277 -- [f,map g x] -- tpl_args
278 -- map (f.g) x) -- rhs
280 -- Then the call: matchRule the_rule [e1,map e2 e3]
281 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
283 -- Any 'surplus' arguments in the input are simply put on the end
286 matchRule is_active in_scope args rough_args
287 (BuiltinRule { ru_name = name, ru_try = match_fn })
288 = case match_fn args of
289 Just expr -> Just expr
292 matchRule is_active in_scope args rough_args
293 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
294 ru_bndrs = tpl_vars, ru_args = tpl_args,
296 | not (is_active act) = Nothing
297 | ruleCantMatch tpl_tops rough_args = Nothing
299 = case matchN in_scope tpl_vars tpl_args args of
301 Just (tpl_vals, leftovers) -> Just (rule_fn
305 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
306 -- We could do this when putting things into the rulebase, I guess
311 -> [Var] -- Template tyvars
312 -> [CoreExpr] -- Template
313 -> [CoreExpr] -- Target; can have more elts than template
314 -> Maybe ([CoreExpr], -- What is substituted for each template var
315 [CoreExpr]) -- Leftover target exprs
317 matchN in_scope tmpl_vars tmpl_es target_es
318 = do { (subst, leftover_es) <- go init_menv emptySubstEnv tmpl_es target_es
319 ; return (map (lookup_tmpl subst) tmpl_vars, leftover_es) }
321 init_menv = ME { me_tmpls = mkVarSet tmpl_vars, me_env = init_rn_env }
322 init_rn_env = mkRnEnv2 (extendInScopeSetList in_scope tmpl_vars)
324 go menv subst [] es = Just (subst, es)
325 go menv subst ts [] = Nothing -- Fail if too few actual args
326 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
327 ; go menv subst1 ts es }
329 lookup_tmpl :: (TvSubstEnv, IdSubstEnv) -> Var -> CoreExpr
330 lookup_tmpl (tv_subst, id_subst) tmpl_var
331 | isTyVar tmpl_var = case lookupVarEnv tv_subst tmpl_var of
333 Nothing -> unbound tmpl_var
334 | otherwise = case lookupVarEnv id_subst tmpl_var of
336 other -> unbound tmpl_var
338 unbound var = pprPanic "Template variable unbound in rewrite rule" (ppr var)
342 ---------------------------------------------
343 The inner workings of matching
344 ---------------------------------------------
347 -- These two definitions are not the same as in Subst,
348 -- but they simple and direct, and purely local to this module
349 -- The third, for TvSubstEnv, is the same as in VarEnv, but repeated here
350 -- for uniformity with IdSubstEnv
351 type SubstEnv = (TvSubstEnv, IdSubstEnv)
352 type IdSubstEnv = IdEnv CoreExpr
353 type TvSubstEnv = TyVarEnv Type
355 emptySubstEnv :: SubstEnv
356 emptySubstEnv = (emptyVarEnv, emptyVarEnv)
359 -- At one stage I tried to match even if there are more
360 -- template args than real args.
362 -- I now think this is probably a bad idea.
363 -- Should the template (map f xs) match (map g)? I think not.
364 -- For a start, in general eta expansion wastes work.
370 -> CoreExpr -- Template
371 -> CoreExpr -- Target
374 -- See the notes with Unify.match, which matches types
375 -- Everything is very similar for terms
377 -- Interesting examples:
379 -- \x->f against \f->f
380 -- When we meet the lambdas we must remember to rename f to f' in the
381 -- second expresion. The RnEnv2 does that.
384 -- forall a. \b->b against \a->3
385 -- We must rename the \a. Otherwise when we meet the lambdas we
386 -- might substitute [a/b] in the template, and then erroneously
387 -- succeed in matching what looks like the template variable 'a' against 3.
389 -- The Var case follows closely what happens in Unify.match
390 match menv subst@(tv_subst, id_subst) (Var v1) e2
391 | v1 `elemVarSet` me_tmpls menv
392 = case lookupVarEnv id_subst v1' of
393 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
394 -> Nothing -- Occurs check failure
395 -- e.g. match forall a. (\x-> a x) against (\y. y y)
398 -> Just (tv_subst, extendVarEnv id_subst v1 e2)
400 Just e2' | tcEqExprX (nukeRnEnvL rn_env) e2' e2
405 | otherwise -- v1 is not a template variable
407 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
411 v1' = rnOccL rn_env v1
413 -- Here is another important rule: if the term being matched is a
414 -- variable, we expand it so long as its unfolding is a WHNF
415 -- (Its occurrence information is not necessarily up to date,
416 -- so we don't use it.)
417 match menv subst e1 (Var v2)
418 | isCheapUnfolding unfolding
419 = match menv subst e1 (unfoldingTemplate unfolding)
421 unfolding = idUnfolding v2
423 match menv subst (Lit lit1) (Lit lit2)
427 match menv subst (App f1 a1) (App f2 a2)
428 = do { subst' <- match menv subst f1 f2
429 ; match menv subst' a1 a2 }
431 match menv subst (Lam x1 e1) (Lam x2 e2)
432 = match menv' subst e1 e2
434 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
436 -- This rule does eta expansion
437 -- (\x.M) ~ N iff M ~ N x
438 match menv subst (Lam x1 e1) e2
439 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
441 (rn_env', new_x) = rnBndrL (me_env menv) x1
442 menv' = menv { me_env = rn_env' }
444 -- Eta expansion the other way
445 -- M ~ (\y.N) iff M y ~ N
446 match menv subst e1 (Lam x2 e2)
447 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
449 (rn_env', new_x) = rnBndrR (me_env menv) x2
450 menv' = menv { me_env = rn_env' }
452 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
453 = do { subst1 <- match_ty menv subst ty1 ty2
454 ; subst2 <- match menv subst1 e1 e2
455 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x2 x2 }
456 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
459 match menv subst (Type ty1) (Type ty2)
460 = match_ty menv subst ty1 ty2
462 match menv subst (Note (Coerce to1 from1) e1) (Note (Coerce to2 from2) e2)
463 = do { subst1 <- match_ty menv subst to1 to2
464 ; subst2 <- match_ty menv subst1 from1 from2
465 ; match menv subst2 e1 e2 }
467 -- This is an interesting rule: we simply ignore lets in the
468 -- term being matched against! The unfolding inside it is (by assumption)
469 -- already inside any occurrences of the bound variables, so we'll expand
470 -- them when we encounter them.
471 match menv subst e1 (Let (NonRec x2 r2) e2)
472 = match menv' subst e1 e2
474 menv' = menv { me_env = fst (rnBndrR (me_env menv) x2) }
475 -- It's important to do this renaming. For example:
477 -- forall f,x,xs. f (x:xs)
479 -- f (let y = e in (y:[]))
480 -- We must not get success with x->y! Instead, we
481 -- need an occurs check.
483 -- Everything else fails
484 match menv subst e1 e2 = Nothing
486 ------------------------------------------
487 match_alts :: MatchEnv
489 -> [CoreAlt] -- Template
490 -> [CoreAlt] -- Target
492 match_alts menv subst [] []
494 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
496 = do { subst1 <- match menv' subst r1 r2
497 ; match_alts menv subst1 alts1 alts2 }
500 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
502 match_alts menv subst alts1 alts2
506 Matching Core types: use the matcher in TcType.
507 Notice that we treat newtypes as opaque. For example, suppose
508 we have a specialised version of a function at a newtype, say
510 We only want to replace (f T) with f', not (f Int).
513 ------------------------------------------
514 match_ty menv (tv_subst, id_subst) ty1 ty2
515 = do { tv_subst' <- Unify.tcMatchTyX menv tv_subst ty1 ty2
516 ; return (tv_subst', id_subst) }
520 %************************************************************************
522 \subsection{Checking a program for failing rule applications}
524 %************************************************************************
526 -----------------------------------------------------
528 -----------------------------------------------------
530 We want to know what sites have rules that could have fired but didn't.
531 This pass runs over the tree (without changing it) and reports such.
533 NB: we assume that this follows a run of the simplifier, so every Id
534 occurrence (including occurrences of imported Ids) is decorated with
535 all its (active) rules. No need to construct a rule base or anything
539 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
540 -- Report partial matches for rules beginning
541 -- with the specified string
542 ruleCheckProgram phase rule_pat binds
544 = text "Rule check results: no rule application sites"
546 = vcat [text "Rule check results:",
548 vcat [ p $$ line | p <- bagToList results ]
551 results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
552 line = text (replicate 20 '-')
554 type RuleCheckEnv = (CompilerPhase, String) -- Phase and Pattern
556 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
557 -- The Bag returned has one SDoc for each call site found
558 ruleCheckBind env (NonRec b r) = ruleCheck env r
559 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
561 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
562 ruleCheck env (Var v) = emptyBag
563 ruleCheck env (Lit l) = emptyBag
564 ruleCheck env (Type ty) = emptyBag
565 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
566 ruleCheck env (Note n e) = ruleCheck env e
567 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
568 ruleCheck env (Lam b e) = ruleCheck env e
569 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
570 unionManyBags [ruleCheck env r | (_,_,r) <- as]
572 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
573 ruleCheckApp env (Var f) as = ruleCheckFun env f as
574 ruleCheckApp env other as = ruleCheck env other
578 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
579 -- Produce a report for all rules matching the predicate
580 -- saying why it doesn't match the specified application
582 ruleCheckFun (phase, pat) fn args
583 | null name_match_rules = emptyBag
584 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
586 name_match_rules = filter match (idCoreRules fn)
587 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
589 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
590 ruleAppCheck_help phase fn args rules
591 = -- The rules match the pattern, so we want to print something
592 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
593 vcat (map check_rule rules)]
596 i_args = args `zip` [1::Int ..]
597 rough_args = map roughTopName args
599 check_rule rule = rule_herald rule <> colon <+> rule_info rule
601 rule_herald (BuiltinRule { ru_name = name })
602 = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
603 rule_herald (Rule { ru_name = name })
604 = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
607 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
608 = text "matches (which is very peculiar!)"
610 rule_info (BuiltinRule {}) = text "does not match"
612 rule_info (Rule { ru_name = name, ru_act = act,
613 ru_bndrs = rule_bndrs, ru_args = rule_args})
614 | not (isActive phase act) = text "active only in later phase"
615 | n_args < n_rule_args = text "too few arguments"
616 | n_mismatches == n_rule_args = text "no arguments match"
617 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
618 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
620 n_rule_args = length rule_args
621 n_mismatches = length mismatches
622 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
623 not (isJust (match_fn rule_arg arg))]
625 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
626 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
628 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
629 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
630 , me_tmpls = mkVarSet rule_bndrs }