PageRenderTime 56ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/specialise/SpecConstr.lhs

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