2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[CoreRules]{Transformation rules}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 RuleBase, emptyRuleBase, mkRuleBase, extendRuleBaseList,
16 unionRuleBase, pprRuleBase, ruleCheckProgram,
18 mkSpecInfo, extendSpecInfo, addSpecInfo,
19 rulesOfBinds, addIdSpecialisations,
23 lookupRule, mkLocalRule, roughTopNames
26 #include "HsVersions.h"
28 import CoreSyn -- All of it
29 import OccurAnal ( occurAnalyseExpr )
30 import CoreFVs ( exprFreeVars, exprsFreeVars, bindFreeVars, rulesFreeVars )
31 import CoreUnfold ( isCheapUnfolding, unfoldingTemplate )
32 import CoreUtils ( tcEqExprX, exprType )
33 import PprCore ( pprRules )
34 import Type ( Type, TvSubstEnv )
35 import Coercion ( coercionKind )
36 import TcType ( tcSplitTyConApp_maybe )
37 import CoreTidy ( tidyRules )
39 import IdInfo ( SpecInfo( SpecInfo ) )
43 import Name ( Name, NamedThing(..) )
45 import Unify ( ruleMatchTyX, MatchEnv(..) )
46 import BasicTypes ( Activation, CompilerPhase, isActive )
47 import StaticFlags ( opt_PprStyle_Debug )
58 %************************************************************************
60 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
62 %************************************************************************
64 A @CoreRule@ holds details of one rule for an @Id@, which
65 includes its specialisations.
67 For example, if a rule for @f@ contains the mapping:
69 forall a b d. [Type (List a), Type b, Var d] ===> f' a b
71 then when we find an application of f to matching types, we simply replace
72 it by the matching RHS:
74 f (List Int) Bool dict ===> f' Int Bool
76 All the stuff about how many dictionaries to discard, and what types
77 to apply the specialised function to, are handled by the fact that the
78 Rule contains a template for the result of the specialisation.
80 There is one more exciting case, which is dealt with in exactly the same
81 way. If the specialised value is unboxed then it is lifted at its
82 definition site and unlifted at its uses. For example:
84 pi :: forall a. Num a => a
86 might have a specialisation
88 [Int#] ===> (case pi' of Lift pi# -> pi#)
90 where pi' :: Lift Int# is the specialised version of pi.
93 mkLocalRule :: RuleName -> Activation
94 -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
95 -- Used to make CoreRule for an Id defined in this module
96 mkLocalRule name act fn bndrs args rhs
97 = Rule { ru_name = name, ru_fn = fn, ru_act = act,
98 ru_bndrs = bndrs, ru_args = args,
99 ru_rhs = rhs, ru_rough = roughTopNames args,
103 roughTopNames :: [CoreExpr] -> [Maybe Name]
104 roughTopNames args = map roughTopName args
106 roughTopName :: CoreExpr -> Maybe Name
107 -- Find the "top" free name of an expression
108 -- a) the function in an App chain (if a GlobalId)
109 -- b) the TyCon in a type
110 -- This is used for the fast-match-check for rules;
111 -- if the top names don't match, the rest can't
112 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
113 Just (tc,_) -> Just (getName tc)
115 roughTopName (App f a) = roughTopName f
116 roughTopName (Var f) | isGlobalId f = Just (idName f)
117 | otherwise = Nothing
118 roughTopName other = Nothing
120 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
121 -- (ruleCantMatch tpl actual) returns True only if 'actual'
122 -- definitely can't match 'tpl' by instantiating 'tpl'.
123 -- It's only a one-way match; unlike instance matching we
124 -- don't consider unification
127 -- ruleCantMatch [Nothing] [Just n2] = False
128 -- Reason: a template variable can be instantiated by a constant
130 -- ruleCantMatch [Just n1] [Nothing] = False
131 -- Reason: a local variable 'v' in the actuals might [_$_]
133 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
134 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
135 ruleCantMatch ts as = False
139 %************************************************************************
141 SpecInfo: the rules in an IdInfo
143 %************************************************************************
146 mkSpecInfo :: [CoreRule] -> SpecInfo
147 mkSpecInfo rules = SpecInfo rules (rulesFreeVars rules)
149 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
150 extendSpecInfo (SpecInfo rs1 fvs1) rs2
151 = SpecInfo (rs2 ++ rs1) (rulesFreeVars rs2 `unionVarSet` fvs1)
153 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
154 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
155 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
157 addIdSpecialisations :: Id -> [CoreRule] -> Id
158 addIdSpecialisations id rules
159 = setIdSpecialisation id $
160 extendSpecInfo (idSpecialisation id) rules
162 rulesOfBinds :: [CoreBind] -> [CoreRule]
163 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
167 %************************************************************************
171 %************************************************************************
174 type RuleBase = NameEnv [CoreRule]
175 -- Maps (the name of) an Id to its rules
176 -- The rules are are unordered;
177 -- we sort out any overlaps on lookup
179 emptyRuleBase = emptyNameEnv
181 mkRuleBase :: [CoreRule] -> RuleBase
182 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
184 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
185 extendRuleBaseList rule_base new_guys
186 = foldl extendRuleBase rule_base new_guys
188 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
189 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
191 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
192 extendRuleBase rule_base rule
193 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
195 pprRuleBase :: RuleBase -> SDoc
196 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
197 | rs <- nameEnvElts rules ]
201 %************************************************************************
203 \subsection{Matching}
205 %************************************************************************
207 Note [Extra args in rule matching]
208 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
209 If we find a matching rule, we return (Just (rule, rhs)),
210 but the rule firing has only consumed as many of the input args
211 as the ruleArity says. It's up to the caller to keep track
212 of any left-over args. E.g. if you call
213 lookupRule ... f [e1, e2, e3]
214 and it returns Just (r, rhs), where r has ruleArity 2
215 then the real rewrite is
216 f e1 e2 e3 ==> rhs e3
218 You might think it'd be cleaner for lookupRule to deal with the
219 leftover arguments, by applying 'rhs' to them, but the main call
220 in the Simplifier works better as it is. Reason: the 'args' passed
221 to lookupRule are the result of a lazy substitution
224 lookupRule :: (Activation -> Bool) -> InScopeSet
225 -> RuleBase -- Imported rules
226 -> Id -> [CoreExpr] -> Maybe (CoreRule, CoreExpr)
227 -- See Note [Extra argsin rule matching]
228 lookupRule is_active in_scope rule_base fn args
229 = matchRules is_active in_scope fn args (getRules rule_base fn)
231 getRules :: RuleBase -> Id -> [CoreRule]
232 -- The rules for an Id come from two places:
233 -- (a) the ones it is born with (idCoreRules fn)
234 -- (b) rules added in subsequent modules (extra_rules)
235 -- PrimOps, for example, are born with a bunch of rules under (a)
236 getRules rule_base fn
237 | isLocalId fn = idCoreRules fn
238 | otherwise = WARN( not (isPrimOpId fn) && notNull (idCoreRules fn),
239 ppr fn <+> ppr (idCoreRules fn) )
240 idCoreRules fn ++ (lookupNameEnv rule_base (idName fn) `orElse` [])
241 -- Only PrimOpIds have rules inside themselves, and perhaps more besides
243 matchRules :: (Activation -> Bool) -> InScopeSet
245 -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
246 -- See comments on matchRule
247 matchRules is_active in_scope fn args rules
248 = -- pprTrace "matchRules" (ppr fn <+> ppr rules) $
251 (m:ms) -> Just (findBest (fn,args) m ms)
253 rough_args = map roughTopName args
255 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
257 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
258 Just e -> go ((r,e):ms) rs
259 Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$
260 -- ppr [(arg_id, unfoldingTemplate unf) | Var arg_id <- args, let unf = idUnfolding arg_id, isCheapUnfolding unf] )
263 findBest :: (Id, [CoreExpr])
264 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
265 -- All these pairs matched the expression
266 -- Return the pair the the most specific rule
267 -- The (fn,args) is just for overlap reporting
269 findBest target (rule,ans) [] = (rule,ans)
270 findBest target (rule1,ans1) ((rule2,ans2):prs)
271 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
272 | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
273 | debugIsOn = let pp_rule rule
274 | opt_PprStyle_Debug = ppr rule
275 | otherwise = doubleQuotes (ftext (ru_name rule))
276 in pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
277 (vcat [if opt_PprStyle_Debug then
278 ptext (sLit "Expression to match:") <+> ppr fn <+> sep (map ppr args)
280 ptext (sLit "Rule 1:") <+> pp_rule rule1,
281 ptext (sLit "Rule 2:") <+> pp_rule rule2]) $
282 findBest target (rule1,ans1) prs
283 | otherwise = findBest target (rule1,ans1) prs
287 isMoreSpecific :: CoreRule -> CoreRule -> Bool
288 isMoreSpecific (BuiltinRule {}) r2 = True
289 isMoreSpecific r1 (BuiltinRule {}) = False
290 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
291 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
292 = isJust (matchN in_scope bndrs2 args2 args1)
294 in_scope = mkInScopeSet (mkVarSet bndrs1)
295 -- Actually we should probably include the free vars
296 -- of rule1's args, but I can't be bothered
298 noBlackList :: Activation -> Bool
299 noBlackList act = False -- Nothing is black listed
301 matchRule :: (Activation -> Bool) -> InScopeSet
302 -> [CoreExpr] -> [Maybe Name]
303 -> CoreRule -> Maybe CoreExpr
305 -- If (matchRule rule args) returns Just (name,rhs)
306 -- then (f args) matches the rule, and the corresponding
307 -- rewritten RHS is rhs
309 -- The bndrs and rhs is occurrence-analysed
314 -- forall f g x. map f (map g x) ==> map (f . g) x
316 -- CoreRule "map/map"
317 -- [f,g,x] -- tpl_vars
318 -- [f,map g x] -- tpl_args
319 -- map (f.g) x) -- rhs
321 -- Then the call: matchRule the_rule [e1,map e2 e3]
322 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
324 -- Any 'surplus' arguments in the input are simply put on the end
327 matchRule is_active in_scope args rough_args
328 (BuiltinRule { ru_name = name, ru_try = match_fn })
329 = case match_fn args of
330 Just expr -> Just expr
333 matchRule is_active in_scope args rough_args
334 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
335 ru_bndrs = tpl_vars, ru_args = tpl_args,
337 | not (is_active act) = Nothing
338 | ruleCantMatch tpl_tops rough_args = Nothing
340 = case matchN in_scope tpl_vars tpl_args args of
342 Just (binds, tpl_vals) -> Just (mkLets binds $
343 rule_fn `mkApps` tpl_vals)
345 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
346 -- We could do this when putting things into the rulebase, I guess
351 -> [Var] -- Template tyvars
352 -> [CoreExpr] -- Template
353 -> [CoreExpr] -- Target; can have more elts than template
354 -> Maybe ([CoreBind], -- Bindings to wrap around the entire result
355 [CoreExpr]) -- What is substituted for each template var
357 matchN in_scope tmpl_vars tmpl_es target_es
358 = do { (tv_subst, id_subst, binds)
359 <- go init_menv emptySubstEnv tmpl_es target_es
360 ; return (fromOL binds,
361 map (lookup_tmpl tv_subst id_subst) tmpl_vars') }
363 (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
364 -- See Note [Template binders]
366 init_menv = ME { me_tmpls = mkVarSet tmpl_vars', me_env = init_rn_env }
368 go menv subst [] es = Just subst
369 go menv subst ts [] = Nothing -- Fail if too few actual args
370 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
371 ; go menv subst1 ts es }
373 lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
374 lookup_tmpl tv_subst id_subst tmpl_var'
375 | isTyVar tmpl_var' = case lookupVarEnv tv_subst tmpl_var' of
377 Nothing -> unbound tmpl_var'
378 | otherwise = case lookupVarEnv id_subst tmpl_var' of
380 other -> unbound tmpl_var'
382 unbound var = pprPanic "Template variable unbound in rewrite rule"
383 (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
386 Note [Template binders]
387 ~~~~~~~~~~~~~~~~~~~~~~~
388 Consider the following match:
389 Template: forall x. f x
391 This should succeed, because the template variable 'x' has
392 nothing to do with the 'x' in the target.
394 On reflection, this case probably does just work, but this might not
395 Template: forall x. f (\x.x)
397 Here we want to clone when we find the \x, but to know that x must be in scope
399 To achive this, we use rnBndrL to rename the template variables if
400 necessary; the renamed ones are the tmpl_vars'
403 ---------------------------------------------
404 The inner workings of matching
405 ---------------------------------------------
408 -- These two definitions are not the same as in Subst,
409 -- but they simple and direct, and purely local to this module
411 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
412 -- variables passed into the match.
414 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
415 -- from nested matches; see the Let case of match, below
417 type SubstEnv = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
418 type IdSubstEnv = IdEnv CoreExpr
420 emptySubstEnv :: SubstEnv
421 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
424 -- At one stage I tried to match even if there are more
425 -- template args than real args.
427 -- I now think this is probably a bad idea.
428 -- Should the template (map f xs) match (map g)? I think not.
429 -- For a start, in general eta expansion wastes work.
435 -> CoreExpr -- Template
436 -> CoreExpr -- Target
439 -- See the notes with Unify.match, which matches types
440 -- Everything is very similar for terms
442 -- Interesting examples:
444 -- \x->f against \f->f
445 -- When we meet the lambdas we must remember to rename f to f' in the
446 -- second expresion. The RnEnv2 does that.
449 -- forall a. \b->b against \a->3
450 -- We must rename the \a. Otherwise when we meet the lambdas we
451 -- might substitute [a/b] in the template, and then erroneously
452 -- succeed in matching what looks like the template variable 'a' against 3.
454 -- The Var case follows closely what happens in Unify.match
455 match menv subst (Var v1) e2
456 | Just subst <- match_var menv subst v1 e2
459 match menv subst e1 (Note n e2)
460 = match menv subst e1 e2
461 -- Note [Notes in RULE matching]
462 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
463 -- Look through Notes. In particular, we don't want to
464 -- be confused by InlineMe notes. Maybe we should be more
465 -- careful about profiling notes, but for now I'm just
466 -- riding roughshod over them.
467 --- See Note [Notes in call patterns] in SpecConstr
469 -- Here is another important rule: if the term being matched is a
470 -- variable, we expand it so long as its unfolding is a WHNF
471 -- (Its occurrence information is not necessarily up to date,
472 -- so we don't use it.)
473 match menv subst e1 (Var v2)
474 | isCheapUnfolding unfolding
475 = match menv subst e1 (unfoldingTemplate unfolding)
478 unfolding = idUnfolding (lookupRnInScope rn_env (rnOccR rn_env v2))
479 -- Notice that we look up v2 in the in-scope set
480 -- See Note [Lookup in-scope]
481 -- Remember to apply any renaming first (hence rnOccR)
483 -- Note [Matching lets]
484 -- ~~~~~~~~~~~~~~~~~~~~
485 -- Matching a let-expression. Consider
486 -- RULE forall x. f (g x) = <rhs>
487 -- and target expression
488 -- f (let { w=R } in g E))
489 -- Then we'd like the rule to match, to generate
490 -- let { w=R } in (\x. <rhs>) E
491 -- In effect, we want to float the let-binding outward, to enable
492 -- the match to happen. This is the WHOLE REASON for accumulating
493 -- bindings in the SubstEnv
495 -- We can only do this if
496 -- (a) Widening the scope of w does not capture any variables
497 -- We use a conservative test: w is not already in scope
498 -- If not, we clone the binders, and substitute
499 -- (b) The free variables of R are not bound by the part of the
500 -- target expression outside the let binding; e.g.
501 -- f (\v. let w = v+1 in g E)
502 -- Here we obviously cannot float the let-binding for w.
504 -- You may think rule (a) would never apply, because rule matching is
505 -- mostly invoked from the simplifier, when we have just run substExpr
506 -- over the argument, so there will be no shadowing anyway.
507 -- The fly in the ointment is that the forall'd variables of the
508 -- RULE itself are considered in scope.
510 -- I though of various cheapo ways to solve this tiresome problem,
511 -- but ended up doing the straightforward thing, which is to
512 -- clone the binders if they are in scope. It's tiresome, and
513 -- potentially inefficient, because of the calls to substExpr,
514 -- but I don't think it'll happen much in pracice.
516 {- Cases to think about
517 (let x=y+1 in \x. (x,x))
518 --> let x=y+1 in (\x1. (x1,x1))
519 (\x. let x = y+1 in (x,x))
520 --> let x1 = y+1 in (\x. (x1,x1)
521 (let x=y+1 in (x,x), let x=y-1 in (x,x))
522 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
525 (let x=y+1 in let z=x+1 in (z,z)
526 --> matches (p,p) but watch out that the use of
528 I'm removing the cloning because that makes the above case
529 fail, because the inner let looks as if it has locally-bound vars -}
531 match menv subst@(tv_subst, id_subst, binds) e1 (Let bind e2)
532 | all freshly_bound bndrs,
533 not (any locally_bound bind_fvs)
534 = match (menv { me_env = rn_env' })
535 (tv_subst, id_subst, binds `snocOL` bind')
539 bndrs = bindersOf bind
540 bind_fvs = varSetElems (bindFreeVars bind)
541 locally_bound x = inRnEnvR rn_env x
542 freshly_bound x = not (x `rnInScope` rn_env)
545 rn_env' = extendRnInScopeList rn_env bndrs
547 (rn_env', bndrs') = mapAccumL rnBndrR rn_env bndrs
548 s_prs = [(bndr, Var bndr') | (bndr,bndr') <- zip bndrs bndrs', bndr /= bndr']
549 subst = mkSubst (rnInScopeSet rn_env) emptyVarEnv (mkVarEnv s_prs)
550 (bind', e2') | null s_prs = (bind, e2)
551 | otherwise = (s_bind, substExpr subst e2)
552 s_bind = case bind of
553 NonRec {} -> NonRec (head bndrs') (head rhss)
554 Rec {} -> Rec (bndrs' `zip` map (substExpr subst) rhss)
557 match menv subst (Lit lit1) (Lit lit2)
561 match menv subst (App f1 a1) (App f2 a2)
562 = do { subst' <- match menv subst f1 f2
563 ; match menv subst' a1 a2 }
565 match menv subst (Lam x1 e1) (Lam x2 e2)
566 = match menv' subst e1 e2
568 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
570 -- This rule does eta expansion
571 -- (\x.M) ~ N iff M ~ N x
572 -- It's important that this is *after* the let rule,
573 -- so that (\x.M) ~ (let y = e in \y.N)
574 -- does the let thing, and then gets the lam/lam rule above
575 match menv subst (Lam x1 e1) e2
576 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
578 (rn_env', new_x) = rnBndrL (me_env menv) x1
579 menv' = menv { me_env = rn_env' }
581 -- Eta expansion the other way
582 -- M ~ (\y.N) iff M y ~ N
583 match menv subst e1 (Lam x2 e2)
584 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
586 (rn_env', new_x) = rnBndrR (me_env menv) x2
587 menv' = menv { me_env = rn_env' }
589 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
590 = do { subst1 <- match_ty menv subst ty1 ty2
591 ; subst2 <- match menv subst1 e1 e2
592 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
593 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
596 match menv subst (Type ty1) (Type ty2)
597 = match_ty menv subst ty1 ty2
599 match menv subst (Cast e1 co1) (Cast e2 co2)
600 = do { subst1 <- match_ty menv subst co1 co2
601 ; match menv subst1 e1 e2 }
603 {- REMOVING OLD CODE: I think that the above handling for let is
604 better than the stuff here, which looks
605 pretty suspicious to me. SLPJ Sept 06
606 -- This is an interesting rule: we simply ignore lets in the
607 -- term being matched against! The unfolding inside it is (by assumption)
608 -- already inside any occurrences of the bound variables, so we'll expand
609 -- them when we encounter them. This gives a chance of matching
610 -- forall x,y. f (g (x,y))
612 -- f (let v = (a,b) in g v)
614 match menv subst e1 (Let bind e2)
615 = match (menv { me_env = rn_env' }) subst e1 e2
617 (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
618 -- It's important to do this renaming, so that the bndrs
619 -- are brought into the local scope. For example:
621 -- forall f,x,xs. f (x:xs)
623 -- f (let y = e in (y:[]))
624 -- We must not get success with x->y! So we record that y is
625 -- locally bound (with rnBndrR), and proceed. The Var case
626 -- will fail when trying to bind x->y
629 -- Everything else fails
630 match menv subst e1 e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr e1) $$ (text "e2:" <+> ppr e2)) $
633 ------------------------------------------
634 match_var :: MatchEnv
637 -> CoreExpr -- Target
639 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
640 | v1' `elemVarSet` me_tmpls menv
641 = case lookupVarEnv id_subst v1' of
642 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
643 -> Nothing -- Occurs check failure
644 -- e.g. match forall a. (\x-> a x) against (\y. y y)
646 | otherwise -- No renaming to do on e2, because no free var
647 -- of e2 is in the rnEnvR of the envt
648 -- Note [Matching variable types]
649 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
650 -- However, we must match the *types*; e.g.
651 -- forall (c::Char->Int) (x::Char).
652 -- f (c x) = "RULE FIRED"
653 -- We must only match on args that have the right type
654 -- It's actually quite difficult to come up with an example that shows
655 -- you need type matching, esp since matching is left-to-right, so type
656 -- args get matched first. But it's possible (e.g. simplrun008) and
657 -- this is the Right Thing to do
658 -> do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
659 -- c.f. match_ty below
660 ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
662 Just e1' | tcEqExprX (nukeRnEnvL rn_env) e1' e2
668 | otherwise -- v1 is not a template variable; check for an exact match with e2
670 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
675 v1' = rnOccL rn_env v1
676 -- If the template is
677 -- forall x. f x (\x -> x) = ...
678 -- Then the x inside the lambda isn't the
679 -- template x, so we must rename first!
682 ------------------------------------------
683 match_alts :: MatchEnv
685 -> [CoreAlt] -- Template
686 -> [CoreAlt] -- Target
688 match_alts menv subst [] []
690 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
692 = do { subst1 <- match menv' subst r1 r2
693 ; match_alts menv subst1 alts1 alts2 }
696 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
698 match_alts menv subst alts1 alts2
702 Matching Core types: use the matcher in TcType.
703 Notice that we treat newtypes as opaque. For example, suppose
704 we have a specialised version of a function at a newtype, say
706 We only want to replace (f T) with f', not (f Int).
709 ------------------------------------------
715 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
716 = do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
717 ; return (tv_subst', id_subst, binds) }
721 Note [Lookup in-scope]
722 ~~~~~~~~~~~~~~~~~~~~~~
723 Consider this example
724 foo :: Int -> Maybe Int -> Int
726 foo m (Just n) = foo (m-n) (Just n)
728 SpecConstr sees this fragment:
730 case w_smT of wild_Xf [Just A] {
731 Data.Maybe.Nothing -> lvl_smf;
732 Data.Maybe.Just n_acT [Just S(L)] ->
733 case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
734 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
737 and correctly generates the rule
739 RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
740 sc_snn :: GHC.Prim.Int#}
741 $wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
742 = $s$wfoo_sno y_amr sc_snn ;]
744 BUT we must ensure that this rule matches in the original function!
745 Note that the call to $wfoo is
746 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
748 During matching we expand wild_Xf to (Just n_acT). But then we must also
749 expand n_acT to (I# y_amr). And we can only do that if we look up n_acT
750 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
753 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
757 %************************************************************************
759 \subsection{Checking a program for failing rule applications}
761 %************************************************************************
763 -----------------------------------------------------
765 -----------------------------------------------------
767 We want to know what sites have rules that could have fired but didn't.
768 This pass runs over the tree (without changing it) and reports such.
771 ruleCheckProgram :: CompilerPhase -> String -> RuleBase -> [CoreBind] -> SDoc
772 -- Report partial matches for rules beginning
773 -- with the specified string
774 ruleCheckProgram phase rule_pat rule_base binds
776 = text "Rule check results: no rule application sites"
778 = vcat [text "Rule check results:",
780 vcat [ p $$ line | p <- bagToList results ]
783 results = unionManyBags (map (ruleCheckBind (phase, rule_pat, rule_base)) binds)
784 line = text (replicate 20 '-')
786 type RuleCheckEnv = (CompilerPhase, String, RuleBase) -- Phase and Pattern
788 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
789 -- The Bag returned has one SDoc for each call site found
790 ruleCheckBind env (NonRec b r) = ruleCheck env r
791 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
793 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
794 ruleCheck env (Var v) = emptyBag
795 ruleCheck env (Lit l) = emptyBag
796 ruleCheck env (Type ty) = emptyBag
797 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
798 ruleCheck env (Note n e) = ruleCheck env e
799 ruleCheck env (Cast e co) = ruleCheck env e
800 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
801 ruleCheck env (Lam b e) = ruleCheck env e
802 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
803 unionManyBags [ruleCheck env r | (_,_,r) <- as]
805 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
806 ruleCheckApp env (Var f) as = ruleCheckFun env f as
807 ruleCheckApp env other as = ruleCheck env other
811 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
812 -- Produce a report for all rules matching the predicate
813 -- saying why it doesn't match the specified application
815 ruleCheckFun (phase, pat, rule_base) fn args
816 | null name_match_rules = emptyBag
817 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
819 name_match_rules = filter match (getRules rule_base fn)
820 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
822 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
823 ruleAppCheck_help phase fn args rules
824 = -- The rules match the pattern, so we want to print something
825 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
826 vcat (map check_rule rules)]
829 i_args = args `zip` [1::Int ..]
830 rough_args = map roughTopName args
832 check_rule rule = rule_herald rule <> colon <+> rule_info rule
834 rule_herald (BuiltinRule { ru_name = name })
835 = ptext (sLit "Builtin rule") <+> doubleQuotes (ftext name)
836 rule_herald (Rule { ru_name = name })
837 = ptext (sLit "Rule") <+> doubleQuotes (ftext name)
840 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
841 = text "matches (which is very peculiar!)"
843 rule_info (BuiltinRule {}) = text "does not match"
845 rule_info (Rule { ru_name = name, ru_act = act,
846 ru_bndrs = rule_bndrs, ru_args = rule_args})
847 | not (isActive phase act) = text "active only in later phase"
848 | n_args < n_rule_args = text "too few arguments"
849 | n_mismatches == n_rule_args = text "no arguments match"
850 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
851 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
853 n_rule_args = length rule_args
854 n_mismatches = length mismatches
855 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
856 not (isJust (match_fn rule_arg arg))]
858 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
859 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
861 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
862 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
863 , me_tmpls = mkVarSet rule_bndrs }