PageRenderTime 70ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/specialise/SpecConstr.lhs

https://github.com/luite/ghc
Haskell | 1872 lines | 1278 code | 334 blank | 260 comment | 71 complexity | 7806c64adb5e6f9087b3fd713c4eb6c9 MD5 | raw file
  1. ToDo [Nov 2010]
  2. ~~~~~~~~~~~~~~~
  3. 1. Use a library type rather than an annotation for ForceSpecConstr
  4. 2. Nuke NoSpecConstr
  5. %
  6. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  7. %
  8. \section[SpecConstr]{Specialise over constructors}
  9. \begin{code}
  10. module SpecConstr(
  11. specConstrProgram
  12. #ifdef GHCI
  13. , SpecConstrAnnotation(..)
  14. #endif
  15. ) where
  16. #include "HsVersions.h"
  17. import CoreSyn
  18. import CoreSubst
  19. import CoreUtils
  20. import CoreUnfold ( couldBeSmallEnoughToInline )
  21. import CoreFVs ( exprsFreeVars )
  22. import CoreMonad
  23. import Literal ( litIsLifted )
  24. import HscTypes ( ModGuts(..) )
  25. import WwLib ( mkWorkerArgs )
  26. import DataCon
  27. import Coercion hiding( substTy, substCo )
  28. import Rules
  29. import Type hiding ( substTy )
  30. import TyCon ( isRecursiveTyCon )
  31. import Id
  32. import MkCore ( mkImpossibleExpr )
  33. import Var
  34. import VarEnv
  35. import VarSet
  36. import Name
  37. import BasicTypes
  38. import DynFlags ( DynFlags(..) )
  39. import StaticFlags ( opt_PprStyle_Debug )
  40. import Maybes ( orElse, catMaybes, isJust, isNothing )
  41. import Demand
  42. import Serialized ( deserializeWithData )
  43. import Util
  44. import Pair
  45. import UniqSupply
  46. import Outputable
  47. import FastString
  48. import UniqFM
  49. import MonadUtils
  50. import Control.Monad ( zipWithM )
  51. import Data.List
  52. -- See Note [SpecConstrAnnotation]
  53. #ifndef GHCI
  54. type SpecConstrAnnotation = ()
  55. #else
  56. import TyCon ( TyCon )
  57. import GHC.Exts( SpecConstrAnnotation(..) )
  58. #endif
  59. \end{code}
  60. -----------------------------------------------------
  61. Game plan
  62. -----------------------------------------------------
  63. Consider
  64. drop n [] = []
  65. drop 0 xs = []
  66. drop n (x:xs) = drop (n-1) xs
  67. After the first time round, we could pass n unboxed. This happens in
  68. numerical code too. Here's what it looks like in Core:
  69. drop n xs = case xs of
  70. [] -> []
  71. (y:ys) -> case n of
  72. I# n# -> case n# of
  73. 0 -> []
  74. _ -> drop (I# (n# -# 1#)) xs
  75. Notice that the recursive call has an explicit constructor as argument.
  76. Noticing this, we can make a specialised version of drop
  77. RULE: drop (I# n#) xs ==> drop' n# xs
  78. drop' n# xs = let n = I# n# in ...orig RHS...
  79. Now the simplifier will apply the specialisation in the rhs of drop', giving
  80. drop' n# xs = case xs of
  81. [] -> []
  82. (y:ys) -> case n# of
  83. 0 -> []
  84. _ -> drop' (n# -# 1#) xs
  85. Much better!
  86. We'd also like to catch cases where a parameter is carried along unchanged,
  87. but evaluated each time round the loop:
  88. f i n = if i>0 || i>n then i else f (i*2) n
  89. Here f isn't strict in n, but we'd like to avoid evaluating it each iteration.
  90. In Core, by the time we've w/wd (f is strict in i) we get
  91. f i# n = case i# ># 0 of
  92. False -> I# i#
  93. True -> case n of { I# n# ->
  94. case i# ># n# of
  95. False -> I# i#
  96. True -> f (i# *# 2#) n
  97. At the call to f, we see that the argument, n is known to be (I# n#),
  98. and n is evaluated elsewhere in the body of f, so we can play the same
  99. trick as above.
  100. Note [Reboxing]
  101. ~~~~~~~~~~~~~~~
  102. We must be careful not to allocate the same constructor twice. Consider
  103. f p = (...(case p of (a,b) -> e)...p...,
  104. ...let t = (r,s) in ...t...(f t)...)
  105. At the recursive call to f, we can see that t is a pair. But we do NOT want
  106. to make a specialised copy:
  107. f' a b = let p = (a,b) in (..., ...)
  108. because now t is allocated by the caller, then r and s are passed to the
  109. recursive call, which allocates the (r,s) pair again.
  110. This happens if
  111. (a) the argument p is used in other than a case-scrutinsation way.
  112. (b) the argument to the call is not a 'fresh' tuple; you have to
  113. look into its unfolding to see that it's a tuple
  114. Hence the "OR" part of Note [Good arguments] below.
  115. ALTERNATIVE 2: pass both boxed and unboxed versions. This no longer saves
  116. allocation, but does perhaps save evals. In the RULE we'd have
  117. something like
  118. f (I# x#) = f' (I# x#) x#
  119. If at the call site the (I# x) was an unfolding, then we'd have to
  120. rely on CSE to eliminate the duplicate allocation.... This alternative
  121. doesn't look attractive enough to pursue.
  122. ALTERNATIVE 3: ignore the reboxing problem. The trouble is that
  123. the conservative reboxing story prevents many useful functions from being
  124. specialised. Example:
  125. foo :: Maybe Int -> Int -> Int
  126. foo (Just m) 0 = 0
  127. foo x@(Just m) n = foo x (n-m)
  128. Here the use of 'x' will clearly not require boxing in the specialised function.
  129. The strictness analyser has the same problem, in fact. Example:
  130. f p@(a,b) = ...
  131. If we pass just 'a' and 'b' to the worker, it might need to rebox the
  132. pair to create (a,b). A more sophisticated analysis might figure out
  133. precisely the cases in which this could happen, but the strictness
  134. analyser does no such analysis; it just passes 'a' and 'b', and hopes
  135. for the best.
  136. So my current choice is to make SpecConstr similarly aggressive, and
  137. ignore the bad potential of reboxing.
  138. Note [Good arguments]
  139. ~~~~~~~~~~~~~~~~~~~~~
  140. So we look for
  141. * A self-recursive function. Ignore mutual recursion for now,
  142. because it's less common, and the code is simpler for self-recursion.
  143. * EITHER
  144. a) At a recursive call, one or more parameters is an explicit
  145. constructor application
  146. AND
  147. That same parameter is scrutinised by a case somewhere in
  148. the RHS of the function
  149. OR
  150. b) At a recursive call, one or more parameters has an unfolding
  151. that is an explicit constructor application
  152. AND
  153. That same parameter is scrutinised by a case somewhere in
  154. the RHS of the function
  155. AND
  156. Those are the only uses of the parameter (see Note [Reboxing])
  157. What to abstract over
  158. ~~~~~~~~~~~~~~~~~~~~~
  159. There's a bit of a complication with type arguments. If the call
  160. site looks like
  161. f p = ...f ((:) [a] x xs)...
  162. then our specialised function look like
  163. f_spec x xs = let p = (:) [a] x xs in ....as before....
  164. This only makes sense if either
  165. a) the type variable 'a' is in scope at the top of f, or
  166. b) the type variable 'a' is an argument to f (and hence fs)
  167. Actually, (a) may hold for value arguments too, in which case
  168. we may not want to pass them. Supose 'x' is in scope at f's
  169. defn, but xs is not. Then we'd like
  170. f_spec xs = let p = (:) [a] x xs in ....as before....
  171. Similarly (b) may hold too. If x is already an argument at the
  172. call, no need to pass it again.
  173. Finally, if 'a' is not in scope at the call site, we could abstract
  174. it as we do the term variables:
  175. f_spec a x xs = let p = (:) [a] x xs in ...as before...
  176. So the grand plan is:
  177. * abstract the call site to a constructor-only pattern
  178. e.g. C x (D (f p) (g q)) ==> C s1 (D s2 s3)
  179. * Find the free variables of the abstracted pattern
  180. * Pass these variables, less any that are in scope at
  181. the fn defn. But see Note [Shadowing] below.
  182. NOTICE that we only abstract over variables that are not in scope,
  183. so we're in no danger of shadowing variables used in "higher up"
  184. in f_spec's RHS.
  185. Note [Shadowing]
  186. ~~~~~~~~~~~~~~~~
  187. In this pass we gather up usage information that may mention variables
  188. that are bound between the usage site and the definition site; or (more
  189. seriously) may be bound to something different at the definition site.
  190. For example:
  191. f x = letrec g y v = let x = ...
  192. in ...(g (a,b) x)...
  193. Since 'x' is in scope at the call site, we may make a rewrite rule that
  194. looks like
  195. RULE forall a,b. g (a,b) x = ...
  196. But this rule will never match, because it's really a different 'x' at
  197. the call site -- and that difference will be manifest by the time the
  198. simplifier gets to it. [A worry: the simplifier doesn't *guarantee*
  199. no-shadowing, so perhaps it may not be distinct?]
  200. Anyway, the rule isn't actually wrong, it's just not useful. One possibility
  201. is to run deShadowBinds before running SpecConstr, but instead we run the
  202. simplifier. That gives the simplest possible program for SpecConstr to
  203. chew on; and it virtually guarantees no shadowing.
  204. Note [Specialising for constant parameters]
  205. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  206. This one is about specialising on a *constant* (but not necessarily
  207. constructor) argument
  208. foo :: Int -> (Int -> Int) -> Int
  209. foo 0 f = 0
  210. foo m f = foo (f m) (+1)
  211. It produces
  212. lvl_rmV :: GHC.Base.Int -> GHC.Base.Int
  213. lvl_rmV =
  214. \ (ds_dlk :: GHC.Base.Int) ->
  215. case ds_dlk of wild_alH { GHC.Base.I# x_alG ->
  216. GHC.Base.I# (GHC.Prim.+# x_alG 1)
  217. T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
  218. GHC.Prim.Int#
  219. T.$wfoo =
  220. \ (ww_sme :: GHC.Prim.Int#) (w_smg :: GHC.Base.Int -> GHC.Base.Int) ->
  221. case ww_sme of ds_Xlw {
  222. __DEFAULT ->
  223. case w_smg (GHC.Base.I# ds_Xlw) of w1_Xmo { GHC.Base.I# ww1_Xmz ->
  224. T.$wfoo ww1_Xmz lvl_rmV
  225. };
  226. 0 -> 0
  227. }
  228. The recursive call has lvl_rmV as its argument, so we could create a specialised copy
  229. with that argument baked in; that is, not passed at all. Now it can perhaps be inlined.
  230. When is this worth it? Call the constant 'lvl'
  231. - If 'lvl' has an unfolding that is a constructor, see if the corresponding
  232. parameter is scrutinised anywhere in the body.
  233. - If 'lvl' has an unfolding that is a inlinable function, see if the corresponding
  234. parameter is applied (...to enough arguments...?)
  235. Also do this is if the function has RULES?
  236. Also
  237. Note [Specialising for lambda parameters]
  238. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  239. foo :: Int -> (Int -> Int) -> Int
  240. foo 0 f = 0
  241. foo m f = foo (f m) (\n -> n-m)
  242. This is subtly different from the previous one in that we get an
  243. explicit lambda as the argument:
  244. T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
  245. GHC.Prim.Int#
  246. T.$wfoo =
  247. \ (ww_sm8 :: GHC.Prim.Int#) (w_sma :: GHC.Base.Int -> GHC.Base.Int) ->
  248. case ww_sm8 of ds_Xlr {
  249. __DEFAULT ->
  250. case w_sma (GHC.Base.I# ds_Xlr) of w1_Xmf { GHC.Base.I# ww1_Xmq ->
  251. T.$wfoo
  252. ww1_Xmq
  253. (\ (n_ad3 :: GHC.Base.Int) ->
  254. case n_ad3 of wild_alB { GHC.Base.I# x_alA ->
  255. GHC.Base.I# (GHC.Prim.-# x_alA ds_Xlr)
  256. })
  257. };
  258. 0 -> 0
  259. }
  260. I wonder if SpecConstr couldn't be extended to handle this? After all,
  261. lambda is a sort of constructor for functions and perhaps it already
  262. has most of the necessary machinery?
  263. Furthermore, there's an immediate win, because you don't need to allocate the lamda
  264. at the call site; and if perchance it's called in the recursive call, then you
  265. may avoid allocating it altogether. Just like for constructors.
  266. Looks cool, but probably rare...but it might be easy to implement.
  267. Note [SpecConstr for casts]
  268. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  269. Consider
  270. data family T a :: *
  271. data instance T Int = T Int
  272. foo n = ...
  273. where
  274. go (T 0) = 0
  275. go (T n) = go (T (n-1))
  276. The recursive call ends up looking like
  277. go (T (I# ...) `cast` g)
  278. So we want to spot the constructor application inside the cast.
  279. That's why we have the Cast case in argToPat
  280. Note [Local recursive groups]
  281. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  282. For a *local* recursive group, we can see all the calls to the
  283. function, so we seed the specialisation loop from the calls in the
  284. body, not from the calls in the RHS. Consider:
  285. bar m n = foo n (n,n) (n,n) (n,n) (n,n)
  286. where
  287. foo n p q r s
  288. | n == 0 = m
  289. | n > 3000 = case p of { (p1,p2) -> foo (n-1) (p2,p1) q r s }
  290. | n > 2000 = case q of { (q1,q2) -> foo (n-1) p (q2,q1) r s }
  291. | n > 1000 = case r of { (r1,r2) -> foo (n-1) p q (r2,r1) s }
  292. | otherwise = case s of { (s1,s2) -> foo (n-1) p q r (s2,s1) }
  293. If we start with the RHSs of 'foo', we get lots and lots of specialisations,
  294. most of which are not needed. But if we start with the (single) call
  295. in the rhs of 'bar' we get exactly one fully-specialised copy, and all
  296. the recursive calls go to this fully-specialised copy. Indeed, the original
  297. function is later collected as dead code. This is very important in
  298. specialising the loops arising from stream fusion, for example in NDP where
  299. we were getting literally hundreds of (mostly unused) specialisations of
  300. a local function.
  301. In a case like the above we end up never calling the original un-specialised
  302. function. (Although we still leave its code around just in case.)
  303. However, if we find any boring calls in the body, including *unsaturated*
  304. ones, such as
  305. letrec foo x y = ....foo...
  306. in map foo xs
  307. then we will end up calling the un-specialised function, so then we *should*
  308. use the calls in the un-specialised RHS as seeds. We call these
  309. "boring call patterns", and callsToPats reports if it finds any of these.
  310. Note [Do not specialise diverging functions]
  311. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  312. Specialising a function that just diverges is a waste of code.
  313. Furthermore, it broke GHC (simpl014) thus:
  314. {-# STR Sb #-}
  315. f = \x. case x of (a,b) -> f x
  316. If we specialise f we get
  317. f = \x. case x of (a,b) -> fspec a b
  318. But fspec doesn't have decent strictnes info. As it happened,
  319. (f x) :: IO t, so the state hack applied and we eta expanded fspec,
  320. and hence f. But now f's strictness is less than its arity, which
  321. breaks an invariant.
  322. Note [SpecConstrAnnotation]
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. SpecConstrAnnotation is defined in GHC.Exts, and is only guaranteed to
  325. be available in stage 2 (well, until the bootstrap compiler can be
  326. guaranteed to have it)
  327. So we define it to be () in stage1 (ie when GHCI is undefined), and
  328. '#ifdef' out the code that uses it.
  329. See also Note [Forcing specialisation]
  330. Note [Forcing specialisation]
  331. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  332. With stream fusion and in other similar cases, we want to fully specialise
  333. some (but not necessarily all!) loops regardless of their size and the
  334. number of specialisations. We allow a library to specify this by annotating
  335. a type with ForceSpecConstr and then adding a parameter of that type to the
  336. loop. Here is a (simplified) example from the vector library:
  337. data SPEC = SPEC | SPEC2
  338. {-# ANN type SPEC ForceSpecConstr #-}
  339. foldl :: (a -> b -> a) -> a -> Stream b -> a
  340. {-# INLINE foldl #-}
  341. foldl f z (Stream step s _) = foldl_loop SPEC z s
  342. where
  343. foldl_loop !sPEC z s = case step s of
  344. Yield x s' -> foldl_loop sPEC (f z x) s'
  345. Skip -> foldl_loop sPEC z s'
  346. Done -> z
  347. SpecConstr will spot the SPEC parameter and always fully specialise
  348. foldl_loop. Note that
  349. * We have to prevent the SPEC argument from being removed by
  350. w/w which is why (a) SPEC is a sum type, and (b) we have to seq on
  351. the SPEC argument.
  352. * And lastly, the SPEC argument is ultimately eliminated by
  353. SpecConstr itself so there is no runtime overhead.
  354. This is all quite ugly; we ought to come up with a better design.
  355. ForceSpecConstr arguments are spotted in scExpr' and scTopBinds which then set
  356. sc_force to True when calling specLoop. This flag does three things:
  357. * Ignore specConstrThreshold, to specialise functions of arbitrary size
  358. (see scTopBind)
  359. * Ignore specConstrCount, to make arbitrary numbers of specialisations
  360. (see specialise)
  361. * Specialise even for arguments that are not scrutinised in the loop
  362. (see argToPat; Trac #4488)
  363. * Only specialise on recursive types a finite number of times
  364. (see is_too_recursive; Trac #5550)
  365. This flag is inherited for nested non-recursive bindings (which are likely to
  366. be join points and hence should be fully specialised) but reset for nested
  367. recursive bindings.
  368. What alternatives did I consider? Annotating the loop itself doesn't
  369. work because (a) it is local and (b) it will be w/w'ed and having
  370. w/w propagating annotations somehow doesn't seem like a good idea. The
  371. types of the loop arguments really seem to be the most persistent
  372. thing.
  373. Annotating the types that make up the loop state doesn't work,
  374. either, because (a) it would prevent us from using types like Either
  375. or tuples here, (b) we don't want to restrict the set of types that
  376. can be used in Stream states and (c) some types are fixed by the user
  377. (e.g., the accumulator here) but we still want to specialise as much
  378. as possible.
  379. ForceSpecConstr is done by way of an annotation:
  380. data SPEC = SPEC | SPEC2
  381. {-# ANN type SPEC ForceSpecConstr #-}
  382. But SPEC is the *only* type so annotated, so it'd be better to
  383. use a particular library type.
  384. Alternatives to ForceSpecConstr
  385. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  386. Instead of giving the loop an extra argument of type SPEC, we
  387. also considered *wrapping* arguments in SPEC, thus
  388. data SPEC a = SPEC a | SPEC2
  389. loop = \arg -> case arg of
  390. SPEC state ->
  391. case state of (x,y) -> ... loop (SPEC (x',y')) ...
  392. S2 -> error ...
  393. The idea is that a SPEC argument says "specialise this argument
  394. regardless of whether the function case-analyses it". But this
  395. doesn't work well:
  396. * SPEC must still be a sum type, else the strictness analyser
  397. eliminates it
  398. * But that means that 'loop' won't be strict in its real payload
  399. This loss of strictness in turn screws up specialisation, because
  400. we may end up with calls like
  401. loop (SPEC (case z of (p,q) -> (q,p)))
  402. Without the SPEC, if 'loop' were strict, the case would move out
  403. and we'd see loop applied to a pair. But if 'loop' isn't strict
  404. this doesn't look like a specialisable call.
  405. Note [NoSpecConstr]
  406. ~~~~~~~~~~~~~~~~~~~
  407. The ignoreDataCon stuff allows you to say
  408. {-# ANN type T NoSpecConstr #-}
  409. to mean "don't specialise on arguments of this type. It was added
  410. before we had ForceSpecConstr. Lacking ForceSpecConstr we specialised
  411. regardless of size; and then we needed a way to turn that *off*. Now
  412. that we have ForceSpecConstr, this NoSpecConstr is probably redundant.
  413. (Used only for PArray.)
  414. -----------------------------------------------------
  415. Stuff not yet handled
  416. -----------------------------------------------------
  417. Here are notes arising from Roman's work that I don't want to lose.
  418. Example 1
  419. ~~~~~~~~~
  420. data T a = T !a
  421. foo :: Int -> T Int -> Int
  422. foo 0 t = 0
  423. foo x t | even x = case t of { T n -> foo (x-n) t }
  424. | otherwise = foo (x-1) t
  425. SpecConstr does no specialisation, because the second recursive call
  426. looks like a boxed use of the argument. A pity.
  427. $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
  428. $wfoo_sFw =
  429. \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) ->
  430. case ww_sFo of ds_Xw6 [Just L] {
  431. __DEFAULT ->
  432. case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] {
  433. __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq;
  434. 0 ->
  435. case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] ->
  436. case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] ->
  437. $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy
  438. } } };
  439. 0 -> 0
  440. Example 2
  441. ~~~~~~~~~
  442. data a :*: b = !a :*: !b
  443. data T a = T !a
  444. foo :: (Int :*: T Int) -> Int
  445. foo (0 :*: t) = 0
  446. foo (x :*: t) | even x = case t of { T n -> foo ((x-n) :*: t) }
  447. | otherwise = foo ((x-1) :*: t)
  448. Very similar to the previous one, except that the parameters are now in
  449. a strict tuple. Before SpecConstr, we have
  450. $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
  451. $wfoo_sG3 =
  452. \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T
  453. GHC.Base.Int) ->
  454. case ww_sFU of ds_Xws [Just L] {
  455. __DEFAULT ->
  456. case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] {
  457. __DEFAULT ->
  458. case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] ->
  459. $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2 -- $wfoo1
  460. };
  461. 0 ->
  462. case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] ->
  463. case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] ->
  464. $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB -- $wfoo2
  465. } } };
  466. 0 -> 0 }
  467. We get two specialisations:
  468. "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#}
  469. Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB)
  470. = Foo.$s$wfoo1 a_sFB sc_sGC ;
  471. "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#}
  472. Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp))
  473. = Foo.$s$wfoo y_aFp sc_sGC ;
  474. But perhaps the first one isn't good. After all, we know that tpl_B2 is
  475. a T (I# x) really, because T is strict and Int has one constructor. (We can't
  476. unbox the strict fields, because T is polymorphic!)
  477. %************************************************************************
  478. %* *
  479. \subsection{Top level wrapper stuff}
  480. %* *
  481. %************************************************************************
  482. \begin{code}
  483. specConstrProgram :: ModGuts -> CoreM ModGuts
  484. specConstrProgram guts
  485. = do
  486. dflags <- getDynFlags
  487. us <- getUniqueSupplyM
  488. annos <- getFirstAnnotations deserializeWithData guts
  489. let binds' = fst $ initUs us (go (initScEnv dflags annos) (mg_binds guts))
  490. return (guts { mg_binds = binds' })
  491. where
  492. go _ [] = return []
  493. go env (bind:binds) = do (env', bind') <- scTopBind env bind
  494. binds' <- go env' binds
  495. return (bind' : binds')
  496. \end{code}
  497. %************************************************************************
  498. %* *
  499. \subsection{Environment: goes downwards}
  500. %* *
  501. %************************************************************************
  502. Note [Work-free values only in environment]
  503. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  504. The sc_vals field keeps track of in-scope value bindings, so
  505. that if we come across (case x of Just y ->...) we can reduce the
  506. case from knowing that x is bound to a pair.
  507. But only *work-free* values are ok here. For example if the envt had
  508. x -> Just (expensive v)
  509. then we do NOT want to expand to
  510. let y = expensive v in ...
  511. because the x-binding still exists and we've now duplicated (expensive v).
  512. This seldom happens because let-bound constructor applications are
  513. ANF-ised, but it can happen as a result of on-the-fly transformations in
  514. SpecConstr itself. Here is Trac #7865:
  515. let {
  516. a'_shr =
  517. case xs_af8 of _ {
  518. [] -> acc_af6;
  519. : ds_dgt [Dmd=<L,A>] ds_dgu [Dmd=<L,A>] ->
  520. (expensive x_af7, x_af7
  521. } } in
  522. let {
  523. ds_sht =
  524. case a'_shr of _ { (p'_afd, q'_afe) ->
  525. TSpecConstr_DoubleInline.recursive
  526. (GHC.Types.: @ GHC.Types.Int x_af7 wild_X6) (q'_afe, p'_afd)
  527. } } in
  528. When processed knowing that xs_af8 was bound to a cons, we simplify to
  529. a'_shr = (expensive x_af7, x_af7)
  530. and we do NOT want to inline that at the occurrence of a'_shr in ds_sht.
  531. (There are other occurrences of a'_shr.) No no no.
  532. It would be possible to do some on-the-fly ANF-ising, so that a'_shr turned
  533. into a work-free value again, thus
  534. a1 = expensive x_af7
  535. a'_shr = (a1, x_af7)
  536. but that's more work, so until its shown to be important I'm going to
  537. leave it for now.
  538. \begin{code}
  539. data ScEnv = SCE { sc_dflags :: DynFlags,
  540. sc_size :: Maybe Int, -- Size threshold
  541. sc_count :: Maybe Int, -- Max # of specialisations for any one fn
  542. -- See Note [Avoiding exponential blowup]
  543. sc_recursive :: Int, -- Max # of specialisations over recursive type.
  544. -- Stops ForceSpecConstr from diverging.
  545. sc_force :: Bool, -- Force specialisation?
  546. -- See Note [Forcing specialisation]
  547. sc_subst :: Subst, -- Current substitution
  548. -- Maps InIds to OutExprs
  549. sc_how_bound :: HowBoundEnv,
  550. -- Binds interesting non-top-level variables
  551. -- Domain is OutVars (*after* applying the substitution)
  552. sc_vals :: ValueEnv,
  553. -- Domain is OutIds (*after* applying the substitution)
  554. -- Used even for top-level bindings (but not imported ones)
  555. -- The range of the ValueEnv is *work-free* values
  556. -- such as (\x. blah), or (Just v)
  557. -- but NOT (Just (expensive v))
  558. -- See Note [Work-free values only in environment]
  559. sc_annotations :: UniqFM SpecConstrAnnotation
  560. }
  561. ---------------------
  562. -- As we go, we apply a substitution (sc_subst) to the current term
  563. type InExpr = CoreExpr -- _Before_ applying the subst
  564. type InVar = Var
  565. type OutExpr = CoreExpr -- _After_ applying the subst
  566. type OutId = Id
  567. type OutVar = Var
  568. ---------------------
  569. type HowBoundEnv = VarEnv HowBound -- Domain is OutVars
  570. ---------------------
  571. type ValueEnv = IdEnv Value -- Domain is OutIds
  572. data Value = ConVal AltCon [CoreArg] -- _Saturated_ constructors
  573. -- The AltCon is never DEFAULT
  574. | LambdaVal -- Inlinable lambdas or PAPs
  575. instance Outputable Value where
  576. ppr (ConVal con args) = ppr con <+> interpp'SP args
  577. ppr LambdaVal = ptext (sLit "<Lambda>")
  578. ---------------------
  579. initScEnv :: DynFlags -> UniqFM SpecConstrAnnotation -> ScEnv
  580. initScEnv dflags anns
  581. = SCE { sc_dflags = dflags,
  582. sc_size = specConstrThreshold dflags,
  583. sc_count = specConstrCount dflags,
  584. sc_recursive = specConstrRecursive dflags,
  585. sc_force = False,
  586. sc_subst = emptySubst,
  587. sc_how_bound = emptyVarEnv,
  588. sc_vals = emptyVarEnv,
  589. sc_annotations = anns }
  590. data HowBound = RecFun -- These are the recursive functions for which
  591. -- we seek interesting call patterns
  592. | RecArg -- These are those functions' arguments, or their sub-components;
  593. -- we gather occurrence information for these
  594. instance Outputable HowBound where
  595. ppr RecFun = text "RecFun"
  596. ppr RecArg = text "RecArg"
  597. scForce :: ScEnv -> Bool -> ScEnv
  598. scForce env b = env { sc_force = b }
  599. lookupHowBound :: ScEnv -> Id -> Maybe HowBound
  600. lookupHowBound env id = lookupVarEnv (sc_how_bound env) id
  601. scSubstId :: ScEnv -> Id -> CoreExpr
  602. scSubstId env v = lookupIdSubst (text "scSubstId") (sc_subst env) v
  603. scSubstTy :: ScEnv -> Type -> Type
  604. scSubstTy env ty = substTy (sc_subst env) ty
  605. scSubstCo :: ScEnv -> Coercion -> Coercion
  606. scSubstCo env co = substCo (sc_subst env) co
  607. zapScSubst :: ScEnv -> ScEnv
  608. zapScSubst env = env { sc_subst = zapSubstEnv (sc_subst env) }
  609. extendScInScope :: ScEnv -> [Var] -> ScEnv
  610. -- Bring the quantified variables into scope
  611. extendScInScope env qvars = env { sc_subst = extendInScopeList (sc_subst env) qvars }
  612. -- Extend the substitution
  613. extendScSubst :: ScEnv -> Var -> OutExpr -> ScEnv
  614. extendScSubst env var expr = env { sc_subst = extendSubst (sc_subst env) var expr }
  615. extendScSubstList :: ScEnv -> [(Var,OutExpr)] -> ScEnv
  616. extendScSubstList env prs = env { sc_subst = extendSubstList (sc_subst env) prs }
  617. extendHowBound :: ScEnv -> [Var] -> HowBound -> ScEnv
  618. extendHowBound env bndrs how_bound
  619. = env { sc_how_bound = extendVarEnvList (sc_how_bound env)
  620. [(bndr,how_bound) | bndr <- bndrs] }
  621. extendBndrsWith :: HowBound -> ScEnv -> [Var] -> (ScEnv, [Var])
  622. extendBndrsWith how_bound env bndrs
  623. = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndrs')
  624. where
  625. (subst', bndrs') = substBndrs (sc_subst env) bndrs
  626. hb_env' = sc_how_bound env `extendVarEnvList`
  627. [(bndr,how_bound) | bndr <- bndrs']
  628. extendBndrWith :: HowBound -> ScEnv -> Var -> (ScEnv, Var)
  629. extendBndrWith how_bound env bndr
  630. = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndr')
  631. where
  632. (subst', bndr') = substBndr (sc_subst env) bndr
  633. hb_env' = extendVarEnv (sc_how_bound env) bndr' how_bound
  634. extendRecBndrs :: ScEnv -> [Var] -> (ScEnv, [Var])
  635. extendRecBndrs env bndrs = (env { sc_subst = subst' }, bndrs')
  636. where
  637. (subst', bndrs') = substRecBndrs (sc_subst env) bndrs
  638. extendBndr :: ScEnv -> Var -> (ScEnv, Var)
  639. extendBndr env bndr = (env { sc_subst = subst' }, bndr')
  640. where
  641. (subst', bndr') = substBndr (sc_subst env) bndr
  642. extendValEnv :: ScEnv -> Id -> Maybe Value -> ScEnv
  643. extendValEnv env _ Nothing = env
  644. extendValEnv env id (Just cv)
  645. | valueIsWorkFree cv -- Don't duplicate work!! Trac #7865
  646. = env { sc_vals = extendVarEnv (sc_vals env) id cv }
  647. extendValEnv env _ _ = env
  648. extendCaseBndrs :: ScEnv -> OutExpr -> OutId -> AltCon -> [Var] -> (ScEnv, [Var])
  649. -- When we encounter
  650. -- case scrut of b
  651. -- C x y -> ...
  652. -- we want to bind b, to (C x y)
  653. -- NB1: Extends only the sc_vals part of the envt
  654. -- NB2: Kill the dead-ness info on the pattern binders x,y, since
  655. -- they are potentially made alive by the [b -> C x y] binding
  656. extendCaseBndrs env scrut case_bndr con alt_bndrs
  657. = (env2, alt_bndrs')
  658. where
  659. live_case_bndr = not (isDeadBinder case_bndr)
  660. env1 | Var v <- scrut = extendValEnv env v cval
  661. | otherwise = env -- See Note [Add scrutinee to ValueEnv too]
  662. env2 | live_case_bndr = extendValEnv env1 case_bndr cval
  663. | otherwise = env1
  664. alt_bndrs' | case scrut of { Var {} -> True; _ -> live_case_bndr }
  665. = map zap alt_bndrs
  666. | otherwise
  667. = alt_bndrs
  668. cval = case con of
  669. DEFAULT -> Nothing
  670. LitAlt {} -> Just (ConVal con [])
  671. DataAlt {} -> Just (ConVal con vanilla_args)
  672. where
  673. vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++
  674. varsToCoreExprs alt_bndrs
  675. zap v | isTyVar v = v -- See NB2 above
  676. | otherwise = zapIdOccInfo v
  677. decreaseSpecCount :: ScEnv -> Int -> ScEnv
  678. -- See Note [Avoiding exponential blowup]
  679. decreaseSpecCount env n_specs
  680. = env { sc_count = case sc_count env of
  681. Nothing -> Nothing
  682. Just n -> Just (n `div` (n_specs + 1)) }
  683. -- The "+1" takes account of the original function;
  684. -- See Note [Avoiding exponential blowup]
  685. ---------------------------------------------------
  686. -- See Note [SpecConstrAnnotation]
  687. ignoreType :: ScEnv -> Type -> Bool
  688. ignoreDataCon :: ScEnv -> DataCon -> Bool
  689. forceSpecBndr :: ScEnv -> Var -> Bool
  690. #ifndef GHCI
  691. ignoreType _ _ = False
  692. ignoreDataCon _ _ = False
  693. forceSpecBndr _ _ = False
  694. #else /* GHCI */
  695. ignoreDataCon env dc = ignoreTyCon env (dataConTyCon dc)
  696. ignoreType env ty
  697. = case tyConAppTyCon_maybe ty of
  698. Just tycon -> ignoreTyCon env tycon
  699. _ -> False
  700. ignoreTyCon :: ScEnv -> TyCon -> Bool
  701. ignoreTyCon env tycon
  702. = lookupUFM (sc_annotations env) tycon == Just NoSpecConstr
  703. forceSpecBndr env var = forceSpecFunTy env . snd . splitForAllTys . varType $ var
  704. forceSpecFunTy :: ScEnv -> Type -> Bool
  705. forceSpecFunTy env = any (forceSpecArgTy env) . fst . splitFunTys
  706. forceSpecArgTy :: ScEnv -> Type -> Bool
  707. forceSpecArgTy env ty
  708. | Just ty' <- coreView ty = forceSpecArgTy env ty'
  709. forceSpecArgTy env ty
  710. | Just (tycon, tys) <- splitTyConApp_maybe ty
  711. , tycon /= funTyCon
  712. = lookupUFM (sc_annotations env) tycon == Just ForceSpecConstr
  713. || any (forceSpecArgTy env) tys
  714. forceSpecArgTy _ _ = False
  715. #endif /* GHCI */
  716. \end{code}
  717. Note [Add scrutinee to ValueEnv too]
  718. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  719. Consider this:
  720. case x of y
  721. (a,b) -> case b of c
  722. I# v -> ...(f y)...
  723. By the time we get to the call (f y), the ValueEnv
  724. will have a binding for y, and for c
  725. y -> (a,b)
  726. c -> I# v
  727. BUT that's not enough! Looking at the call (f y) we
  728. see that y is pair (a,b), but we also need to know what 'b' is.
  729. So in extendCaseBndrs we must *also* add the binding
  730. b -> I# v
  731. else we lose a useful specialisation for f. This is necessary even
  732. though the simplifier has systematically replaced uses of 'x' with 'y'
  733. and 'b' with 'c' in the code. The use of 'b' in the ValueEnv came
  734. from outside the case. See Trac #4908 for the live example.
  735. Note [Avoiding exponential blowup]
  736. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  737. The sc_count field of the ScEnv says how many times we are prepared to
  738. duplicate a single function. But we must take care with recursive
  739. specialiations. Consider
  740. let $j1 = let $j2 = let $j3 = ...
  741. in
  742. ...$j3...
  743. in
  744. ...$j2...
  745. in
  746. ...$j1...
  747. If we specialise $j1 then in each specialisation (as well as the original)
  748. we can specialise $j2, and similarly $j3. Even if we make just *one*
  749. specialisation of each, because we also have the original we'll get 2^n
  750. copies of $j3, which is not good.
  751. So when recursively specialising we divide the sc_count by the number of
  752. copies we are making at this level, including the original.
  753. %************************************************************************
  754. %* *
  755. \subsection{Usage information: flows upwards}
  756. %* *
  757. %************************************************************************
  758. \begin{code}
  759. data ScUsage
  760. = SCU {
  761. scu_calls :: CallEnv, -- Calls
  762. -- The functions are a subset of the
  763. -- RecFuns in the ScEnv
  764. scu_occs :: !(IdEnv ArgOcc) -- Information on argument occurrences
  765. } -- The domain is OutIds
  766. type CallEnv = IdEnv [Call]
  767. type Call = (ValueEnv, [CoreArg])
  768. -- The arguments of the call, together with the
  769. -- env giving the constructor bindings at the call site
  770. nullUsage :: ScUsage
  771. nullUsage = SCU { scu_calls = emptyVarEnv, scu_occs = emptyVarEnv }
  772. combineCalls :: CallEnv -> CallEnv -> CallEnv
  773. combineCalls = plusVarEnv_C (++)
  774. combineUsage :: ScUsage -> ScUsage -> ScUsage
  775. combineUsage u1 u2 = SCU { scu_calls = combineCalls (scu_calls u1) (scu_calls u2),
  776. scu_occs = plusVarEnv_C combineOcc (scu_occs u1) (scu_occs u2) }
  777. combineUsages :: [ScUsage] -> ScUsage
  778. combineUsages [] = nullUsage
  779. combineUsages us = foldr1 combineUsage us
  780. lookupOccs :: ScUsage -> [OutVar] -> (ScUsage, [ArgOcc])
  781. lookupOccs (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndrs
  782. = (SCU {scu_calls = sc_calls, scu_occs = delVarEnvList sc_occs bndrs},
  783. [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs])
  784. data ArgOcc = NoOcc -- Doesn't occur at all; or a type argument
  785. | UnkOcc -- Used in some unknown way
  786. | ScrutOcc -- See Note [ScrutOcc]
  787. (DataConEnv [ArgOcc]) -- How the sub-components are used
  788. type DataConEnv a = UniqFM a -- Keyed by DataCon
  789. {- Note [ScrutOcc]
  790. ~~~~~~~~~~~~~~~~~~~
  791. An occurrence of ScrutOcc indicates that the thing, or a `cast` version of the thing,
  792. is *only* taken apart or applied.
  793. Functions, literal: ScrutOcc emptyUFM
  794. Data constructors: ScrutOcc subs,
  795. where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components,
  796. The domain of the UniqFM is the Unique of the data constructor
  797. The [ArgOcc] is the occurrences of the *pattern-bound* components
  798. of the data structure. E.g.
  799. data T a = forall b. MkT a b (b->a)
  800. A pattern binds b, x::a, y::b, z::b->a, but not 'a'!
  801. -}
  802. instance Outputable ArgOcc where
  803. ppr (ScrutOcc xs) = ptext (sLit "scrut-occ") <> ppr xs
  804. ppr UnkOcc = ptext (sLit "unk-occ")
  805. ppr NoOcc = ptext (sLit "no-occ")
  806. evalScrutOcc :: ArgOcc
  807. evalScrutOcc = ScrutOcc emptyUFM
  808. -- Experimentally, this vesion of combineOcc makes ScrutOcc "win", so
  809. -- that if the thing is scrutinised anywhere then we get to see that
  810. -- in the overall result, even if it's also used in a boxed way
  811. -- This might be too agressive; see Note [Reboxing] Alternative 3
  812. combineOcc :: ArgOcc -> ArgOcc -> ArgOcc
  813. combineOcc NoOcc occ = occ
  814. combineOcc occ NoOcc = occ
  815. combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys)
  816. combineOcc UnkOcc (ScrutOcc ys) = ScrutOcc ys
  817. combineOcc (ScrutOcc xs) UnkOcc = ScrutOcc xs
  818. combineOcc UnkOcc UnkOcc = UnkOcc
  819. combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc]
  820. combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys
  821. setScrutOcc :: ScEnv -> ScUsage -> OutExpr -> ArgOcc -> ScUsage
  822. -- _Overwrite_ the occurrence info for the scrutinee, if the scrutinee
  823. -- is a variable, and an interesting variable
  824. setScrutOcc env usg (Cast e _) occ = setScrutOcc env usg e occ
  825. setScrutOcc env usg (Tick _ e) occ = setScrutOcc env usg e occ
  826. setScrutOcc env usg (Var v) occ
  827. | Just RecArg <- lookupHowBound env v = usg { scu_occs = extendVarEnv (scu_occs usg) v occ }
  828. | otherwise = usg
  829. setScrutOcc _env usg _other _occ -- Catch-all
  830. = usg
  831. \end{code}
  832. %************************************************************************
  833. %* *
  834. \subsection{The main recursive function}
  835. %* *
  836. %************************************************************************
  837. The main recursive function gathers up usage information, and
  838. creates specialised versions of functions.
  839. \begin{code}
  840. scExpr, scExpr' :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr)
  841. -- The unique supply is needed when we invent
  842. -- a new name for the specialised function and its args
  843. scExpr env e = scExpr' env e
  844. scExpr' env (Var v) = case scSubstId env v of
  845. Var v' -> return (mkVarUsage env v' [], Var v')
  846. e' -> scExpr (zapScSubst env) e'
  847. scExpr' env (Type t) = return (nullUsage, Type (scSubstTy env t))
  848. scExpr' env (Coercion c) = return (nullUsage, Coercion (scSubstCo env c))
  849. scExpr' _ e@(Lit {}) = return (nullUsage, e)
  850. scExpr' env (Tick t e) = do (usg, e') <- scExpr env e
  851. return (usg, Tick t e')
  852. scExpr' env (Cast e co) = do (usg, e') <- scExpr env e
  853. return (usg, Cast e' (scSubstCo env co))
  854. scExpr' env e@(App _ _) = scApp env (collectArgs e)
  855. scExpr' env (Lam b e) = do let (env', b') = extendBndr env b
  856. (usg, e') <- scExpr env' e
  857. return (usg, Lam b' e')
  858. scExpr' env (Case scrut b ty alts)
  859. = do { (scrut_usg, scrut') <- scExpr env scrut
  860. ; case isValue (sc_vals env) scrut' of
  861. Just (ConVal con args) -> sc_con_app con args scrut'
  862. _other -> sc_vanilla scrut_usg scrut'
  863. }
  864. where
  865. sc_con_app con args scrut' -- Known constructor; simplify
  866. = do { let (_, bs, rhs) = findAlt con alts
  867. `orElse` (DEFAULT, [], mkImpossibleExpr ty)
  868. alt_env' = extendScSubstList env ((b,scrut') : bs `zip` trimConArgs con args)
  869. ; scExpr alt_env' rhs }
  870. sc_vanilla scrut_usg scrut' -- Normal case
  871. = do { let (alt_env,b') = extendBndrWith RecArg env b
  872. -- Record RecArg for the components
  873. ; (alt_usgs, alt_occs, alts')
  874. <- mapAndUnzip3M (sc_alt alt_env scrut' b') alts
  875. ; let scrut_occ = foldr combineOcc NoOcc alt_occs
  876. scrut_usg' = setScrutOcc env scrut_usg scrut' scrut_occ
  877. -- The combined usage of the scrutinee is given
  878. -- by scrut_occ, which is passed to scScrut, which
  879. -- in turn treats a bare-variable scrutinee specially
  880. ; return (foldr combineUsage scrut_usg' alt_usgs,
  881. Case scrut' b' (scSubstTy env ty) alts') }
  882. sc_alt env scrut' b' (con,bs,rhs)
  883. = do { let (env1, bs1) = extendBndrsWith RecArg env bs
  884. (env2, bs2) = extendCaseBndrs env1 scrut' b' con bs1
  885. ; (usg, rhs') <- scExpr env2 rhs
  886. ; let (usg', b_occ:arg_occs) = lookupOccs usg (b':bs2)
  887. scrut_occ = case con of
  888. DataAlt dc -> ScrutOcc (unitUFM dc arg_occs)
  889. _ -> ScrutOcc emptyUFM
  890. ; return (usg', b_occ `combineOcc` scrut_occ, (con, bs2, rhs')) }
  891. scExpr' env (Let (NonRec bndr rhs) body)
  892. | isTyVar bndr -- Type-lets may be created by doBeta
  893. = scExpr' (extendScSubst env bndr rhs) body
  894. | otherwise
  895. = do { let (body_env, bndr') = extendBndr env bndr
  896. ; (rhs_usg, rhs_info) <- scRecRhs env (bndr',rhs)
  897. ; let body_env2 = extendHowBound body_env [bndr'] RecFun
  898. -- Note [Local let bindings]
  899. RI _ rhs' _ _ _ = rhs_info
  900. body_env3 = extendValEnv body_env2 bndr' (isValue (sc_vals env) rhs')
  901. ; (body_usg, body') <- scExpr body_env3 body
  902. -- NB: For non-recursive bindings we inherit sc_force flag from
  903. -- the parent function (see Note [Forcing specialisation])
  904. ; (spec_usg, specs) <- specialise env
  905. (scu_calls body_usg)
  906. rhs_info
  907. (SI [] 0 (Just rhs_usg))
  908. ; return (body_usg { scu_calls = scu_calls body_usg `delVarEnv` bndr' }
  909. `combineUsage` rhs_usg `combineUsage` spec_usg,
  910. mkLets [NonRec b r | (b,r) <- specInfoBinds rhs_info specs] body')
  911. }
  912. -- A *local* recursive group: see Note [Local recursive groups]
  913. scExpr' env (Let (Rec prs) body)
  914. = do { let (bndrs,rhss) = unzip prs
  915. (rhs_env1,bndrs') = extendRecBndrs env bndrs
  916. rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
  917. force_spec = any (forceSpecBndr env) bndrs'
  918. -- Note [Forcing specialisation]
  919. ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
  920. ; (body_usg, body') <- scExpr rhs_env2 body
  921. -- NB: start specLoop from body_usg
  922. ; (spec_usg, specs) <- specLoop (scForce rhs_env2 force_spec)
  923. (scu_calls body_usg) rhs_infos nullUsage
  924. [SI [] 0 (Just usg) | usg <- rhs_usgs]
  925. -- Do not unconditionally generate specialisations from rhs_usgs
  926. -- Instead use them only if we find an unspecialised call
  927. -- See Note [Local recursive groups]
  928. ; let rhs_usg = combineUsages rhs_usgs
  929. all_usg = spec_usg `combineUsage` rhs_usg `combineUsage` body_usg
  930. bind' = Rec (concat (zipWith specInfoBinds rhs_infos specs))
  931. ; return (all_usg { scu_calls = scu_calls all_usg `delVarEnvList` bndrs' },
  932. Let bind' body') }
  933. \end{code}
  934. Note [Local let bindings]
  935. ~~~~~~~~~~~~~~~~~~~~~~~~~
  936. It is not uncommon to find this
  937. let $j = \x. <blah> in ...$j True...$j True...
  938. Here $j is an arbitrary let-bound function, but it often comes up for
  939. join points. We might like to specialise $j for its call patterns.
  940. Notice the difference from a letrec, where we look for call patterns
  941. in the *RHS* of the function. Here we look for call patterns in the
  942. *body* of the let.
  943. At one point I predicated this on the RHS mentioning the outer
  944. recursive function, but that's not essential and might even be
  945. harmful. I'm not sure.
  946. \begin{code}
  947. scApp :: ScEnv -> (InExpr, [InExpr]) -> UniqSM (ScUsage, CoreExpr)
  948. scApp env (Var fn, args) -- Function is a variable
  949. = ASSERT( not (null args) )
  950. do { args_w_usgs <- mapM (scExpr env) args
  951. ; let (arg_usgs, args') = unzip args_w_usgs
  952. arg_usg = combineUsages arg_usgs
  953. ; case scSubstId env fn of
  954. fn'@(Lam {}) -> scExpr (zapScSubst env) (doBeta fn' args')
  955. -- Do beta-reduction and try again
  956. Var fn' -> return (arg_usg `combineUsage` mkVarUsage env fn' args',
  957. mkApps (Var fn') args')
  958. other_fn' -> return (arg_usg, mkApps other_fn' args') }
  959. -- NB: doing this ignores any usage info from the substituted
  960. -- function, but I don't think that matters. If it does
  961. -- we can fix it.
  962. where
  963. doBeta :: OutExpr -> [OutExpr] -> OutExpr
  964. -- ToDo: adjust for System IF
  965. doBeta (Lam bndr body) (arg : args) = Let (NonRec bndr arg) (doBeta body args)
  966. doBeta fn args = mkApps fn args
  967. -- The function is almost always a variable, but not always.
  968. -- In particular, if this pass follows float-in,
  969. -- which it may, we can get
  970. -- (let f = ...f... in f) arg1 arg2
  971. scApp env (other_fn, args)
  972. = do { (fn_usg, fn') <- scExpr env other_fn
  973. ; (arg_usgs, args') <- mapAndUnzipM (scExpr env) args
  974. ; return (combineUsages arg_usgs `combineUsage` fn_usg, mkApps fn' args') }
  975. ----------------------
  976. mkVarUsage :: ScEnv -> Id -> [CoreExpr] -> ScUsage
  977. mkVarUsage env fn args
  978. = case lookupHowBound env fn of
  979. Just RecFun -> SCU { scu_calls = unitVarEnv fn [(sc_vals env, args)]
  980. , scu_occs = emptyVarEnv }
  981. Just RecArg -> SCU { scu_calls = emptyVarEnv
  982. , scu_occs = unitVarEnv fn arg_occ }
  983. Nothing -> nullUsage
  984. where
  985. -- I rather think we could use UnkOcc all the time
  986. arg_occ | null args = UnkOcc
  987. | otherwise = evalScrutOcc
  988. ----------------------
  989. scTopBind :: ScEnv -> CoreBind -> UniqSM (ScEnv, CoreBind)
  990. scTopBind env (Rec prs)
  991. | Just threshold <- sc_size env
  992. , not force_spec
  993. , not (all (couldBeSmallEnoughToInline (sc_dflags env) threshold) rhss)
  994. -- No specialisation
  995. = do { let (rhs_env,bndrs') = extendRecBndrs env bndrs
  996. ; (_, rhss') <- mapAndUnzipM (scExpr rhs_env) rhss
  997. ; return (rhs_env, Rec (bndrs' `zip` rhss')) }
  998. | otherwise -- Do specialisation
  999. = do { let (rhs_env1,bndrs') = extendRecBndrs env bndrs
  1000. rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
  1001. ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
  1002. ; let rhs_usg = combineUsages rhs_usgs
  1003. ; (_, specs) <- specLoop (scForce rhs_env2 force_spec)
  1004. (scu_calls rhs_usg) rhs_infos nullUsage
  1005. [SI [] 0 Nothing | _ <- bndrs]
  1006. ; return (rhs_env1, -- For the body of the letrec, delete the RecFun business
  1007. Rec (concat (zipWith specInfoBinds rhs_infos specs))) }
  1008. where
  1009. (bndrs,rhss) = unzip prs
  1010. force_spec = any (forceSpecBndr env) bndrs
  1011. -- Note [Forcing specialisation]
  1012. scTopBind env (NonRec bndr rhs)
  1013. = do { (_, rhs') <- scExpr env rhs
  1014. ; let (env1, bndr') = extendBndr env bndr
  1015. env2 = extendValEnv env1 bndr' (isValue (sc_vals env) rhs')
  1016. ; return (env2, NonRec bndr' rhs') }
  1017. ----------------------
  1018. scRecRhs :: ScEnv -> (OutId, InExpr) -> UniqSM (ScUsage, RhsInfo)
  1019. scRecRhs env (bndr,rhs)
  1020. = do { let (arg_bndrs,body) = collectBinders rhs
  1021. (body_env, arg_bndrs') = extendBndrsWith RecArg env arg_bndrs
  1022. ; (body_usg, body') <- scExpr body_env body
  1023. ; let (rhs_usg, arg_occs) = lookupOccs body_usg arg_bndrs'
  1024. ; return (rhs_usg, RI bndr (mkLams arg_bndrs' body')
  1025. arg_bndrs body arg_occs) }
  1026. -- The arg_occs says how the visible,
  1027. -- lambda-bound binders of the RHS are used
  1028. -- (including the TyVar binders)
  1029. -- Two pats are the same if they match both ways
  1030. ----------------------
  1031. specInfoBinds :: RhsInfo -> SpecInfo -> [(Id,CoreExpr)]
  1032. specInfoBinds (RI fn new_rhs _ _ _) (SI specs _ _)
  1033. = [(id,rhs) | OS _ _ id rhs <- specs] ++
  1034. -- First the specialised bindings
  1035. [(fn `addIdSpecialisations` rules, new_rhs)]
  1036. -- And now the original binding
  1037. where
  1038. rules = [r | OS _ r _ _ <- specs]
  1039. \end{code}
  1040. %************************************************************************
  1041. %* *
  1042. The specialiser itself
  1043. %* *
  1044. %************************************************************************
  1045. \begin{code}
  1046. data RhsInfo = RI OutId -- The binder
  1047. OutExpr -- The new RHS
  1048. [InVar] InExpr -- The *original* RHS (\xs.body)
  1049. -- Note [Specialise original body]
  1050. [ArgOcc] -- Info on how the xs occur in body
  1051. data SpecInfo = SI [OneSpec] -- The specialisations we have generated
  1052. Int -- Length of specs; used for numbering them
  1053. (Maybe ScUsage) -- Just cs => we have not yet used calls in the
  1054. -- from calls in the *original* RHS as
  1055. -- seeds for new specialisations;
  1056. -- if you decide to do so, here is the
  1057. -- RHS usage (which has not yet been
  1058. -- unleashed)
  1059. -- Nothing => we have
  1060. -- See Note [Local recursive groups]
  1061. -- One specialisation: Rule plus definition
  1062. data OneSpec = OS CallPat -- Call pattern that generated this specialisation
  1063. CoreRule -- Rule connecting original id with the specialisation
  1064. OutId OutExpr -- Spec id + its rhs
  1065. specLoop :: ScEnv
  1066. -> CallEnv
  1067. -> [RhsInfo]
  1068. -> ScUsage -> [SpecInfo] -- One per binder; acccumulating parameter
  1069. -> UniqSM (ScUsage, [SpecInfo]) -- ...ditto...
  1070. specLoop env all_calls rhs_infos usg_so_far specs_so_far
  1071. = do { specs_w_usg <- zipWithM (specialise env all_calls) rhs_infos specs_so_far
  1072. ; let (new_usg_s, all_specs) = unzip specs_w_usg
  1073. new_usg = combineUsages new_usg_s
  1074. new_calls = scu_calls new_usg
  1075. all_usg = usg_so_far `combineUsage` new_usg
  1076. ; if isEmptyVarEnv new_calls then
  1077. return (all_usg, all_specs)
  1078. else
  1079. specLoop env new_calls rhs_infos all_usg all_specs }
  1080. specialise
  1081. :: ScEnv
  1082. -> CallEnv -- Info on calls
  1083. -> RhsInfo
  1084. -> SpecInfo -- Original RHS plus patterns dealt with
  1085. -> UniqSM (ScUsage, SpecInfo) -- New specialised versions and their usage
  1086. -- Note: this only generates *specialised* bindings
  1087. -- The original binding is added by specInfoBinds
  1088. --
  1089. -- Note: the rhs here is the optimised version of the original rhs
  1090. -- So when we make a specialised copy of the RHS, we're starting
  1091. -- from an RHS whose nested functions have been optimised already.
  1092. specialise env bind_calls (RI fn _ arg_bndrs body arg_occs)
  1093. spec_info@(SI specs spec_count mb_unspec)
  1094. | not (isBottomingId fn) -- Note [Do not specialise diverging functions]
  1095. , not (isNeverActive (idInlineActivation fn)) -- See Note [Transfer activation]
  1096. , notNull arg_bndrs -- Only specialise functions
  1097. , Just all_calls <- lookupVarEnv bind_calls fn
  1098. = do { (boring_call, pats) <- callsToPats env specs arg_occs all_calls
  1099. -- ; pprTrace "specialise" (vcat [ ppr fn <+> text "with" <+> int (length pats) <+> text "good patterns"
  1100. -- , text "arg_occs" <+> ppr arg_occs
  1101. -- , text "calls" <+> ppr all_calls
  1102. -- , text "good pats" <+> ppr pats]) $
  1103. -- return ()
  1104. -- Bale out if too many specialisations
  1105. ; let n_pats = length pats
  1106. spec_count' = n_pats + spec_count
  1107. ; case sc_count env of
  1108. Just max | not (sc_force env) && spec_count' > max
  1109. -> if (debugIsOn || opt_PprStyle_Debug) -- Suppress this scary message for
  1110. then pprTrace "SpecConstr" msg $ -- ordinary users! Trac #5125
  1111. return (nullUsage, spec_info)
  1112. else return (nullUsage, spec_info)
  1113. where
  1114. msg = vcat [ sep [ ptext (sLit "Function") <+> quotes (ppr fn)
  1115. , nest 2 (ptext (sLit "has") <+>
  1116. speakNOf spec_count' (ptext (sLit "call pattern")) <> comma <+>
  1117. ptext (sLit "but the limit is") <+> int max) ]
  1118. , ptext (sLit "Use -fspec-constr-count=n to set the bound")
  1119. , extra ]
  1120. extra | not opt_PprStyle_Debug = ptext (sLit "Use -dppr-debug to see specialisations")
  1121. | otherwise = ptext (sLit "Specialisations:") <+> ppr (pats ++ [p | OS p _ _ _ <- specs])
  1122. _normal_case -> do {
  1123. let spec_env = decreaseSpecCount env n_pats
  1124. ; (spec_usgs, new_specs) <- mapAndUnzipM (spec_one spec_env fn arg_bndrs body)
  1125. (pats `zip` [spec_count..])
  1126. -- See Note [Specialise original body]
  1127. ; let spec_usg = combineUsages spec_usgs
  1128. (new_usg, mb_unspec')
  1129. = case mb_unspec of
  1130. Just rhs_usg | boring_call -> (spec_usg `combineUsage` rhs_usg, Nothing)
  1131. _ -> (spec_usg, mb_unspec)
  1132. ; return (new_usg, SI (new_specs ++ specs) spec_count' mb_unspec') } }
  1133. | otherwise
  1134. = return (nullUsage, spec_info) -- The boring case
  1135. ---------------------
  1136. spec_one :: ScEnv
  1137. -> OutId -- Function
  1138. -> [InVar] -- Lambda-binders of RHS; should match patterns
  1139. -> InExpr -- Body of the original function
  1140. -> (CallPat, Int)
  1141. -> UniqSM (ScUsage, OneSpec) -- Rule and binding
  1142. -- spec_one creates a specialised copy of the function, together
  1143. -- with a rule for using it. I'm very proud of how short this
  1144. -- function is, considering what it does :-).
  1145. {-
  1146. Example
  1147. In-scope: a, x::a
  1148. f = /\b \y::[(a,b)] -> ....f (b,c) ((:) (a,(b,c)) (x,v) (h w))...
  1149. [c::*, v::(b,c) are presumably bound by the (...) part]
  1150. ==>
  1151. f_spec = /\ b c \ v::(b,c) hw::[(a,(b,c))] ->
  1152. (...entire body of f...) [b -> (b,c),
  1153. y -> ((:) (a,(b,c)) (x,v) hw)]
  1154. RULE: forall b::* c::*, -- Note, *not* forall a, x
  1155. v::(b,c),
  1156. hw::[(a,(b,c))] .
  1157. f (b,c) ((:) (a,(b,c)) (x,v) hw) = f_spec b c v hw
  1158. -}
  1159. spec_one env fn arg_bndrs body (call_pat@(qvars, pats), rule_number)
  1160. = do { spec_uniq <- getUniqueUs
  1161. ; let spec_env = extendScSubstList (extendScInScope env qvars)
  1162. (arg_bndrs `zip` pats)
  1163. fn_name = idName fn
  1164. fn_loc = nameSrcSpan fn_name
  1165. fn_occ = nameOccName fn_name
  1166. spec_occ = mkSpecOcc fn_occ
  1167. -- We use fn_occ rather than fn in the rule_name string
  1168. -- as we don't want the uniq to end up in the rule, and
  1169. -- hence in the ABI, as that can cause spurious ABI
  1170. -- changes (#4012).
  1171. rule_name = mkFastString ("SC:" ++ occNameString fn_occ ++ show rule_number)
  1172. spec_name = mkInternalName spec_uniq spec_occ fn_loc
  1173. -- ; pprTrace "{spec_one" (ppr (sc_count env) <+> ppr fn <+> ppr pats <+> text "-->" <+> ppr spec_name) $
  1174. -- return ()
  1175. -- Specialise the body
  1176. ; (spec_usg, spec_body) <- scExpr spec_env body
  1177. -- ; pprTrace "done spec_one}" (ppr fn) $
  1178. -- return ()
  1179. -- And build the results
  1180. ; let spec_id = mkLocalId spec_name (mkPiTypes spec_lam_args body_ty)
  1181. -- See Note [Transfer strictness]
  1182. `setIdStrictness` spec_str
  1183. `setIdArity` count isId spec_lam_args
  1184. spec_str = calcSpecStrictness fn spec_lam_args pats
  1185. -- Conditionally use result of new worker-wrapper transform
  1186. (spec_lam_args, spec_call_args) = mkWorkerArgs (sc_dflags env) qvars False body_ty
  1187. -- Usual w/w hack to avoid generating
  1188. -- a spec_rhs of unlifted type and no args
  1189. spec_rhs = mkLams spec_lam_args spec_body
  1190. body_ty = exprType spec_body
  1191. rule_rhs = mkVarApps (Var spec_id) spec_call_args
  1192. inline_act = idInlineActivation fn
  1193. rule = mkRule True {- Auto -} True {- Local -}
  1194. rule_name inline_act fn_name qvars pats rule_rhs
  1195. -- See Note [Transfer activation]
  1196. ; return (spec_usg, OS call_pat rule spec_id spec_rhs) }
  1197. calcSpecStrictness :: Id -- The original function
  1198. -> [Var] -> [CoreExpr] -- Call pattern
  1199. -> StrictSig -- Strictness of specialised thing
  1200. -- See Note [Transfer strictness]
  1201. calcSpecStrictness fn qvars pats
  1202. = StrictSig (mkTopDmdType spec_dmds topRes)
  1203. where
  1204. spec_dmds = [ lookupVarEnv dmd_env qv `orElse` topDmd | qv <- qvars, isId qv ]
  1205. StrictSig (DmdType _ dmds _) = idStrictness fn
  1206. dmd_env = go emptyVarEnv dmds pats
  1207. go :: DmdEnv -> [Demand] -> [CoreExpr] -> DmdEnv
  1208. go env ds (Type {} : pats) = go env ds pats
  1209. go env ds (Coercion {} : pats) = go env ds pats
  1210. go env (d:ds) (pat : pats) = go (go_one env d pat) ds pats
  1211. go env _ _ = env
  1212. go_one :: DmdEnv -> Demand -> CoreExpr -> DmdEnv
  1213. go_one env d (Var v) = extendVarEnv_C bothDmd env v d
  1214. go_one env d e
  1215. | Just ds <- splitProdDmd_maybe d -- NB: d does not have to be strict
  1216. , (Var _, args) <- collectArgs e = go env ds args
  1217. go_one env _ _ = env
  1218. \end{code}
  1219. Note [Specialise original body]
  1220. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1221. The RhsInfo for a binding keeps the *original* body of the binding. We
  1222. must specialise that, *not* the result of applying specExpr to the RHS
  1223. (which is also kept in RhsInfo). Otherwise we end up specialising a
  1224. specialised RHS, and that can lead directly to exponential behaviour.
  1225. Note [Transfer activation]
  1226. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1227. This note is for SpecConstr, but exactly the same thing
  1228. happens in the overloading specialiser; see
  1229. Note [Auto-specialisation and RULES] in Specialise.
  1230. In which phase should the specialise-constructor rules be active?
  1231. Originally I made them always-active, but Manuel found that this
  1232. defeated some clever user-written rules. Then I made them active only
  1233. in Phase 0; after all, currently, the specConstr transformation is
  1234. only run after the simplifier has reached Phase 0, but that meant
  1235. that specialisations didn't fire inside wrappers; see test
  1236. simplCore/should_compile/spec-inline.
  1237. So now I just use the inline-activation of the parent Id, as the
  1238. activation for the specialiation RULE, just like the main specialiser;
  1239. This in turn means there is no point in specialising NOINLINE things,
  1240. so we test for that.
  1241. Note [Transfer strictness]
  1242. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1243. We must transfer strictness information from the original function to
  1244. the specialised one. Suppose, for example
  1245. f has strictness SS
  1246. and a RULE f (a:as) b = f_spec a as b
  1247. Now we want f_spec to have strictness LLS, otherwise we'll use call-by-need
  1248. when calling f_spec instead of call-by-value. And that can result in
  1249. unbounded worsening in space (cf the classic foldl vs foldl')
  1250. See Trac #3437 for a good example.
  1251. The function calcSpecStrictness performs the calculation.
  1252. %************************************************************************
  1253. %* *
  1254. \subsection{Argument analysis}
  1255. %* *
  1256. %************************************************************************
  1257. This code deals with analysing call-site arguments to see whether
  1258. they are constructor applications.
  1259. Note [Free type variables of the qvar types]
  1260. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1261. In a call (f @a x True), that we want to specialise, what variables should
  1262. we quantify over. Clearly over 'a' and 'x', but what about any type variables
  1263. free in x's type? In fact we don't need to worry about them because (f @a)
  1264. can only be a well-typed application if its type is compatible with x, so any
  1265. variables free in x's type must be free in (f @a), and hence either be gathered
  1266. via 'a' itself, or be in scope at f's defn. Hence we just take
  1267. (exprsFreeVars pats).
  1268. BUT phantom type synonyms can mess this reasoning up,
  1269. eg x::T b with type T b = Int
  1270. So we apply expandTypeSynonyms to the bound Ids.
  1271. See Trac # 5458. Yuk.
  1272. \begin{code}
  1273. type CallPat = ([Var], [CoreExpr]) -- Quantified variables and arguments
  1274. callsToPats :: ScEnv -> [OneSpec] -> [ArgOcc] -> [Call] -> UniqSM (Bool, [CallPat])
  1275. -- Result has no duplicate patterns,
  1276. -- nor ones mentioned in done_pats
  1277. -- Bool indicates that there was at least one boring pattern
  1278. callsToPats env done_specs bndr_occs calls
  1279. = do { mb_pats <- mapM (callToPats env bndr_occs) calls
  1280. ; let good_pats :: [(CallPat, ValueEnv)]
  1281. good_pats = catMaybes mb_pats
  1282. done_pats = [p | OS p _ _ _ <- done_specs]
  1283. is_done p = any (samePat p) done_pats
  1284. no_recursive = map fst (filterOut (is_too_recursive env) good_pats)
  1285. ; return (any isNothing mb_pats,
  1286. filterOut is_done (nubBy samePat no_recursive)) }
  1287. is_too_recursive :: ScEnv -> (CallPat, ValueEnv) -> Bool
  1288. -- Count the number of recursive constructors in a call pattern,
  1289. -- filter out if there are more than the maximum.
  1290. -- This is only necessary if ForceSpecConstr is in effect:
  1291. -- otherwise specConstrCount will cause specialisation to terminate.
  1292. is_too_recursive env ((_,exprs), val_env)
  1293. = sc_force env && maximum (map go exprs) > sc_recursive env
  1294. where
  1295. go e
  1296. | Just (ConVal (DataAlt dc) args) <- isValue val_env e
  1297. , isRecursiveTyCon (dataConTyCon dc)
  1298. = 1 + sum (map go args)
  1299. |App f a <- e
  1300. = go f + go a
  1301. | otherwise
  1302. = 0
  1303. callToPats :: ScEnv -> [ArgOcc] -> Call -> UniqSM (Maybe (CallPat, ValueEnv))
  1304. -- The [Var] is the variables to quantify over in the rule
  1305. -- Type variables come first, since they may scope
  1306. -- over the following term variables
  1307. -- The [CoreExpr] are the argument patterns for the rule
  1308. callToPats env bndr_occs (con_env, args)
  1309. | length args < length bndr_occs -- Check saturated
  1310. = return Nothing
  1311. | otherwise
  1312. = do { let in_scope = substInScope (sc_subst env)
  1313. ; (interesting, pats) <- argsToPats env in_scope con_env args bndr_occs
  1314. ; let pat_fvs = varSetElems (exprsFreeVars pats)
  1315. in_scope_vars = getInScopeVars in_scope
  1316. qvars = filterOut (`elemVarSet` in_scope_vars) pat_fvs
  1317. -- Quantify over variables that are not in sccpe
  1318. -- at the call site
  1319. -- See Note [Free type variables of the qvar types]
  1320. -- See Note [Shadowing] at the top
  1321. (tvs, ids) = partition isTyVar qvars
  1322. qvars' = tvs ++ map sanitise ids
  1323. -- Put the type variables first; the type of a term
  1324. -- variable may mention a type variable
  1325. sanitise id = id `setIdType` expandTypeSynonyms (idType id)
  1326. -- See Note [Free type variables of the qvar types]
  1327. ; -- pprTrace "callToPats" (ppr args $$ ppr bndr_occs) $
  1328. if interesting
  1329. then return (Just ((qvars', pats), con_env))
  1330. else return Nothing }
  1331. -- argToPat takes an actual argument, and returns an abstracted
  1332. -- version, consisting of just the "constructor skeleton" of the
  1333. -- argument, with non-constructor sub-expression replaced by new
  1334. -- placeholder variables. For example:
  1335. -- C a (D (f x) (g y)) ==> C p1 (D p2 p3)
  1336. argToPat :: ScEnv
  1337. -> InScopeSet -- What's in scope at the fn defn site
  1338. -> ValueEnv -- ValueEnv at the call site
  1339. -> CoreArg -- A call arg (or component thereof)
  1340. -> ArgOcc
  1341. -> UniqSM (Bool, CoreArg)
  1342. -- Returns (interesting, pat),
  1343. -- where pat is the pattern derived from the argument
  1344. -- interesting=True if the pattern is non-trivial (not a variable or type)
  1345. -- E.g. x:xs --> (True, x:xs)
  1346. -- f xs --> (False, w) where w is a fresh wildcard
  1347. -- (f xs, 'c') --> (True, (w, 'c')) where w is a fresh wildcard
  1348. -- \x. x+y --> (True, \x. x+y)
  1349. -- lvl7 --> (True, lvl7) if lvl7 is bound
  1350. -- somewhere further out
  1351. argToPat _env _in_scope _val_env arg@(Type {}) _arg_occ
  1352. = return (False, arg)
  1353. argToPat env in_scope val_env (Tick _ arg) arg_occ
  1354. = argToPat env in_scope val_env arg arg_occ
  1355. -- Note [Notes in call patterns]
  1356. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1357. -- Ignore Notes. In particular, we want to ignore any InlineMe notes
  1358. -- Perhaps we should not ignore profiling notes, but I'm going to
  1359. -- ride roughshod over them all for now.
  1360. --- See Note [Notes in RULE matching] in Rules
  1361. argToPat env in_scope val_env (Let _ arg) arg_occ
  1362. = argToPat env in_scope val_env arg arg_occ
  1363. -- See Note [Matching lets] in Rule.lhs
  1364. -- Look through let expressions
  1365. -- e.g. f (let v = rhs in (v,w))
  1366. -- Here we can specialise for f (v,w)
  1367. -- because the rule-matcher will look through the let.
  1368. {- Disabled; see Note [Matching cases] in Rule.lhs
  1369. argToPat env in_scope val_env (Case scrut _ _ [(_, _, rhs)]) arg_occ
  1370. | exprOkForSpeculation scrut -- See Note [Matching cases] in Rule.hhs
  1371. = argToPat env in_scope val_env rhs arg_occ
  1372. -}
  1373. argToPat env in_scope val_env (Cast arg co) arg_occ
  1374. | isReflCo co -- Substitution in the SpecConstr itself
  1375. -- can lead to identity coercions
  1376. = argToPat env in_scope val_env arg arg_occ
  1377. | not (ignoreType env ty2)
  1378. = do { (interesting, arg') <- argToPat env in_scope val_env arg arg_occ
  1379. ; if not interesting then
  1380. wildCardPat ty2
  1381. else do
  1382. { -- Make a wild-card pattern for the coercion
  1383. uniq <- getUniqueUs
  1384. ; let co_name = mkSysTvName uniq (fsLit "sg")
  1385. co_var = mkCoVar co_name (mkCoercionType ty1 ty2)
  1386. ; return (interesting, Cast arg' (mkCoVarCo co_var)) } }
  1387. where
  1388. Pair ty1 ty2 = coercionKind co
  1389. {- Disabling lambda specialisation for now
  1390. It's fragile, and the spec_loop can be infinite
  1391. argToPat in_scope val_env arg arg_occ
  1392. | is_value_lam arg
  1393. = return (True, arg)
  1394. where
  1395. is_value_lam (Lam v e) -- Spot a value lambda, even if
  1396. | isId v = True -- it is inside a type lambda
  1397. | otherwise = is_value_lam e
  1398. is_value_lam other = False
  1399. -}
  1400. -- Check for a constructor application
  1401. -- NB: this *precedes* the Var case, so that we catch nullary constrs
  1402. argToPat env in_scope val_env arg arg_occ
  1403. | Just (ConVal (DataAlt dc) args) <- isValue val_env arg
  1404. , not (ignoreDataCon env dc) -- See Note [NoSpecConstr]
  1405. , Just arg_occs <- mb_scrut dc
  1406. = do { let (ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) args
  1407. ; (_, args') <- argsToPats env in_scope val_env rest_args arg_occs
  1408. ; return (True,
  1409. mkConApp dc (ty_args ++ args')) }
  1410. where
  1411. mb_scrut dc = case arg_occ of
  1412. ScrutOcc bs
  1413. | Just occs <- lookupUFM bs dc
  1414. -> Just (occs) -- See Note [Reboxing]
  1415. _other | sc_force env -> Just (repeat UnkOcc)
  1416. | otherwise -> Nothing
  1417. -- Check if the argument is a variable that
  1418. -- (a) is used in an interesting way in the body
  1419. -- (b) we know what its value is
  1420. -- In that case it counts as "interesting"
  1421. argToPat env in_scope val_env (Var v) arg_occ
  1422. | sc_force env || case arg_occ of { UnkOcc -> False; _other -> True }, -- (a)
  1423. is_value, -- (b)
  1424. not (ignoreType env (varType v))
  1425. = return (True, Var v)
  1426. where
  1427. is_value
  1428. | isLocalId v = v `elemInScopeSet` in_scope
  1429. && isJust (lookupVarEnv val_env v)
  1430. -- Local variables have values in val_env
  1431. | otherwise = isValueUnfolding (idUnfolding v)
  1432. -- Imports have unfoldings
  1433. -- I'm really not sure what this comment means
  1434. -- And by not wild-carding we tend to get forall'd
  1435. -- variables that are in scope, which in turn can
  1436. -- expose the weakness in let-matching
  1437. -- See Note [Matching lets] in Rules
  1438. -- Check for a variable bound inside the function.
  1439. -- Don't make a wild-card, because we may usefully share
  1440. -- e.g. f a = let x = ... in f (x,x)
  1441. -- NB: this case follows the lambda and con-app cases!!
  1442. -- argToPat _in_scope _val_env (Var v) _arg_occ
  1443. -- = return (False, Var v)
  1444. -- SLPJ : disabling this to avoid proliferation of versions
  1445. -- also works badly when thinking about seeding the loop
  1446. -- from the body of the let
  1447. -- f x y = letrec g z = ... in g (x,y)
  1448. -- We don't want to specialise for that *particular* x,y
  1449. -- The default case: make a wild-card
  1450. -- We use this for coercions too
  1451. argToPat _env _in_scope _val_env arg _arg_occ
  1452. = wildCardPat (exprType arg)
  1453. wildCardPat :: Type -> UniqSM (Bool, CoreArg)
  1454. wildCardPat ty
  1455. = do { uniq <- getUniqueUs
  1456. ; let id = mkSysLocal (fsLit "sc") uniq ty
  1457. ; return (False, varToCoreExpr id) }
  1458. argsToPats :: ScEnv -> InScopeSet -> ValueEnv
  1459. -> [CoreArg] -> [ArgOcc] -- Should be same length
  1460. -> UniqSM (Bool, [CoreArg])
  1461. argsToPats env in_scope val_env args occs
  1462. = do { stuff <- zipWithM (argToPat env in_scope val_env) args occs
  1463. ; let (interesting_s, args') = unzip stuff
  1464. ; return (or interesting_s, args') }
  1465. \end{code}
  1466. \begin{code}
  1467. isValue :: ValueEnv -> CoreExpr -> Maybe Value
  1468. isValue _env (Lit lit)
  1469. | litIsLifted lit = Nothing
  1470. | otherwise = Just (ConVal (LitAlt lit) [])
  1471. isValue env (Var v)
  1472. | Just cval <- lookupVarEnv env v
  1473. = Just cval -- You might think we could look in the idUnfolding here
  1474. -- but that doesn't take account of which branch of a
  1475. -- case we are in, which is the whole point
  1476. | not (isLocalId v) && isCheapUnfolding unf
  1477. = isValue env (unfoldingTemplate unf)
  1478. where
  1479. unf = idUnfolding v
  1480. -- However we do want to consult the unfolding
  1481. -- as well, for let-bound constructors!
  1482. isValue env (Lam b e)
  1483. | isTyVar b = case isValue env e of
  1484. Just _ -> Just LambdaVal
  1485. Nothing -> Nothing
  1486. | otherwise = Just LambdaVal
  1487. isValue _env expr -- Maybe it's a constructor application
  1488. | (Var fun, args) <- collectArgs expr
  1489. = case isDataConWorkId_maybe fun of
  1490. Just con | args `lengthAtLeast` dataConRepArity con
  1491. -- Check saturated; might be > because the
  1492. -- arity excludes type args
  1493. -> Just (ConVal (DataAlt con) args)
  1494. _other | valArgCount args < idArity fun
  1495. -- Under-applied function
  1496. -> Just LambdaVal -- Partial application
  1497. _other -> Nothing
  1498. isValue _env _expr = Nothing
  1499. valueIsWorkFree :: Value -> Bool
  1500. valueIsWorkFree LambdaVal = True
  1501. valueIsWorkFree (ConVal _ args) = all exprIsWorkFree args
  1502. samePat :: CallPat -> CallPat -> Bool
  1503. samePat (vs1, as1) (vs2, as2)
  1504. = all2 same as1 as2
  1505. where
  1506. same (Var v1) (Var v2)
  1507. | v1 `elem` vs1 = v2 `elem` vs2
  1508. | v2 `elem` vs2 = False
  1509. | otherwise = v1 == v2
  1510. same (Lit l1) (Lit l2) = l1==l2
  1511. same (App f1 a1) (App f2 a2) = same f1 f2 && same a1 a2
  1512. same (Type {}) (Type {}) = True -- Note [Ignore type differences]
  1513. same (Coercion {}) (Coercion {}) = True
  1514. same (Tick _ e1) e2 = same e1 e2 -- Ignore casts and notes
  1515. same (Cast e1 _) e2 = same e1 e2
  1516. same e1 (Tick _ e2) = same e1 e2
  1517. same e1 (Cast e2 _) = same e1 e2
  1518. same e1 e2 = WARN( bad e1 || bad e2, ppr e1 $$ ppr e2)
  1519. False -- Let, lambda, case should not occur
  1520. bad (Case {}) = True
  1521. bad (Let {}) = True
  1522. bad (Lam {}) = True
  1523. bad _other = False
  1524. \end{code}
  1525. Note [Ignore type differences]
  1526. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1527. We do not want to generate specialisations where the call patterns
  1528. differ only in their type arguments! Not only is it utterly useless,
  1529. but it also means that (with polymorphic recursion) we can generate
  1530. an infinite number of specialisations. Example is Data.Sequence.adjustTree,
  1531. I think.