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,
16 lookupRule, mkLocalRule, roughTopNames
19 #include "HsVersions.h"
21 import CoreSyn -- All of it
22 import OccurAnal ( occurAnalyseExpr )
23 import CoreFVs ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesRhsFreeVars )
24 import CoreUnfold ( isCheapUnfolding, unfoldingTemplate )
25 import CoreUtils ( tcEqExprX, exprType )
26 import PprCore ( pprRules )
27 import Type ( Type, TvSubstEnv )
28 import Coercion ( coercionKind )
29 import TcType ( tcSplitTyConApp_maybe )
30 import CoreTidy ( tidyRules )
31 import Id ( Id, idUnfolding, isLocalId, isGlobalId, idName, idType,
32 idSpecialisation, idCoreRules, setIdSpecialisation )
33 import IdInfo ( SpecInfo( SpecInfo ) )
37 import Name ( Name, NamedThing(..) )
39 import Unify ( ruleMatchTyX, MatchEnv(..) )
40 import BasicTypes ( Activation, CompilerPhase, isActive )
47 import List hiding( mapAccumL ) -- Also defined in Util
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,
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
119 -- Notice that there is no case
120 -- ruleCantMatch (Just n1 : ts) (Nothing : as) = True
121 -- Reason: a local variable 'v' in the actuals might
122 -- have an unfolding which is a global.
123 -- This quite often happens with case scrutinees.
124 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
125 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
126 ruleCantMatch ts as = False
130 %************************************************************************
132 SpecInfo: the rules in an IdInfo
134 %************************************************************************
137 mkSpecInfo :: [CoreRule] -> SpecInfo
138 mkSpecInfo rules = SpecInfo rules (rulesRhsFreeVars rules)
140 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
141 extendSpecInfo (SpecInfo rs1 fvs1) rs2
142 = SpecInfo (rs2 ++ rs1) (rulesRhsFreeVars rs2 `unionVarSet` fvs1)
144 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
145 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
146 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
148 addIdSpecialisations :: Id -> [CoreRule] -> Id
149 addIdSpecialisations id rules
150 = setIdSpecialisation id $
151 extendSpecInfo (idSpecialisation id) rules
153 rulesOfBinds :: [CoreBind] -> [CoreRule]
154 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
158 %************************************************************************
162 %************************************************************************
165 type RuleBase = NameEnv [CoreRule]
166 -- Maps (the name of) an Id to its rules
167 -- The rules are are unordered;
168 -- we sort out any overlaps on lookup
170 emptyRuleBase = emptyNameEnv
172 mkRuleBase :: [CoreRule] -> RuleBase
173 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
175 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
176 extendRuleBaseList rule_base new_guys
177 = foldl extendRuleBase rule_base new_guys
179 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
180 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
182 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
183 extendRuleBase rule_base rule
184 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
186 pprRuleBase :: RuleBase -> SDoc
187 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
188 | rs <- nameEnvElts rules ]
192 %************************************************************************
194 \subsection{Matching}
196 %************************************************************************
198 Note [Extra args in rule matching]
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
200 If we find a matching rule, we return (Just (rule, rhs)),
201 but the rule firing has only consumed as many of the input args
202 as the ruleArity says. It's up to the caller to keep track
203 of any left-over args. E.g. if you call
204 lookupRule ... f [e1, e2, e3]
205 and it returns Just (r, rhs), where r has ruleArity 2
206 then the real rewrite is
207 f e1 e2 e3 ==> rhs e3
209 You might think it'd be cleaner for lookupRule to deal with the
210 leftover arguments, by applying 'rhs' to them, but the main call
211 in the Simplifier works better as it is. Reason: the 'args' passed
212 to lookupRule are the result of a lazy substitution
215 lookupRule :: (Activation -> Bool) -> InScopeSet
216 -> RuleBase -- Imported rules
217 -> Id -> [CoreExpr] -> Maybe (CoreRule, CoreExpr)
218 -- See Note [Extra argsin rule matching]
219 lookupRule is_active in_scope rule_base fn args
220 = matchRules is_active in_scope fn args rules
222 -- The rules for an Id come from two places:
223 -- (a) the ones it is born with (idCoreRules fn)
224 -- (b) rules added in subsequent modules (extra_rules)
225 -- PrimOps, for example, are born with a bunch of rules under (a)
226 rules = extra_rules ++ idCoreRules fn
227 extra_rules | isLocalId fn = []
228 | otherwise = lookupNameEnv rule_base (idName fn) `orElse` []
230 matchRules :: (Activation -> Bool) -> InScopeSet
232 -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
233 -- See comments on matchRule
234 matchRules is_active in_scope fn args rules
235 = -- pprTrace "matchRules" (ppr fn <+> ppr rules) $
238 (m:ms) -> Just (findBest (fn,args) m ms)
240 rough_args = map roughTopName args
242 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
244 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
245 Just e -> go ((r,e):ms) rs
246 Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$
247 -- ppr [(arg_id, unfoldingTemplate unf) | Var arg_id <- args, let unf = idUnfolding arg_id, isCheapUnfolding unf] )
250 findBest :: (Id, [CoreExpr])
251 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
252 -- All these pairs matched the expression
253 -- Return the pair the the most specific rule
254 -- The (fn,args) is just for overlap reporting
256 findBest target (rule,ans) [] = (rule,ans)
257 findBest target (rule1,ans1) ((rule2,ans2):prs)
258 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
259 | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
261 | otherwise = pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
262 (vcat [ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args),
263 ptext SLIT("Rule 1:") <+> ppr rule1,
264 ptext SLIT("Rule 2:") <+> ppr rule2]) $
265 findBest target (rule1,ans1) prs
267 | otherwise = findBest target (rule1,ans1) prs
272 isMoreSpecific :: CoreRule -> CoreRule -> Bool
273 isMoreSpecific (BuiltinRule {}) r2 = True
274 isMoreSpecific r1 (BuiltinRule {}) = False
275 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
276 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
277 = isJust (matchN in_scope bndrs2 args2 args1)
279 in_scope = mkInScopeSet (mkVarSet bndrs1)
280 -- Actually we should probably include the free vars
281 -- of rule1's args, but I can't be bothered
283 noBlackList :: Activation -> Bool
284 noBlackList act = False -- Nothing is black listed
286 matchRule :: (Activation -> Bool) -> InScopeSet
287 -> [CoreExpr] -> [Maybe Name]
288 -> CoreRule -> Maybe CoreExpr
290 -- If (matchRule rule args) returns Just (name,rhs)
291 -- then (f args) matches the rule, and the corresponding
292 -- rewritten RHS is rhs
294 -- The bndrs and rhs is occurrence-analysed
299 -- forall f g x. map f (map g x) ==> map (f . g) x
301 -- CoreRule "map/map"
302 -- [f,g,x] -- tpl_vars
303 -- [f,map g x] -- tpl_args
304 -- map (f.g) x) -- rhs
306 -- Then the call: matchRule the_rule [e1,map e2 e3]
307 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
309 -- Any 'surplus' arguments in the input are simply put on the end
312 matchRule is_active in_scope args rough_args
313 (BuiltinRule { ru_name = name, ru_try = match_fn })
314 = case match_fn args of
315 Just expr -> Just expr
318 matchRule is_active in_scope args rough_args
319 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
320 ru_bndrs = tpl_vars, ru_args = tpl_args,
322 | not (is_active act) = Nothing
323 | ruleCantMatch tpl_tops rough_args = Nothing
325 = case matchN in_scope tpl_vars tpl_args args of
327 Just (binds, tpl_vals) -> Just (mkLets binds $
328 rule_fn `mkApps` tpl_vals)
330 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
331 -- We could do this when putting things into the rulebase, I guess
336 -> [Var] -- Template tyvars
337 -> [CoreExpr] -- Template
338 -> [CoreExpr] -- Target; can have more elts than template
339 -> Maybe ([CoreBind], -- Bindings to wrap around the entire result
340 [CoreExpr]) -- What is substituted for each template var
342 matchN in_scope tmpl_vars tmpl_es target_es
343 = do { (tv_subst, id_subst, binds)
344 <- go init_menv emptySubstEnv tmpl_es target_es
345 ; return (fromOL binds,
346 map (lookup_tmpl tv_subst id_subst) tmpl_vars') }
348 (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
349 -- See Note [Template binders]
351 init_menv = ME { me_tmpls = mkVarSet tmpl_vars', me_env = init_rn_env }
353 go menv subst [] es = Just subst
354 go menv subst ts [] = Nothing -- Fail if too few actual args
355 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
356 ; go menv subst1 ts es }
358 lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
359 lookup_tmpl tv_subst id_subst tmpl_var'
360 | isTyVar tmpl_var' = case lookupVarEnv tv_subst tmpl_var' of
362 Nothing -> unbound tmpl_var'
363 | otherwise = case lookupVarEnv id_subst tmpl_var' of
365 other -> unbound tmpl_var'
367 unbound var = pprPanic "Template variable unbound in rewrite rule"
368 (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
371 Note [Template binders]
372 ~~~~~~~~~~~~~~~~~~~~~~~
373 Consider the following match:
374 Template: forall x. f x
376 This should succeed, because the template variable 'x' has
377 nothing to do with the 'x' in the target.
379 On reflection, this case probably does just work, but this might not
380 Template: forall x. f (\x.x)
382 Here we want to clone when we find the \x, but to know that x must be in scope
384 To achive this, we use rnBndrL to rename the template variables if
385 necessary; the renamed ones are the tmpl_vars'
388 ---------------------------------------------
389 The inner workings of matching
390 ---------------------------------------------
393 -- These two definitions are not the same as in Subst,
394 -- but they simple and direct, and purely local to this module
396 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
397 -- variables passed into the match.
399 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
400 -- from nested matches; see the Let case of match, below
402 type SubstEnv = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
403 type IdSubstEnv = IdEnv CoreExpr
405 emptySubstEnv :: SubstEnv
406 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
409 -- At one stage I tried to match even if there are more
410 -- template args than real args.
412 -- I now think this is probably a bad idea.
413 -- Should the template (map f xs) match (map g)? I think not.
414 -- For a start, in general eta expansion wastes work.
420 -> CoreExpr -- Template
421 -> CoreExpr -- Target
424 -- See the notes with Unify.match, which matches types
425 -- Everything is very similar for terms
427 -- Interesting examples:
429 -- \x->f against \f->f
430 -- When we meet the lambdas we must remember to rename f to f' in the
431 -- second expresion. The RnEnv2 does that.
434 -- forall a. \b->b against \a->3
435 -- We must rename the \a. Otherwise when we meet the lambdas we
436 -- might substitute [a/b] in the template, and then erroneously
437 -- succeed in matching what looks like the template variable 'a' against 3.
439 -- The Var case follows closely what happens in Unify.match
440 match menv subst (Var v1) e2
441 | Just subst <- match_var menv subst v1 e2
444 match menv subst e1 (Note n e2)
445 = match menv subst e1 e2
446 -- Note [Notes in RULE matching]
447 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
448 -- Look through Notes. In particular, we don't want to
449 -- be confused by InlineMe notes. Maybe we should be more
450 -- careful about profiling notes, but for now I'm just
451 -- riding roughshod over them.
452 --- See Note [Notes in call patterns] in SpecConstr
454 -- Here is another important rule: if the term being matched is a
455 -- variable, we expand it so long as its unfolding is a WHNF
456 -- (Its occurrence information is not necessarily up to date,
457 -- so we don't use it.)
458 match menv subst e1 (Var v2)
459 | isCheapUnfolding unfolding
460 = match menv subst e1 (unfoldingTemplate unfolding)
463 unfolding = idUnfolding (lookupRnInScope rn_env (rnOccR rn_env v2))
464 -- Notice that we look up v2 in the in-scope set
465 -- See Note [Lookup in-scope]
466 -- Remember to apply any renaming first (hence rnOccR)
468 -- Note [Matching lets]
469 -- ~~~~~~~~~~~~~~~~~~~~
470 -- Matching a let-expression. Consider
471 -- RULE forall x. f (g x) = <rhs>
472 -- and target expression
473 -- f (let { w=R } in g E))
474 -- Then we'd like the rule to match, to generate
475 -- let { w=R } in (\x. <rhs>) E
476 -- In effect, we want to float the let-binding outward, to enable
477 -- the match to happen. This is the WHOLE REASON for accumulating
478 -- bindings in the SubstEnv
480 -- We can only do this if
481 -- (a) Widening the scope of w does not capture any variables
482 -- We use a conservative test: w is not already in scope
483 -- If not, we clone the binders, and substitute
484 -- (b) The free variables of R are not bound by the part of the
485 -- target expression outside the let binding; e.g.
486 -- f (\v. let w = v+1 in g E)
487 -- Here we obviously cannot float the let-binding for w.
489 -- You may think rule (a) would never apply, because rule matching is
490 -- mostly invoked from the simplifier, when we have just run substExpr
491 -- over the argument, so there will be no shadowing anyway.
492 -- The fly in the ointment is that the forall'd variables of the
493 -- RULE itself are considered in scope.
495 -- I though of various cheapo ways to solve this tiresome problem,
496 -- but ended up doing the straightforward thing, which is to
497 -- clone the binders if they are in scope. It's tiresome, and
498 -- potentially inefficient, because of the calls to substExpr,
499 -- but I don't think it'll happen much in pracice.
501 {- Cases to think about
502 (let x=y+1 in \x. (x,x))
503 --> let x=y+1 in (\x1. (x1,x1))
504 (\x. let x = y+1 in (x,x))
505 --> let x1 = y+1 in (\x. (x1,x1)
506 (let x=y+1 in (x,x), let x=y-1 in (x,x))
507 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
510 (let x=y+1 in let z=x+1 in (z,z)
511 --> matches (p,p) but watch out that the use of
513 I'm removing the cloning because that makes the above case
514 fail, because the inner let looks as if it has locally-bound vars -}
516 match menv subst@(tv_subst, id_subst, binds) e1 (Let bind e2)
517 | all freshly_bound bndrs,
518 not (any locally_bound bind_fvs)
519 = match (menv { me_env = rn_env' })
520 (tv_subst, id_subst, binds `snocOL` bind')
524 bndrs = bindersOf bind
525 bind_fvs = varSetElems (bindFreeVars bind)
526 locally_bound x = inRnEnvR rn_env x
527 freshly_bound x = not (x `rnInScope` rn_env)
530 rn_env' = extendRnInScopeList rn_env bndrs
532 (rn_env', bndrs') = mapAccumL rnBndrR rn_env bndrs
533 s_prs = [(bndr, Var bndr') | (bndr,bndr') <- zip bndrs bndrs', bndr /= bndr']
534 subst = mkSubst (rnInScopeSet rn_env) emptyVarEnv (mkVarEnv s_prs)
535 (bind', e2') | null s_prs = (bind, e2)
536 | otherwise = (s_bind, substExpr subst e2)
537 s_bind = case bind of
538 NonRec {} -> NonRec (head bndrs') (head rhss)
539 Rec {} -> Rec (bndrs' `zip` map (substExpr subst) rhss)
542 match menv subst (Lit lit1) (Lit lit2)
546 match menv subst (App f1 a1) (App f2 a2)
547 = do { subst' <- match menv subst f1 f2
548 ; match menv subst' a1 a2 }
550 match menv subst (Lam x1 e1) (Lam x2 e2)
551 = match menv' subst e1 e2
553 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
555 -- This rule does eta expansion
556 -- (\x.M) ~ N iff M ~ N x
557 -- It's important that this is *after* the let rule,
558 -- so that (\x.M) ~ (let y = e in \y.N)
559 -- does the let thing, and then gets the lam/lam rule above
560 match menv subst (Lam x1 e1) e2
561 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
563 (rn_env', new_x) = rnBndrL (me_env menv) x1
564 menv' = menv { me_env = rn_env' }
566 -- Eta expansion the other way
567 -- M ~ (\y.N) iff M y ~ N
568 match menv subst e1 (Lam x2 e2)
569 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
571 (rn_env', new_x) = rnBndrR (me_env menv) x2
572 menv' = menv { me_env = rn_env' }
574 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
575 = do { subst1 <- match_ty menv subst ty1 ty2
576 ; subst2 <- match menv subst1 e1 e2
577 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
578 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
581 match menv subst (Type ty1) (Type ty2)
582 = match_ty menv subst ty1 ty2
584 match menv subst (Cast e1 co1) (Cast e2 co2)
585 | (from1, to1) <- coercionKind co1
586 , (from2, to2) <- coercionKind co2
587 = do { subst1 <- match_ty menv subst to1 to2
588 ; subst2 <- match_ty menv subst1 from1 from2
589 ; match menv subst2 e1 e2 }
591 {- REMOVING OLD CODE: I think that the above handling for let is
592 better than the stuff here, which looks
593 pretty suspicious to me. SLPJ Sept 06
594 -- This is an interesting rule: we simply ignore lets in the
595 -- term being matched against! The unfolding inside it is (by assumption)
596 -- already inside any occurrences of the bound variables, so we'll expand
597 -- them when we encounter them. This gives a chance of matching
598 -- forall x,y. f (g (x,y))
600 -- f (let v = (a,b) in g v)
602 match menv subst e1 (Let bind e2)
603 = match (menv { me_env = rn_env' }) subst e1 e2
605 (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
606 -- It's important to do this renaming, so that the bndrs
607 -- are brought into the local scope. For example:
609 -- forall f,x,xs. f (x:xs)
611 -- f (let y = e in (y:[]))
612 -- We must not get success with x->y! So we record that y is
613 -- locally bound (with rnBndrR), and proceed. The Var case
614 -- will fail when trying to bind x->y
617 -- Everything else fails
618 match menv subst e1 e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr e1) $$ (text "e2:" <+> ppr e2)) $
621 ------------------------------------------
622 match_var :: MatchEnv
625 -> CoreExpr -- Target
627 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
628 | v1' `elemVarSet` me_tmpls menv
629 = case lookupVarEnv id_subst v1' of
630 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
631 -> Nothing -- Occurs check failure
632 -- e.g. match forall a. (\x-> a x) against (\y. y y)
634 | otherwise -- No renaming to do on e2, because no free var
635 -- of e2 is in the rnEnvR of the envt
636 -- However, we must match the *types*; e.g.
637 -- forall (c::Char->Int) (x::Char).
638 -- f (c x) = "RULE FIRED"
639 -- We must only match on args that have the right type
640 -- It's actually quite difficult to come up with an example that shows
641 -- you need type matching, esp since matching is left-to-right, so type
642 -- args get matched first. But it's possible (e.g. simplrun008) and
643 -- this is the Right Thing to do
644 -> do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
645 -- c.f. match_ty below
646 ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
648 Just e1' | tcEqExprX (nukeRnEnvL rn_env) e1' e2
654 | otherwise -- v1 is not a template variable; check for an exact match with e2
656 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
661 v1' = rnOccL rn_env v1
662 -- If the template is
663 -- forall x. f x (\x -> x) = ...
664 -- Then the x inside the lambda isn't the
665 -- template x, so we must rename first!
668 ------------------------------------------
669 match_alts :: MatchEnv
671 -> [CoreAlt] -- Template
672 -> [CoreAlt] -- Target
674 match_alts menv subst [] []
676 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
678 = do { subst1 <- match menv' subst r1 r2
679 ; match_alts menv subst1 alts1 alts2 }
682 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
684 match_alts menv subst alts1 alts2
688 Matching Core types: use the matcher in TcType.
689 Notice that we treat newtypes as opaque. For example, suppose
690 we have a specialised version of a function at a newtype, say
692 We only want to replace (f T) with f', not (f Int).
695 ------------------------------------------
701 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
702 = do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
703 ; return (tv_subst', id_subst, binds) }
707 Note [Lookup in-scope]
708 ~~~~~~~~~~~~~~~~~~~~~~
709 Consider this example
710 foo :: Int -> Maybe Int -> Int
712 foo m (Just n) = foo (m-n) (Just n)
714 SpecConstr sees this fragment:
716 case w_smT of wild_Xf [Just A] {
717 Data.Maybe.Nothing -> lvl_smf;
718 Data.Maybe.Just n_acT [Just S(L)] ->
719 case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
720 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
723 and correctly generates the rule
725 RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
726 sc_snn :: GHC.Prim.Int#}
727 $wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
728 = $s$wfoo_sno y_amr sc_snn ;]
730 BUT we must ensure that this rule matches in the original function!
731 Note that the call to $wfoo is
732 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
734 During matching we expand wild_Xf to (Just n_acT). But then we must also
735 expand n_acT to (I# y_amr). And we can only do that if we look up n_acT
736 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
739 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
743 %************************************************************************
745 \subsection{Checking a program for failing rule applications}
747 %************************************************************************
749 -----------------------------------------------------
751 -----------------------------------------------------
753 We want to know what sites have rules that could have fired but didn't.
754 This pass runs over the tree (without changing it) and reports such.
756 NB: we assume that this follows a run of the simplifier, so every Id
757 occurrence (including occurrences of imported Ids) is decorated with
758 all its (active) rules. No need to construct a rule base or anything
762 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
763 -- Report partial matches for rules beginning
764 -- with the specified string
765 ruleCheckProgram phase rule_pat binds
767 = text "Rule check results: no rule application sites"
769 = vcat [text "Rule check results:",
771 vcat [ p $$ line | p <- bagToList results ]
774 results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
775 line = text (replicate 20 '-')
777 type RuleCheckEnv = (CompilerPhase, String) -- Phase and Pattern
779 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
780 -- The Bag returned has one SDoc for each call site found
781 ruleCheckBind env (NonRec b r) = ruleCheck env r
782 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
784 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
785 ruleCheck env (Var v) = emptyBag
786 ruleCheck env (Lit l) = emptyBag
787 ruleCheck env (Type ty) = emptyBag
788 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
789 ruleCheck env (Note n e) = ruleCheck env e
790 ruleCheck env (Cast e co) = ruleCheck env e
791 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
792 ruleCheck env (Lam b e) = ruleCheck env e
793 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
794 unionManyBags [ruleCheck env r | (_,_,r) <- as]
796 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
797 ruleCheckApp env (Var f) as = ruleCheckFun env f as
798 ruleCheckApp env other as = ruleCheck env other
802 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
803 -- Produce a report for all rules matching the predicate
804 -- saying why it doesn't match the specified application
806 ruleCheckFun (phase, pat) fn args
807 | null name_match_rules = emptyBag
808 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
810 name_match_rules = filter match (idCoreRules fn)
811 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
813 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
814 ruleAppCheck_help phase fn args rules
815 = -- The rules match the pattern, so we want to print something
816 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
817 vcat (map check_rule rules)]
820 i_args = args `zip` [1::Int ..]
821 rough_args = map roughTopName args
823 check_rule rule = rule_herald rule <> colon <+> rule_info rule
825 rule_herald (BuiltinRule { ru_name = name })
826 = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
827 rule_herald (Rule { ru_name = name })
828 = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
831 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
832 = text "matches (which is very peculiar!)"
834 rule_info (BuiltinRule {}) = text "does not match"
836 rule_info (Rule { ru_name = name, ru_act = act,
837 ru_bndrs = rule_bndrs, ru_args = rule_args})
838 | not (isActive phase act) = text "active only in later phase"
839 | n_args < n_rule_args = text "too few arguments"
840 | n_mismatches == n_rule_args = text "no arguments match"
841 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
842 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
844 n_rule_args = length rule_args
845 n_mismatches = length mismatches
846 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
847 not (isJust (match_fn rule_arg arg))]
849 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
850 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
852 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
853 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
854 , me_tmpls = mkVarSet rule_bndrs }