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, primOpCodeSize,
22 primOpOkForSpeculation, primOpIsCheap,
24 getPrimOpResultInfo, PrimOpResultInfo(..),
29 #include "HsVersions.h"
36 import OccName ( OccName, pprOccName, mkVarOccFS )
37 import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
38 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
40 import BasicTypes ( Arity, Boxity(..) )
41 import ForeignCall ( CLabelString )
42 import Unique ( Unique, mkPrimOpIdUnique )
46 import Module ( PackageId )
49 %************************************************************************
51 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
53 %************************************************************************
55 These are in \tr{state-interface.verb} order.
61 #include "primop-data-decl.hs-incl"
64 Used for the Ord instance
67 primOpTag :: PrimOp -> Int
68 primOpTag op = iBox (tagOf_PrimOp op)
71 -- tagOf_PrimOp :: PrimOp -> FastInt
72 #include "primop-tag.hs-incl"
75 instance Eq PrimOp where
76 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
78 instance Ord PrimOp where
79 op1 < op2 = tagOf_PrimOp op1 <# tagOf_PrimOp op2
80 op1 <= op2 = tagOf_PrimOp op1 <=# tagOf_PrimOp op2
81 op1 >= op2 = tagOf_PrimOp op1 >=# tagOf_PrimOp op2
82 op1 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2
83 op1 `compare` op2 | op1 < op2 = LT
87 instance Outputable PrimOp where
90 instance Show PrimOp where
91 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
94 An @Enum@-derived list would be better; meanwhile... (ToDo)
97 allThePrimOps :: [PrimOp]
99 #include "primop-list.hs-incl"
103 tagToEnumKey :: Unique
104 tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
109 %************************************************************************
111 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
113 %************************************************************************
115 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
116 refer to the primitive operation. The conventional \tr{#}-for-
117 unboxed ops is added on later.
119 The reason for the funny characters in the names is so we do not
120 interfere with the programmer's Haskell name spaces.
122 We use @PrimKinds@ for the ``type'' information, because they're
123 (slightly) more convenient to use than @TyCons@.
126 = Dyadic OccName -- string :: T -> T -> T
128 | Monadic OccName -- string :: T -> T
130 | Compare OccName -- string :: T -> T -> Bool
133 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
138 mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
139 mkDyadic str ty = Dyadic (mkVarOccFS str) ty
140 mkMonadic str ty = Monadic (mkVarOccFS str) ty
141 mkCompare str ty = Compare (mkVarOccFS str) ty
143 mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
144 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
147 %************************************************************************
149 \subsubsection{Strictness}
151 %************************************************************************
153 Not all primops are strict!
156 primOpStrictness :: PrimOp -> Arity -> StrictSig
157 -- See Demand.StrictnessInfo for discussion of what the results
158 -- The arity should be the arity of the primop; that's why
159 -- this function isn't exported.
160 #include "primop-strictness.hs-incl"
163 %************************************************************************
165 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
167 %************************************************************************
169 @primOpInfo@ gives all essential information (from which everything
170 else, notably a type, can be constructed) for each @PrimOp@.
173 primOpInfo :: PrimOp -> PrimOpInfo
174 #include "primop-primop-info.hs-incl"
177 Here are a load of comments from the old primOp info:
179 A @Word#@ is an unsigned @Int#@.
181 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
183 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
185 Decoding of floating-point numbers is sorta Integer-related. Encoding
186 is done with plain ccalls now (see PrelNumExtra.lhs).
188 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
190 mkWeak# :: k -> v -> f -> State# RealWorld
191 -> (# State# RealWorld, Weak# v #)
193 In practice, you'll use the higher-level
195 data Weak v = Weak# v
196 mkWeak :: k -> v -> IO () -> IO (Weak v)
198 The following operation dereferences a weak pointer. The weak pointer
199 may have been finalized, so the operation returns a result code which
200 must be inspected before looking at the dereferenced value.
202 deRefWeak# :: Weak# v -> State# RealWorld ->
203 (# State# RealWorld, v, Int# #)
205 Only look at v if the Int# returned is /= 0 !!
207 The higher-level op is
209 deRefWeak :: Weak v -> IO (Maybe v)
211 Weak pointers can be finalized early by using the finalize# operation:
213 finalizeWeak# :: Weak# v -> State# RealWorld ->
214 (# State# RealWorld, Int#, IO () #)
216 The Int# returned is either
218 0 if the weak pointer has already been finalized, or it has no
219 finalizer (the third component is then invalid).
221 1 if the weak pointer is still alive, with the finalizer returned
222 as the third component.
224 A {\em stable name/pointer} is an index into a table of stable name
225 entries. Since the garbage collector is told about stable pointers,
226 it is safe to pass a stable pointer to external systems such as C
230 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
231 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
232 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
233 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
236 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
237 operation since it doesn't (directly) involve IO operations. The
238 reason is that if some optimisation pass decided to duplicate calls to
239 @makeStablePtr#@ and we only pass one of the stable pointers over, a
240 massive space leak can result. Putting it into the IO monad
241 prevents this. (Another reason for putting them in a monad is to
242 ensure correct sequencing wrt the side-effecting @freeStablePtr@
245 An important property of stable pointers is that if you call
246 makeStablePtr# twice on the same object you get the same stable
249 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
250 besides, it's not likely to be used from Haskell) so it's not a
253 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
258 A stable name is like a stable pointer, but with three important differences:
260 (a) You can't deRef one to get back to the original object.
261 (b) You can convert one to an Int.
262 (c) You don't need to 'freeStableName'
264 The existence of a stable name doesn't guarantee to keep the object it
265 points to alive (unlike a stable pointer), hence (a).
269 (a) makeStableName always returns the same value for a given
270 object (same as stable pointers).
272 (b) if two stable names are equal, it implies that the objects
273 from which they were created were the same.
275 (c) stableNameToInt always returns the same Int for a given
279 -- HWL: The first 4 Int# in all par... annotations denote:
280 -- name, granularity info, size of result, degree of parallelism
281 -- Same structure as _seq_ i.e. returns Int#
282 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
283 -- `the processor containing the expression v'; it is not evaluated
285 These primops are pretty wierd.
287 dataToTag# :: a -> Int (arg must be an evaluated data type)
288 tagToEnum# :: Int -> a (result type must be an enumerated type)
290 The constraints aren't currently checked by the front end, but the
291 code generator will fall over if they aren't satisfied.
293 %************************************************************************
295 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
297 %************************************************************************
299 Some PrimOps need to be called out-of-line because they either need to
300 perform a heap check or they block.
304 primOpOutOfLine :: PrimOp -> Bool
305 #include "primop-out-of-line.hs-incl"
309 primOpOkForSpeculation
310 ~~~~~~~~~~~~~~~~~~~~~~
311 Sometimes we may choose to execute a PrimOp even though it isn't
312 certain that its result will be required; ie execute them
313 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
314 this is OK, because PrimOps are usually cheap, but it isn't OK for
315 (a)~expensive PrimOps and (b)~PrimOps which can fail.
317 PrimOps that have side effects also should not be executed speculatively.
319 Ok-for-speculation also means that it's ok *not* to execute the
323 Here the result is not used, so we can discard the primop. Anything
324 that has side effects mustn't be dicarded in this way, of course!
326 See also @primOpIsCheap@ (below).
330 primOpOkForSpeculation :: PrimOp -> Bool
331 -- See comments with CoreUtils.exprOkForSpeculation
332 primOpOkForSpeculation op
333 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
339 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
340 WARNING), we just borrow some other predicates for a
341 what-should-be-good-enough test. "Cheap" means willing to call it more
342 than once, and/or push it inside a lambda. The latter could change the
343 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
346 primOpIsCheap :: PrimOp -> Bool
347 primOpIsCheap op = primOpOkForSpeculation op
348 -- In March 2001, we changed this to
349 -- primOpIsCheap op = False
350 -- thereby making *no* primops seem cheap. But this killed eta
351 -- expansion on case (x ==# y) of True -> \s -> ...
352 -- which is bad. In particular a loop like
355 -- loop i | i == n = return ()
356 -- | otherwise = bar i >> loop (i+1)
357 -- allocated a closure every time round because it doesn't eta expand.
359 -- The problem that originally gave rise to the change was
360 -- let x = a +# b *# c in x +# x
361 -- were we don't want to inline x. But primopIsCheap doesn't control
362 -- that (it's exprIsDupable that does) so the problem doesn't occur
363 -- even if primOpIsCheap sometimes says 'True'.
368 Gives an indication of the code size of a primop, for the purposes of
369 calculating unfolding sizes; see CoreUnfold.sizeExpr.
372 primOpCodeSize :: PrimOp -> Int
373 #include "primop-code-size.hs-incl"
375 primOpCodeSizeDefault :: Int
376 primOpCodeSizeDefault = 1
377 -- CoreUnfold.primOpSize already takes into account primOpOutOfLine
378 -- and adds some further costs for the args in that case.
380 primOpCodeSizeForeignCall :: Int
381 primOpCodeSizeForeignCall = 4
385 primOpCanFail :: PrimOp -> Bool
386 #include "primop-can-fail.hs-incl"
389 And some primops have side-effects and so, for example, must not be
392 This predicate means a little more than just "modifies the state of
393 the world". What it really means is "it cosumes the state on its
394 input". To see what this means, consider
397 t = case readMutVar# v s0 of (# s1, x #) -> (S# s1, x)
398 y = case t of (s,x) -> x
402 Now, this is part of an ST or IO thread, so we are guaranteed by
403 construction that the program uses the state in a single-threaded way.
404 Whenever the state resulting from the readMutVar# is demanded, the
405 readMutVar# will be performed, and it will be ordered correctly with
406 respect to other operations in the monad.
408 But there's another way this could go wrong: GHC can inline t into y,
409 and inline y. Then although the original readMutVar# will still be
410 correctly ordered with respect to the other operations, there will be
411 one or more extra readMutVar#s performed later, possibly out-of-order.
412 This really happened; see #3207.
414 The property we need to capture about readMutVar# is that it consumes
415 the State# value on its input. We must retain the linearity of the
418 Our fix for this is to declare any primop that must be used linearly
419 as having side-effects. When primOpHasSideEffects is True,
420 primOpOkForSpeculation will be False, and hence primOpIsCheap will
421 also be False, and applications of the primop will never be
425 primOpHasSideEffects :: PrimOp -> Bool
426 #include "primop-has-side-effects.hs-incl"
430 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
432 = case primOpInfo op of
433 Dyadic _occ ty -> dyadic_fun_ty ty
434 Monadic _occ ty -> monadic_fun_ty ty
435 Compare _occ ty -> compare_fun_ty ty
437 GenPrimOp _occ tyvars arg_tys res_ty ->
438 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
440 primOpOcc :: PrimOp -> OccName
441 primOpOcc op = case primOpInfo op of
445 GenPrimOp occ _ _ _ -> occ
447 -- primOpSig is like primOpType but gives the result split apart:
448 -- (type variables, argument types, result type)
449 -- It also gives arity, strictness info
451 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
453 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
455 arity = length arg_tys
456 (tyvars, arg_tys, res_ty)
457 = case (primOpInfo op) of
458 Monadic _occ ty -> ([], [ty], ty )
459 Dyadic _occ ty -> ([], [ty,ty], ty )
460 Compare _occ ty -> ([], [ty,ty], boolTy)
461 GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty)
465 data PrimOpResultInfo
466 = ReturnsPrim PrimRep
469 -- Some PrimOps need not return a manifest primitive or algebraic value
470 -- (i.e. they might return a polymorphic value). These PrimOps *must*
471 -- be out of line, or the code generator won't work.
473 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
474 getPrimOpResultInfo op
475 = case (primOpInfo op) of
476 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
477 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
478 Compare _ _ -> ReturnsAlg boolTyCon
479 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
480 | otherwise -> ReturnsAlg tc
482 tc = tyConAppTyCon ty
483 -- All primops return a tycon-app result
484 -- The tycon can be an unboxed tuple, though, which
485 -- gives rise to a ReturnAlg
488 The commutable ops are those for which we will try to move constants
489 to the right hand side for strength reduction.
492 commutableOp :: PrimOp -> Bool
493 #include "primop-commutable.hs-incl"
498 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
499 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
500 monadic_fun_ty ty = mkFunTy ty ty
501 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
506 pprPrimOp :: PrimOp -> SDoc
507 pprPrimOp other_op = pprOccName (primOpOcc other_op)
511 %************************************************************************
513 \subsubsection[PrimCall]{User-imported primitive calls}
515 %************************************************************************
518 data PrimCall = PrimCall CLabelString PackageId
520 instance Outputable PrimCall where
521 ppr (PrimCall lbl pkgId)
522 = text "__primcall" <+> ppr pkgId <+> ppr lbl