2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[PrimOp]{Primitive operations (machine-level)}
7 {-# OPTIONS -fno-warn-unused-binds #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 PrimOp(..), allThePrimOps,
16 primOpType, primOpSig,
17 primOpTag, maxPrimOpTag, primOpOcc,
21 primOpOutOfLine, primOpNeedsWrapper,
22 primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
24 getPrimOpResultInfo, PrimOpResultInfo(..)
27 #include "HsVersions.h"
34 import OccName ( OccName, pprOccName, mkVarOccFS )
35 import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
36 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
38 import BasicTypes ( Arity, Boxity(..) )
39 import Unique ( Unique, mkPrimOpIdUnique )
45 %************************************************************************
47 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
49 %************************************************************************
51 These are in \tr{state-interface.verb} order.
57 #include "primop-data-decl.hs-incl"
60 Used for the Ord instance
63 primOpTag :: PrimOp -> Int
64 primOpTag op = iBox (tagOf_PrimOp op)
67 -- tagOf_PrimOp :: PrimOp -> FastInt
68 #include "primop-tag.hs-incl"
71 instance Eq PrimOp where
72 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
74 instance Ord PrimOp where
75 op1 < op2 = tagOf_PrimOp op1 <# tagOf_PrimOp op2
76 op1 <= op2 = tagOf_PrimOp op1 <=# tagOf_PrimOp op2
77 op1 >= op2 = tagOf_PrimOp op1 >=# tagOf_PrimOp op2
78 op1 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2
79 op1 `compare` op2 | op1 < op2 = LT
83 instance Outputable PrimOp where
86 instance Show PrimOp where
87 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
90 An @Enum@-derived list would be better; meanwhile... (ToDo)
93 allThePrimOps :: [PrimOp]
95 #include "primop-list.hs-incl"
99 tagToEnumKey :: Unique
100 tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
105 %************************************************************************
107 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
109 %************************************************************************
111 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
112 refer to the primitive operation. The conventional \tr{#}-for-
113 unboxed ops is added on later.
115 The reason for the funny characters in the names is so we do not
116 interfere with the programmer's Haskell name spaces.
118 We use @PrimKinds@ for the ``type'' information, because they're
119 (slightly) more convenient to use than @TyCons@.
122 = Dyadic OccName -- string :: T -> T -> T
124 | Monadic OccName -- string :: T -> T
126 | Compare OccName -- string :: T -> T -> Bool
129 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
134 mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
135 mkDyadic str ty = Dyadic (mkVarOccFS str) ty
136 mkMonadic str ty = Monadic (mkVarOccFS str) ty
137 mkCompare str ty = Compare (mkVarOccFS str) ty
139 mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
140 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
143 %************************************************************************
145 \subsubsection{Strictness}
147 %************************************************************************
149 Not all primops are strict!
152 primOpStrictness :: PrimOp -> Arity -> StrictSig
153 -- See Demand.StrictnessInfo for discussion of what the results
154 -- The arity should be the arity of the primop; that's why
155 -- this function isn't exported.
156 #include "primop-strictness.hs-incl"
159 %************************************************************************
161 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
163 %************************************************************************
165 @primOpInfo@ gives all essential information (from which everything
166 else, notably a type, can be constructed) for each @PrimOp@.
169 primOpInfo :: PrimOp -> PrimOpInfo
170 #include "primop-primop-info.hs-incl"
173 Here are a load of comments from the old primOp info:
175 A @Word#@ is an unsigned @Int#@.
177 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
179 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
181 Decoding of floating-point numbers is sorta Integer-related. Encoding
182 is done with plain ccalls now (see PrelNumExtra.lhs).
184 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
186 mkWeak# :: k -> v -> f -> State# RealWorld
187 -> (# State# RealWorld, Weak# v #)
189 In practice, you'll use the higher-level
191 data Weak v = Weak# v
192 mkWeak :: k -> v -> IO () -> IO (Weak v)
194 The following operation dereferences a weak pointer. The weak pointer
195 may have been finalized, so the operation returns a result code which
196 must be inspected before looking at the dereferenced value.
198 deRefWeak# :: Weak# v -> State# RealWorld ->
199 (# State# RealWorld, v, Int# #)
201 Only look at v if the Int# returned is /= 0 !!
203 The higher-level op is
205 deRefWeak :: Weak v -> IO (Maybe v)
207 Weak pointers can be finalized early by using the finalize# operation:
209 finalizeWeak# :: Weak# v -> State# RealWorld ->
210 (# State# RealWorld, Int#, IO () #)
212 The Int# returned is either
214 0 if the weak pointer has already been finalized, or it has no
215 finalizer (the third component is then invalid).
217 1 if the weak pointer is still alive, with the finalizer returned
218 as the third component.
220 A {\em stable name/pointer} is an index into a table of stable name
221 entries. Since the garbage collector is told about stable pointers,
222 it is safe to pass a stable pointer to external systems such as C
226 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
227 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
228 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
229 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
232 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
233 operation since it doesn't (directly) involve IO operations. The
234 reason is that if some optimisation pass decided to duplicate calls to
235 @makeStablePtr#@ and we only pass one of the stable pointers over, a
236 massive space leak can result. Putting it into the IO monad
237 prevents this. (Another reason for putting them in a monad is to
238 ensure correct sequencing wrt the side-effecting @freeStablePtr@
241 An important property of stable pointers is that if you call
242 makeStablePtr# twice on the same object you get the same stable
245 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
246 besides, it's not likely to be used from Haskell) so it's not a
249 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
254 A stable name is like a stable pointer, but with three important differences:
256 (a) You can't deRef one to get back to the original object.
257 (b) You can convert one to an Int.
258 (c) You don't need to 'freeStableName'
260 The existence of a stable name doesn't guarantee to keep the object it
261 points to alive (unlike a stable pointer), hence (a).
265 (a) makeStableName always returns the same value for a given
266 object (same as stable pointers).
268 (b) if two stable names are equal, it implies that the objects
269 from which they were created were the same.
271 (c) stableNameToInt always returns the same Int for a given
275 -- HWL: The first 4 Int# in all par... annotations denote:
276 -- name, granularity info, size of result, degree of parallelism
277 -- Same structure as _seq_ i.e. returns Int#
278 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
279 -- `the processor containing the expression v'; it is not evaluated
281 These primops are pretty wierd.
283 dataToTag# :: a -> Int (arg must be an evaluated data type)
284 tagToEnum# :: Int -> a (result type must be an enumerated type)
286 The constraints aren't currently checked by the front end, but the
287 code generator will fall over if they aren't satisfied.
291 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
295 %************************************************************************
297 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
299 %************************************************************************
301 Some PrimOps need to be called out-of-line because they either need to
302 perform a heap check or they block.
306 primOpOutOfLine :: PrimOp -> Bool
307 #include "primop-out-of-line.hs-incl"
311 primOpOkForSpeculation
312 ~~~~~~~~~~~~~~~~~~~~~~
313 Sometimes we may choose to execute a PrimOp even though it isn't
314 certain that its result will be required; ie execute them
315 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
316 this is OK, because PrimOps are usually cheap, but it isn't OK for
317 (a)~expensive PrimOps and (b)~PrimOps which can fail.
319 PrimOps that have side effects also should not be executed speculatively.
321 Ok-for-speculation also means that it's ok *not* to execute the
325 Here the result is not used, so we can discard the primop. Anything
326 that has side effects mustn't be dicarded in this way, of course!
328 See also @primOpIsCheap@ (below).
332 primOpOkForSpeculation :: PrimOp -> Bool
333 -- See comments with CoreUtils.exprOkForSpeculation
334 primOpOkForSpeculation op
335 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
341 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
342 WARNING), we just borrow some other predicates for a
343 what-should-be-good-enough test. "Cheap" means willing to call it more
344 than once, and/or push it inside a lambda. The latter could change the
345 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
348 primOpIsCheap :: PrimOp -> Bool
349 primOpIsCheap op = primOpOkForSpeculation op
350 -- In March 2001, we changed this to
351 -- primOpIsCheap op = False
352 -- thereby making *no* primops seem cheap. But this killed eta
353 -- expansion on case (x ==# y) of True -> \s -> ...
354 -- which is bad. In particular a loop like
357 -- loop i | i == n = return ()
358 -- | otherwise = bar i >> loop (i+1)
359 -- allocated a closure every time round because it doesn't eta expand.
361 -- The problem that originally gave rise to the change was
362 -- let x = a +# b *# c in x +# x
363 -- were we don't want to inline x. But primopIsCheap doesn't control
364 -- that (it's exprIsDupable that does) so the problem doesn't occur
365 -- even if primOpIsCheap sometimes says 'True'.
370 primOpIsDupable means that the use of the primop is small enough to
371 duplicate into different case branches. See CoreUtils.exprIsDupable.
374 primOpIsDupable :: PrimOp -> Bool
375 -- See comments with CoreUtils.exprIsDupable
376 -- We say it's dupable it isn't implemented by a C call with a wrapper
377 primOpIsDupable op = not (primOpNeedsWrapper op)
382 primOpCanFail :: PrimOp -> Bool
383 #include "primop-can-fail.hs-incl"
386 And some primops have side-effects and so, for example, must not be
390 primOpHasSideEffects :: PrimOp -> Bool
391 #include "primop-has-side-effects.hs-incl"
394 Inline primitive operations that perform calls need wrappers to save
395 any live variables that are stored in caller-saves registers.
398 primOpNeedsWrapper :: PrimOp -> Bool
399 #include "primop-needs-wrapper.hs-incl"
403 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
405 = case primOpInfo op of
406 Dyadic _occ ty -> dyadic_fun_ty ty
407 Monadic _occ ty -> monadic_fun_ty ty
408 Compare _occ ty -> compare_fun_ty ty
410 GenPrimOp _occ tyvars arg_tys res_ty ->
411 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
413 primOpOcc :: PrimOp -> OccName
414 primOpOcc op = case primOpInfo op of
418 GenPrimOp occ _ _ _ -> occ
420 -- primOpSig is like primOpType but gives the result split apart:
421 -- (type variables, argument types, result type)
422 -- It also gives arity, strictness info
424 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
426 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
428 arity = length arg_tys
429 (tyvars, arg_tys, res_ty)
430 = case (primOpInfo op) of
431 Monadic _occ ty -> ([], [ty], ty )
432 Dyadic _occ ty -> ([], [ty,ty], ty )
433 Compare _occ ty -> ([], [ty,ty], boolTy)
434 GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty)
438 data PrimOpResultInfo
439 = ReturnsPrim PrimRep
442 -- Some PrimOps need not return a manifest primitive or algebraic value
443 -- (i.e. they might return a polymorphic value). These PrimOps *must*
444 -- be out of line, or the code generator won't work.
446 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
447 getPrimOpResultInfo op
448 = case (primOpInfo op) of
449 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
450 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
451 Compare _ _ -> ReturnsAlg boolTyCon
452 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
453 | otherwise -> ReturnsAlg tc
455 tc = tyConAppTyCon ty
456 -- All primops return a tycon-app result
457 -- The tycon can be an unboxed tuple, though, which
458 -- gives rise to a ReturnAlg
461 The commutable ops are those for which we will try to move constants
462 to the right hand side for strength reduction.
465 commutableOp :: PrimOp -> Bool
466 #include "primop-commutable.hs-incl"
471 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
472 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
473 monadic_fun_ty ty = mkFunTy ty ty
474 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
479 pprPrimOp :: PrimOp -> SDoc
480 pprPrimOp other_op = pprOccName (primOpOcc other_op)