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/WorkingConventions#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 )
38 import Id ( Id, idUnfolding, isLocalId, isGlobalId, idName, idType,
39 idSpecialisation, idCoreRules, setIdSpecialisation )
40 import IdInfo ( SpecInfo( SpecInfo ) )
44 import Name ( Name, NamedThing(..) )
46 import Unify ( ruleMatchTyX, MatchEnv(..) )
47 import BasicTypes ( Activation, CompilerPhase, isActive )
48 import StaticFlags ( opt_PprStyle_Debug )
59 %************************************************************************
61 \subsection[specialisation-IdInfo]{Specialisation info about an @Id@}
63 %************************************************************************
65 A @CoreRule@ holds details of one rule for an @Id@, which
66 includes its specialisations.
68 For example, if a rule for @f@ contains the mapping:
70 forall a b d. [Type (List a), Type b, Var d] ===> f' a b
72 then when we find an application of f to matching types, we simply replace
73 it by the matching RHS:
75 f (List Int) Bool dict ===> f' Int Bool
77 All the stuff about how many dictionaries to discard, and what types
78 to apply the specialised function to, are handled by the fact that the
79 Rule contains a template for the result of the specialisation.
81 There is one more exciting case, which is dealt with in exactly the same
82 way. If the specialised value is unboxed then it is lifted at its
83 definition site and unlifted at its uses. For example:
85 pi :: forall a. Num a => a
87 might have a specialisation
89 [Int#] ===> (case pi' of Lift pi# -> pi#)
91 where pi' :: Lift Int# is the specialised version of pi.
94 mkLocalRule :: RuleName -> Activation
95 -> Name -> [CoreBndr] -> [CoreExpr] -> CoreExpr -> CoreRule
96 -- Used to make CoreRule for an Id defined in this module
97 mkLocalRule name act fn bndrs args rhs
98 = Rule { ru_name = name, ru_fn = fn, ru_act = act,
99 ru_bndrs = bndrs, ru_args = args,
100 ru_rhs = rhs, ru_rough = roughTopNames args,
104 roughTopNames :: [CoreExpr] -> [Maybe Name]
105 roughTopNames args = map roughTopName args
107 roughTopName :: CoreExpr -> Maybe Name
108 -- Find the "top" free name of an expression
109 -- a) the function in an App chain (if a GlobalId)
110 -- b) the TyCon in a type
111 -- This is used for the fast-match-check for rules;
112 -- if the top names don't match, the rest can't
113 roughTopName (Type ty) = case tcSplitTyConApp_maybe ty of
114 Just (tc,_) -> Just (getName tc)
116 roughTopName (App f a) = roughTopName f
117 roughTopName (Var f) | isGlobalId f = Just (idName f)
118 | otherwise = Nothing
119 roughTopName other = Nothing
121 ruleCantMatch :: [Maybe Name] -> [Maybe Name] -> Bool
122 -- (ruleCantMatch tpl actual) returns True only if 'actual'
123 -- definitely can't match 'tpl' by instantiating 'tpl'.
124 -- It's only a one-way match; unlike instance matching we
125 -- don't consider unification
127 -- Notice that there is no case
128 -- ruleCantMatch (Just n1 : ts) (Nothing : as) = True
129 -- Reason: a local variable 'v' in the actuals might
130 -- have an unfolding which is a global.
131 -- This quite often happens with case scrutinees.
132 ruleCantMatch (Just n1 : ts) (Just n2 : as) = n1 /= n2 || ruleCantMatch ts as
133 ruleCantMatch (t : ts) (a : as) = ruleCantMatch ts as
134 ruleCantMatch ts as = False
138 %************************************************************************
140 SpecInfo: the rules in an IdInfo
142 %************************************************************************
145 mkSpecInfo :: [CoreRule] -> SpecInfo
146 mkSpecInfo rules = SpecInfo rules (rulesFreeVars rules)
148 extendSpecInfo :: SpecInfo -> [CoreRule] -> SpecInfo
149 extendSpecInfo (SpecInfo rs1 fvs1) rs2
150 = SpecInfo (rs2 ++ rs1) (rulesFreeVars rs2 `unionVarSet` fvs1)
152 addSpecInfo :: SpecInfo -> SpecInfo -> SpecInfo
153 addSpecInfo (SpecInfo rs1 fvs1) (SpecInfo rs2 fvs2)
154 = SpecInfo (rs1 ++ rs2) (fvs1 `unionVarSet` fvs2)
156 addIdSpecialisations :: Id -> [CoreRule] -> Id
157 addIdSpecialisations id rules
158 = setIdSpecialisation id $
159 extendSpecInfo (idSpecialisation id) rules
161 rulesOfBinds :: [CoreBind] -> [CoreRule]
162 rulesOfBinds binds = concatMap (concatMap idCoreRules . bindersOf) binds
166 %************************************************************************
170 %************************************************************************
173 type RuleBase = NameEnv [CoreRule]
174 -- Maps (the name of) an Id to its rules
175 -- The rules are are unordered;
176 -- we sort out any overlaps on lookup
178 emptyRuleBase = emptyNameEnv
180 mkRuleBase :: [CoreRule] -> RuleBase
181 mkRuleBase rules = extendRuleBaseList emptyRuleBase rules
183 extendRuleBaseList :: RuleBase -> [CoreRule] -> RuleBase
184 extendRuleBaseList rule_base new_guys
185 = foldl extendRuleBase rule_base new_guys
187 unionRuleBase :: RuleBase -> RuleBase -> RuleBase
188 unionRuleBase rb1 rb2 = plusNameEnv_C (++) rb1 rb2
190 extendRuleBase :: RuleBase -> CoreRule -> RuleBase
191 extendRuleBase rule_base rule
192 = extendNameEnv_Acc (:) singleton rule_base (ruleIdName rule) rule
194 pprRuleBase :: RuleBase -> SDoc
195 pprRuleBase rules = vcat [ pprRules (tidyRules emptyTidyEnv rs)
196 | rs <- nameEnvElts rules ]
200 %************************************************************************
202 \subsection{Matching}
204 %************************************************************************
206 Note [Extra args in rule matching]
207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
208 If we find a matching rule, we return (Just (rule, rhs)),
209 but the rule firing has only consumed as many of the input args
210 as the ruleArity says. It's up to the caller to keep track
211 of any left-over args. E.g. if you call
212 lookupRule ... f [e1, e2, e3]
213 and it returns Just (r, rhs), where r has ruleArity 2
214 then the real rewrite is
215 f e1 e2 e3 ==> rhs e3
217 You might think it'd be cleaner for lookupRule to deal with the
218 leftover arguments, by applying 'rhs' to them, but the main call
219 in the Simplifier works better as it is. Reason: the 'args' passed
220 to lookupRule are the result of a lazy substitution
223 lookupRule :: (Activation -> Bool) -> InScopeSet
224 -> RuleBase -- Imported rules
225 -> Id -> [CoreExpr] -> Maybe (CoreRule, CoreExpr)
226 -- See Note [Extra argsin rule matching]
227 lookupRule is_active in_scope rule_base fn args
228 = matchRules is_active in_scope fn args rules
230 -- The rules for an Id come from two places:
231 -- (a) the ones it is born with (idCoreRules fn)
232 -- (b) rules added in subsequent modules (extra_rules)
233 -- PrimOps, for example, are born with a bunch of rules under (a)
234 rules = extra_rules ++ idCoreRules fn
235 extra_rules | isLocalId fn = []
236 | otherwise = lookupNameEnv rule_base (idName fn) `orElse` []
238 matchRules :: (Activation -> Bool) -> InScopeSet
240 -> [CoreRule] -> Maybe (CoreRule, CoreExpr)
241 -- See comments on matchRule
242 matchRules is_active in_scope fn args rules
243 = -- pprTrace "matchRules" (ppr fn <+> ppr rules) $
246 (m:ms) -> Just (findBest (fn,args) m ms)
248 rough_args = map roughTopName args
250 go :: [(CoreRule,CoreExpr)] -> [CoreRule] -> [(CoreRule,CoreExpr)]
252 go ms (r:rs) = case (matchRule is_active in_scope args rough_args r) of
253 Just e -> go ((r,e):ms) rs
254 Nothing -> -- pprTrace "match failed" (ppr r $$ ppr args $$
255 -- ppr [(arg_id, unfoldingTemplate unf) | Var arg_id <- args, let unf = idUnfolding arg_id, isCheapUnfolding unf] )
258 findBest :: (Id, [CoreExpr])
259 -> (CoreRule,CoreExpr) -> [(CoreRule,CoreExpr)] -> (CoreRule,CoreExpr)
260 -- All these pairs matched the expression
261 -- Return the pair the the most specific rule
262 -- The (fn,args) is just for overlap reporting
264 findBest target (rule,ans) [] = (rule,ans)
265 findBest target (rule1,ans1) ((rule2,ans2):prs)
266 | rule1 `isMoreSpecific` rule2 = findBest target (rule1,ans1) prs
267 | rule2 `isMoreSpecific` rule1 = findBest target (rule2,ans2) prs
269 | otherwise = let pp_rule rule
270 | opt_PprStyle_Debug = ppr rule
271 | otherwise = doubleQuotes (ftext (ru_name rule))
272 in pprTrace "Rules.findBest: rule overlap (Rule 1 wins)"
273 (vcat [if opt_PprStyle_Debug then
274 ptext SLIT("Expression to match:") <+> ppr fn <+> sep (map ppr args)
276 ptext SLIT("Rule 1:") <+> pp_rule rule1,
277 ptext SLIT("Rule 2:") <+> pp_rule rule2]) $
278 findBest target (rule1,ans1) prs
280 | otherwise = findBest target (rule1,ans1) prs
285 isMoreSpecific :: CoreRule -> CoreRule -> Bool
286 isMoreSpecific (BuiltinRule {}) r2 = True
287 isMoreSpecific r1 (BuiltinRule {}) = False
288 isMoreSpecific (Rule { ru_bndrs = bndrs1, ru_args = args1 })
289 (Rule { ru_bndrs = bndrs2, ru_args = args2 })
290 = isJust (matchN in_scope bndrs2 args2 args1)
292 in_scope = mkInScopeSet (mkVarSet bndrs1)
293 -- Actually we should probably include the free vars
294 -- of rule1's args, but I can't be bothered
296 noBlackList :: Activation -> Bool
297 noBlackList act = False -- Nothing is black listed
299 matchRule :: (Activation -> Bool) -> InScopeSet
300 -> [CoreExpr] -> [Maybe Name]
301 -> CoreRule -> Maybe CoreExpr
303 -- If (matchRule rule args) returns Just (name,rhs)
304 -- then (f args) matches the rule, and the corresponding
305 -- rewritten RHS is rhs
307 -- The bndrs and rhs is occurrence-analysed
312 -- forall f g x. map f (map g x) ==> map (f . g) x
314 -- CoreRule "map/map"
315 -- [f,g,x] -- tpl_vars
316 -- [f,map g x] -- tpl_args
317 -- map (f.g) x) -- rhs
319 -- Then the call: matchRule the_rule [e1,map e2 e3]
320 -- = Just ("map/map", (\f,g,x -> rhs) e1 e2 e3)
322 -- Any 'surplus' arguments in the input are simply put on the end
325 matchRule is_active in_scope args rough_args
326 (BuiltinRule { ru_name = name, ru_try = match_fn })
327 = case match_fn args of
328 Just expr -> Just expr
331 matchRule is_active in_scope args rough_args
332 (Rule { ru_name = rn, ru_act = act, ru_rough = tpl_tops,
333 ru_bndrs = tpl_vars, ru_args = tpl_args,
335 | not (is_active act) = Nothing
336 | ruleCantMatch tpl_tops rough_args = Nothing
338 = case matchN in_scope tpl_vars tpl_args args of
340 Just (binds, tpl_vals) -> Just (mkLets binds $
341 rule_fn `mkApps` tpl_vals)
343 rule_fn = occurAnalyseExpr (mkLams tpl_vars rhs)
344 -- We could do this when putting things into the rulebase, I guess
349 -> [Var] -- Template tyvars
350 -> [CoreExpr] -- Template
351 -> [CoreExpr] -- Target; can have more elts than template
352 -> Maybe ([CoreBind], -- Bindings to wrap around the entire result
353 [CoreExpr]) -- What is substituted for each template var
355 matchN in_scope tmpl_vars tmpl_es target_es
356 = do { (tv_subst, id_subst, binds)
357 <- go init_menv emptySubstEnv tmpl_es target_es
358 ; return (fromOL binds,
359 map (lookup_tmpl tv_subst id_subst) tmpl_vars') }
361 (init_rn_env, tmpl_vars') = mapAccumL rnBndrL (mkRnEnv2 in_scope) tmpl_vars
362 -- See Note [Template binders]
364 init_menv = ME { me_tmpls = mkVarSet tmpl_vars', me_env = init_rn_env }
366 go menv subst [] es = Just subst
367 go menv subst ts [] = Nothing -- Fail if too few actual args
368 go menv subst (t:ts) (e:es) = do { subst1 <- match menv subst t e
369 ; go menv subst1 ts es }
371 lookup_tmpl :: TvSubstEnv -> IdSubstEnv -> Var -> CoreExpr
372 lookup_tmpl tv_subst id_subst tmpl_var'
373 | isTyVar tmpl_var' = case lookupVarEnv tv_subst tmpl_var' of
375 Nothing -> unbound tmpl_var'
376 | otherwise = case lookupVarEnv id_subst tmpl_var' of
378 other -> unbound tmpl_var'
380 unbound var = pprPanic "Template variable unbound in rewrite rule"
381 (ppr var $$ ppr tmpl_vars $$ ppr tmpl_vars' $$ ppr tmpl_es $$ ppr target_es)
384 Note [Template binders]
385 ~~~~~~~~~~~~~~~~~~~~~~~
386 Consider the following match:
387 Template: forall x. f x
389 This should succeed, because the template variable 'x' has
390 nothing to do with the 'x' in the target.
392 On reflection, this case probably does just work, but this might not
393 Template: forall x. f (\x.x)
395 Here we want to clone when we find the \x, but to know that x must be in scope
397 To achive this, we use rnBndrL to rename the template variables if
398 necessary; the renamed ones are the tmpl_vars'
401 ---------------------------------------------
402 The inner workings of matching
403 ---------------------------------------------
406 -- These two definitions are not the same as in Subst,
407 -- but they simple and direct, and purely local to this module
409 -- * The domain of the TvSubstEnv and IdSubstEnv are the template
410 -- variables passed into the match.
412 -- * The (OrdList CoreBind) in a SubstEnv are the bindings floated out
413 -- from nested matches; see the Let case of match, below
415 type SubstEnv = (TvSubstEnv, IdSubstEnv, OrdList CoreBind)
416 type IdSubstEnv = IdEnv CoreExpr
418 emptySubstEnv :: SubstEnv
419 emptySubstEnv = (emptyVarEnv, emptyVarEnv, nilOL)
422 -- At one stage I tried to match even if there are more
423 -- template args than real args.
425 -- I now think this is probably a bad idea.
426 -- Should the template (map f xs) match (map g)? I think not.
427 -- For a start, in general eta expansion wastes work.
433 -> CoreExpr -- Template
434 -> CoreExpr -- Target
437 -- See the notes with Unify.match, which matches types
438 -- Everything is very similar for terms
440 -- Interesting examples:
442 -- \x->f against \f->f
443 -- When we meet the lambdas we must remember to rename f to f' in the
444 -- second expresion. The RnEnv2 does that.
447 -- forall a. \b->b against \a->3
448 -- We must rename the \a. Otherwise when we meet the lambdas we
449 -- might substitute [a/b] in the template, and then erroneously
450 -- succeed in matching what looks like the template variable 'a' against 3.
452 -- The Var case follows closely what happens in Unify.match
453 match menv subst (Var v1) e2
454 | Just subst <- match_var menv subst v1 e2
457 match menv subst e1 (Note n e2)
458 = match menv subst e1 e2
459 -- Note [Notes in RULE matching]
460 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
461 -- Look through Notes. In particular, we don't want to
462 -- be confused by InlineMe notes. Maybe we should be more
463 -- careful about profiling notes, but for now I'm just
464 -- riding roughshod over them.
465 --- See Note [Notes in call patterns] in SpecConstr
467 -- Here is another important rule: if the term being matched is a
468 -- variable, we expand it so long as its unfolding is a WHNF
469 -- (Its occurrence information is not necessarily up to date,
470 -- so we don't use it.)
471 match menv subst e1 (Var v2)
472 | isCheapUnfolding unfolding
473 = match menv subst e1 (unfoldingTemplate unfolding)
476 unfolding = idUnfolding (lookupRnInScope rn_env (rnOccR rn_env v2))
477 -- Notice that we look up v2 in the in-scope set
478 -- See Note [Lookup in-scope]
479 -- Remember to apply any renaming first (hence rnOccR)
481 -- Note [Matching lets]
482 -- ~~~~~~~~~~~~~~~~~~~~
483 -- Matching a let-expression. Consider
484 -- RULE forall x. f (g x) = <rhs>
485 -- and target expression
486 -- f (let { w=R } in g E))
487 -- Then we'd like the rule to match, to generate
488 -- let { w=R } in (\x. <rhs>) E
489 -- In effect, we want to float the let-binding outward, to enable
490 -- the match to happen. This is the WHOLE REASON for accumulating
491 -- bindings in the SubstEnv
493 -- We can only do this if
494 -- (a) Widening the scope of w does not capture any variables
495 -- We use a conservative test: w is not already in scope
496 -- If not, we clone the binders, and substitute
497 -- (b) The free variables of R are not bound by the part of the
498 -- target expression outside the let binding; e.g.
499 -- f (\v. let w = v+1 in g E)
500 -- Here we obviously cannot float the let-binding for w.
502 -- You may think rule (a) would never apply, because rule matching is
503 -- mostly invoked from the simplifier, when we have just run substExpr
504 -- over the argument, so there will be no shadowing anyway.
505 -- The fly in the ointment is that the forall'd variables of the
506 -- RULE itself are considered in scope.
508 -- I though of various cheapo ways to solve this tiresome problem,
509 -- but ended up doing the straightforward thing, which is to
510 -- clone the binders if they are in scope. It's tiresome, and
511 -- potentially inefficient, because of the calls to substExpr,
512 -- but I don't think it'll happen much in pracice.
514 {- Cases to think about
515 (let x=y+1 in \x. (x,x))
516 --> let x=y+1 in (\x1. (x1,x1))
517 (\x. let x = y+1 in (x,x))
518 --> let x1 = y+1 in (\x. (x1,x1)
519 (let x=y+1 in (x,x), let x=y-1 in (x,x))
520 --> let x=y+1 in let x1=y-1 in ((x,x),(x1,x1))
523 (let x=y+1 in let z=x+1 in (z,z)
524 --> matches (p,p) but watch out that the use of
526 I'm removing the cloning because that makes the above case
527 fail, because the inner let looks as if it has locally-bound vars -}
529 match menv subst@(tv_subst, id_subst, binds) e1 (Let bind e2)
530 | all freshly_bound bndrs,
531 not (any locally_bound bind_fvs)
532 = match (menv { me_env = rn_env' })
533 (tv_subst, id_subst, binds `snocOL` bind')
537 bndrs = bindersOf bind
538 bind_fvs = varSetElems (bindFreeVars bind)
539 locally_bound x = inRnEnvR rn_env x
540 freshly_bound x = not (x `rnInScope` rn_env)
543 rn_env' = extendRnInScopeList rn_env bndrs
545 (rn_env', bndrs') = mapAccumL rnBndrR rn_env bndrs
546 s_prs = [(bndr, Var bndr') | (bndr,bndr') <- zip bndrs bndrs', bndr /= bndr']
547 subst = mkSubst (rnInScopeSet rn_env) emptyVarEnv (mkVarEnv s_prs)
548 (bind', e2') | null s_prs = (bind, e2)
549 | otherwise = (s_bind, substExpr subst e2)
550 s_bind = case bind of
551 NonRec {} -> NonRec (head bndrs') (head rhss)
552 Rec {} -> Rec (bndrs' `zip` map (substExpr subst) rhss)
555 match menv subst (Lit lit1) (Lit lit2)
559 match menv subst (App f1 a1) (App f2 a2)
560 = do { subst' <- match menv subst f1 f2
561 ; match menv subst' a1 a2 }
563 match menv subst (Lam x1 e1) (Lam x2 e2)
564 = match menv' subst e1 e2
566 menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
568 -- This rule does eta expansion
569 -- (\x.M) ~ N iff M ~ N x
570 -- It's important that this is *after* the let rule,
571 -- so that (\x.M) ~ (let y = e in \y.N)
572 -- does the let thing, and then gets the lam/lam rule above
573 match menv subst (Lam x1 e1) e2
574 = match menv' subst e1 (App e2 (varToCoreExpr new_x))
576 (rn_env', new_x) = rnBndrL (me_env menv) x1
577 menv' = menv { me_env = rn_env' }
579 -- Eta expansion the other way
580 -- M ~ (\y.N) iff M y ~ N
581 match menv subst e1 (Lam x2 e2)
582 = match menv' subst (App e1 (varToCoreExpr new_x)) e2
584 (rn_env', new_x) = rnBndrR (me_env menv) x2
585 menv' = menv { me_env = rn_env' }
587 match menv subst (Case e1 x1 ty1 alts1) (Case e2 x2 ty2 alts2)
588 = do { subst1 <- match_ty menv subst ty1 ty2
589 ; subst2 <- match menv subst1 e1 e2
590 ; let menv' = menv { me_env = rnBndr2 (me_env menv) x1 x2 }
591 ; match_alts menv' subst2 alts1 alts2 -- Alts are both sorted
594 match menv subst (Type ty1) (Type ty2)
595 = match_ty menv subst ty1 ty2
597 match menv subst (Cast e1 co1) (Cast e2 co2)
598 | (from1, to1) <- coercionKind co1
599 , (from2, to2) <- coercionKind co2
600 = do { subst1 <- match_ty menv subst to1 to2
601 ; subst2 <- match_ty menv subst1 from1 from2
602 ; match menv subst2 e1 e2 }
604 {- REMOVING OLD CODE: I think that the above handling for let is
605 better than the stuff here, which looks
606 pretty suspicious to me. SLPJ Sept 06
607 -- This is an interesting rule: we simply ignore lets in the
608 -- term being matched against! The unfolding inside it is (by assumption)
609 -- already inside any occurrences of the bound variables, so we'll expand
610 -- them when we encounter them. This gives a chance of matching
611 -- forall x,y. f (g (x,y))
613 -- f (let v = (a,b) in g v)
615 match menv subst e1 (Let bind e2)
616 = match (menv { me_env = rn_env' }) subst e1 e2
618 (rn_env', _bndrs') = mapAccumL rnBndrR (me_env menv) (bindersOf bind)
619 -- It's important to do this renaming, so that the bndrs
620 -- are brought into the local scope. For example:
622 -- forall f,x,xs. f (x:xs)
624 -- f (let y = e in (y:[]))
625 -- We must not get success with x->y! So we record that y is
626 -- locally bound (with rnBndrR), and proceed. The Var case
627 -- will fail when trying to bind x->y
630 -- Everything else fails
631 match menv subst e1 e2 = -- pprTrace "Failing at" ((text "e1:" <+> ppr e1) $$ (text "e2:" <+> ppr e2)) $
634 ------------------------------------------
635 match_var :: MatchEnv
638 -> CoreExpr -- Target
640 match_var menv subst@(tv_subst, id_subst, binds) v1 e2
641 | v1' `elemVarSet` me_tmpls menv
642 = case lookupVarEnv id_subst v1' of
643 Nothing | any (inRnEnvR rn_env) (varSetElems (exprFreeVars e2))
644 -> Nothing -- Occurs check failure
645 -- e.g. match forall a. (\x-> a x) against (\y. y y)
647 | otherwise -- No renaming to do on e2, because no free var
648 -- of e2 is in the rnEnvR of the envt
649 -- However, we must match the *types*; e.g.
650 -- forall (c::Char->Int) (x::Char).
651 -- f (c x) = "RULE FIRED"
652 -- We must only match on args that have the right type
653 -- It's actually quite difficult to come up with an example that shows
654 -- you need type matching, esp since matching is left-to-right, so type
655 -- args get matched first. But it's possible (e.g. simplrun008) and
656 -- this is the Right Thing to do
657 -> do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst (idType v1') (exprType e2)
658 -- c.f. match_ty below
659 ; return (tv_subst', extendVarEnv id_subst v1' e2, binds) }
661 Just e1' | tcEqExprX (nukeRnEnvL rn_env) e1' e2
667 | otherwise -- v1 is not a template variable; check for an exact match with e2
669 Var v2 | v1' == rnOccR rn_env v2 -> Just subst
674 v1' = rnOccL rn_env v1
675 -- If the template is
676 -- forall x. f x (\x -> x) = ...
677 -- Then the x inside the lambda isn't the
678 -- template x, so we must rename first!
681 ------------------------------------------
682 match_alts :: MatchEnv
684 -> [CoreAlt] -- Template
685 -> [CoreAlt] -- Target
687 match_alts menv subst [] []
689 match_alts menv subst ((c1,vs1,r1):alts1) ((c2,vs2,r2):alts2)
691 = do { subst1 <- match menv' subst r1 r2
692 ; match_alts menv subst1 alts1 alts2 }
695 menv' = menv { me_env = rnBndrs2 (me_env menv) vs1 vs2 }
697 match_alts menv subst alts1 alts2
701 Matching Core types: use the matcher in TcType.
702 Notice that we treat newtypes as opaque. For example, suppose
703 we have a specialised version of a function at a newtype, say
705 We only want to replace (f T) with f', not (f Int).
708 ------------------------------------------
714 match_ty menv (tv_subst, id_subst, binds) ty1 ty2
715 = do { tv_subst' <- Unify.ruleMatchTyX menv tv_subst ty1 ty2
716 ; return (tv_subst', id_subst, binds) }
720 Note [Lookup in-scope]
721 ~~~~~~~~~~~~~~~~~~~~~~
722 Consider this example
723 foo :: Int -> Maybe Int -> Int
725 foo m (Just n) = foo (m-n) (Just n)
727 SpecConstr sees this fragment:
729 case w_smT of wild_Xf [Just A] {
730 Data.Maybe.Nothing -> lvl_smf;
731 Data.Maybe.Just n_acT [Just S(L)] ->
732 case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] ->
733 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
736 and correctly generates the rule
738 RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int#
739 sc_snn :: GHC.Prim.Int#}
740 $wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr))
741 = $s$wfoo_sno y_amr sc_snn ;]
743 BUT we must ensure that this rule matches in the original function!
744 Note that the call to $wfoo is
745 $wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf
747 During matching we expand wild_Xf to (Just n_acT). But then we must also
748 expand n_acT to (I# y_amr). And we can only do that if we look up n_acT
749 in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding
752 That is why the 'lookupRnInScope' call in the (Var v2) case of 'match'
756 %************************************************************************
758 \subsection{Checking a program for failing rule applications}
760 %************************************************************************
762 -----------------------------------------------------
764 -----------------------------------------------------
766 We want to know what sites have rules that could have fired but didn't.
767 This pass runs over the tree (without changing it) and reports such.
769 NB: we assume that this follows a run of the simplifier, so every Id
770 occurrence (including occurrences of imported Ids) is decorated with
771 all its (active) rules. No need to construct a rule base or anything
775 ruleCheckProgram :: CompilerPhase -> String -> [CoreBind] -> SDoc
776 -- Report partial matches for rules beginning
777 -- with the specified string
778 ruleCheckProgram phase rule_pat binds
780 = text "Rule check results: no rule application sites"
782 = vcat [text "Rule check results:",
784 vcat [ p $$ line | p <- bagToList results ]
787 results = unionManyBags (map (ruleCheckBind (phase, rule_pat)) binds)
788 line = text (replicate 20 '-')
790 type RuleCheckEnv = (CompilerPhase, String) -- Phase and Pattern
792 ruleCheckBind :: RuleCheckEnv -> CoreBind -> Bag SDoc
793 -- The Bag returned has one SDoc for each call site found
794 ruleCheckBind env (NonRec b r) = ruleCheck env r
795 ruleCheckBind env (Rec prs) = unionManyBags [ruleCheck env r | (b,r) <- prs]
797 ruleCheck :: RuleCheckEnv -> CoreExpr -> Bag SDoc
798 ruleCheck env (Var v) = emptyBag
799 ruleCheck env (Lit l) = emptyBag
800 ruleCheck env (Type ty) = emptyBag
801 ruleCheck env (App f a) = ruleCheckApp env (App f a) []
802 ruleCheck env (Note n e) = ruleCheck env e
803 ruleCheck env (Cast e co) = ruleCheck env e
804 ruleCheck env (Let bd e) = ruleCheckBind env bd `unionBags` ruleCheck env e
805 ruleCheck env (Lam b e) = ruleCheck env e
806 ruleCheck env (Case e _ _ as) = ruleCheck env e `unionBags`
807 unionManyBags [ruleCheck env r | (_,_,r) <- as]
809 ruleCheckApp env (App f a) as = ruleCheck env a `unionBags` ruleCheckApp env f (a:as)
810 ruleCheckApp env (Var f) as = ruleCheckFun env f as
811 ruleCheckApp env other as = ruleCheck env other
815 ruleCheckFun :: RuleCheckEnv -> Id -> [CoreExpr] -> Bag SDoc
816 -- Produce a report for all rules matching the predicate
817 -- saying why it doesn't match the specified application
819 ruleCheckFun (phase, pat) fn args
820 | null name_match_rules = emptyBag
821 | otherwise = unitBag (ruleAppCheck_help phase fn args name_match_rules)
823 name_match_rules = filter match (idCoreRules fn)
824 match rule = pat `isPrefixOf` unpackFS (ruleName rule)
826 ruleAppCheck_help :: CompilerPhase -> Id -> [CoreExpr] -> [CoreRule] -> SDoc
827 ruleAppCheck_help phase fn args rules
828 = -- The rules match the pattern, so we want to print something
829 vcat [text "Expression:" <+> ppr (mkApps (Var fn) args),
830 vcat (map check_rule rules)]
833 i_args = args `zip` [1::Int ..]
834 rough_args = map roughTopName args
836 check_rule rule = rule_herald rule <> colon <+> rule_info rule
838 rule_herald (BuiltinRule { ru_name = name })
839 = ptext SLIT("Builtin rule") <+> doubleQuotes (ftext name)
840 rule_herald (Rule { ru_name = name })
841 = ptext SLIT("Rule") <+> doubleQuotes (ftext name)
844 | Just _ <- matchRule noBlackList emptyInScopeSet args rough_args rule
845 = text "matches (which is very peculiar!)"
847 rule_info (BuiltinRule {}) = text "does not match"
849 rule_info (Rule { ru_name = name, ru_act = act,
850 ru_bndrs = rule_bndrs, ru_args = rule_args})
851 | not (isActive phase act) = text "active only in later phase"
852 | n_args < n_rule_args = text "too few arguments"
853 | n_mismatches == n_rule_args = text "no arguments match"
854 | n_mismatches == 0 = text "all arguments match (considered individually), but rule as a whole does not"
855 | otherwise = text "arguments" <+> ppr mismatches <+> text "do not match (1-indexing)"
857 n_rule_args = length rule_args
858 n_mismatches = length mismatches
859 mismatches = [i | (rule_arg, (arg,i)) <- rule_args `zip` i_args,
860 not (isJust (match_fn rule_arg arg))]
862 lhs_fvs = exprsFreeVars rule_args -- Includes template tyvars
863 match_fn rule_arg arg = match menv emptySubstEnv rule_arg arg
865 in_scope = lhs_fvs `unionVarSet` exprFreeVars arg
866 menv = ME { me_env = mkRnEnv2 (mkInScopeSet in_scope)
867 , me_tmpls = mkVarSet rule_bndrs }