2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[PrimOp]{Primitive operations (machine-level)}
8 PrimOp(..), allThePrimOps,
9 primOpType, primOpSig, primOpUsg, primOpArity,
10 mkPrimOpIdName, primOpRdrName, primOpTag, primOpOcc,
14 primOpOutOfLine, primOpNeedsWrapper,
15 primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
18 getPrimOpResultInfo, PrimOpResultInfo(..)
21 #include "HsVersions.h"
23 import PrimRep -- most of it
27 import Demand ( wwLazy, wwPrim, wwStrict, StrictnessInfo(..) )
29 import Name ( Name, mkWiredInName )
30 import RdrName ( RdrName, mkRdrOrig )
31 import OccName ( OccName, pprOccName, mkVarOcc )
32 import TyCon ( TyCon, isPrimTyCon, tyConPrimRep )
33 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, typePrimRep,
34 splitFunTy_maybe, tyConAppTyCon, splitTyConApp,
37 import Unique ( mkPrimOpIdUnique )
38 import BasicTypes ( Arity, Boxity(..) )
39 import PrelNames ( pREL_GHC, pREL_GHC_Name )
41 import Util ( zipWithEqual )
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"
69 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
72 instance Eq PrimOp where
73 op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
75 instance Ord PrimOp where
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 > op2 = tagOf_PrimOp op1 ># tagOf_PrimOp op2
80 op1 `compare` op2 | op1 < op2 = LT
84 instance Outputable PrimOp where
87 instance Show PrimOp where
88 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
91 An @Enum@-derived list would be better; meanwhile... (ToDo)
93 allThePrimOps :: [PrimOp]
95 #include "primop-list.hs-incl"
98 %************************************************************************
100 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
102 %************************************************************************
104 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
105 refer to the primitive operation. The conventional \tr{#}-for-
106 unboxed ops is added on later.
108 The reason for the funny characters in the names is so we do not
109 interfere with the programmer's Haskell name spaces.
111 We use @PrimKinds@ for the ``type'' information, because they're
112 (slightly) more convenient to use than @TyCons@.
115 = Dyadic OccName -- string :: T -> T -> T
117 | Monadic OccName -- string :: T -> T
119 | Compare OccName -- string :: T -> T -> Bool
122 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
127 mkDyadic str ty = Dyadic (mkVarOcc str) ty
128 mkMonadic str ty = Monadic (mkVarOcc str) ty
129 mkCompare str ty = Compare (mkVarOcc str) ty
130 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOcc str) tvs tys ty
133 %************************************************************************
135 \subsubsection{Strictness}
137 %************************************************************************
139 Not all primops are strict!
142 primOpStrictness :: PrimOp -> Arity -> StrictnessInfo
143 -- See Demand.StrictnessInfo for discussion of what the results
144 -- The arity should be the arity of the primop; that's why
145 -- this function isn't exported.
146 #include "primop-strictness.hs-incl"
149 %************************************************************************
151 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
153 %************************************************************************
155 @primOpInfo@ gives all essential information (from which everything
156 else, notably a type, can be constructed) for each @PrimOp@.
159 primOpInfo :: PrimOp -> PrimOpInfo
160 #include "primop-primop-info.hs-incl"
163 Here are a load of comments from the old primOp info:
165 A @Word#@ is an unsigned @Int#@.
167 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
169 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
171 Decoding of floating-point numbers is sorta Integer-related. Encoding
172 is done with plain ccalls now (see PrelNumExtra.lhs).
174 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
176 mkWeak# :: k -> v -> f -> State# RealWorld
177 -> (# State# RealWorld, Weak# v #)
179 In practice, you'll use the higher-level
181 data Weak v = Weak# v
182 mkWeak :: k -> v -> IO () -> IO (Weak v)
184 The following operation dereferences a weak pointer. The weak pointer
185 may have been finalized, so the operation returns a result code which
186 must be inspected before looking at the dereferenced value.
188 deRefWeak# :: Weak# v -> State# RealWorld ->
189 (# State# RealWorld, v, Int# #)
191 Only look at v if the Int# returned is /= 0 !!
193 The higher-level op is
195 deRefWeak :: Weak v -> IO (Maybe v)
197 Weak pointers can be finalized early by using the finalize# operation:
199 finalizeWeak# :: Weak# v -> State# RealWorld ->
200 (# State# RealWorld, Int#, IO () #)
202 The Int# returned is either
204 0 if the weak pointer has already been finalized, or it has no
205 finalizer (the third component is then invalid).
207 1 if the weak pointer is still alive, with the finalizer returned
208 as the third component.
210 A {\em stable name/pointer} is an index into a table of stable name
211 entries. Since the garbage collector is told about stable pointers,
212 it is safe to pass a stable pointer to external systems such as C
216 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
217 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
218 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
219 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
222 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
223 operation since it doesn't (directly) involve IO operations. The
224 reason is that if some optimisation pass decided to duplicate calls to
225 @makeStablePtr#@ and we only pass one of the stable pointers over, a
226 massive space leak can result. Putting it into the IO monad
227 prevents this. (Another reason for putting them in a monad is to
228 ensure correct sequencing wrt the side-effecting @freeStablePtr@
231 An important property of stable pointers is that if you call
232 makeStablePtr# twice on the same object you get the same stable
235 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
236 besides, it's not likely to be used from Haskell) so it's not a
239 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
244 A stable name is like a stable pointer, but with three important differences:
246 (a) You can't deRef one to get back to the original object.
247 (b) You can convert one to an Int.
248 (c) You don't need to 'freeStableName'
250 The existence of a stable name doesn't guarantee to keep the object it
251 points to alive (unlike a stable pointer), hence (a).
255 (a) makeStableName always returns the same value for a given
256 object (same as stable pointers).
258 (b) if two stable names are equal, it implies that the objects
259 from which they were created were the same.
261 (c) stableNameToInt always returns the same Int for a given
265 [Alastair Reid is to blame for this!]
267 These days, (Glasgow) Haskell seems to have a bit of everything from
268 other languages: strict operations, mutable variables, sequencing,
269 pointers, etc. About the only thing left is LISP's ability to test
270 for pointer equality. So, let's add it in!
273 reallyUnsafePtrEquality :: a -> a -> Int#
276 which tests any two closures (of the same type) to see if they're the
277 same. (Returns $0$ for @False@, $\neq 0$ for @True@ - to avoid
278 difficulties of trying to box up the result.)
280 NB This is {\em really unsafe\/} because even something as trivial as
281 a garbage collection might change the answer by removing indirections.
282 Still, no-one's forcing you to use it. If you're worried about little
283 things like loss of referential transparency, you might like to wrap
284 it all up in a monad-like thing as John O'Donnell and John Hughes did
285 for non-determinism (1989 (Fraserburgh) Glasgow FP Workshop
288 I'm thinking of using it to speed up a critical equality test in some
289 graphics stuff in a context where the possibility of saying that
290 denotationally equal things aren't isn't a problem (as long as it
291 doesn't happen too often.) ADR
293 To Will: Jim said this was already in, but I can't see it so I'm
294 adding it. Up to you whether you add it. (Note that this could have
295 been readily implemented using a @veryDangerousCCall@ before they were
299 -- HWL: The first 4 Int# in all par... annotations denote:
300 -- name, granularity info, size of result, degree of parallelism
301 -- Same structure as _seq_ i.e. returns Int#
302 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
303 -- `the processor containing the expression v'; it is not evaluated
305 These primops are pretty wierd.
307 dataToTag# :: a -> Int (arg must be an evaluated data type)
308 tagToEnum# :: Int -> a (result type must be an enumerated type)
310 The constraints aren't currently checked by the front end, but the
311 code generator will fall over if they aren't satisfied.
315 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
319 %************************************************************************
321 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
323 %************************************************************************
325 Some PrimOps need to be called out-of-line because they either need to
326 perform a heap check or they block.
330 primOpOutOfLine :: PrimOp -> Bool
331 #include "primop-out-of-line.hs-incl"
335 primOpOkForSpeculation
336 ~~~~~~~~~~~~~~~~~~~~~~
337 Sometimes we may choose to execute a PrimOp even though it isn't
338 certain that its result will be required; ie execute them
339 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
340 this is OK, because PrimOps are usually cheap, but it isn't OK for
341 (a)~expensive PrimOps and (b)~PrimOps which can fail.
343 PrimOps that have side effects also should not be executed speculatively.
345 Ok-for-speculation also means that it's ok *not* to execute the
349 Here the result is not used, so we can discard the primop. Anything
350 that has side effects mustn't be dicarded in this way, of course!
352 See also @primOpIsCheap@ (below).
356 primOpOkForSpeculation :: PrimOp -> Bool
357 -- See comments with CoreUtils.exprOkForSpeculation
358 primOpOkForSpeculation op
359 = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
365 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
366 WARNING), we just borrow some other predicates for a
367 what-should-be-good-enough test. "Cheap" means willing to call it more
368 than once. Evaluation order is unaffected.
371 primOpIsCheap :: PrimOp -> Bool
372 primOpIsCheap op = False
373 -- March 2001: be less eager to inline PrimOps
374 -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
379 primOpIsDupable means that the use of the primop is small enough to
380 duplicate into different case branches. See CoreUtils.exprIsDupable.
383 primOpIsDupable :: PrimOp -> Bool
384 -- See comments with CoreUtils.exprIsDupable
385 -- We say it's dupable it isn't implemented by a C call with a wrapper
386 primOpIsDupable op = not (primOpNeedsWrapper op)
391 primOpCanFail :: PrimOp -> Bool
392 #include "primop-can-fail.hs-incl"
395 And some primops have side-effects and so, for example, must not be
399 primOpHasSideEffects :: PrimOp -> Bool
400 #include "primop-has-side-effects.hs-incl"
403 Inline primitive operations that perform calls need wrappers to save
404 any live variables that are stored in caller-saves registers.
407 primOpNeedsWrapper :: PrimOp -> Bool
408 #include "primop-needs-wrapper.hs-incl"
412 primOpArity :: PrimOp -> Arity
414 = case (primOpInfo op) of
418 GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
420 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
422 = case (primOpInfo op) of
423 Dyadic occ ty -> dyadic_fun_ty ty
424 Monadic occ ty -> monadic_fun_ty ty
425 Compare occ ty -> compare_fun_ty ty
427 GenPrimOp occ tyvars arg_tys res_ty ->
428 mkForAllTys tyvars (mkFunTys arg_tys res_ty)
430 mkPrimOpIdName :: PrimOp -> Name
431 -- Make the name for the PrimOp's Id
432 -- We have to pass in the Id itself because it's a WiredInId
433 -- and hence recursive
435 = mkWiredInName pREL_GHC (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
437 primOpRdrName :: PrimOp -> RdrName
438 primOpRdrName op = mkRdrOrig pREL_GHC_Name (primOpOcc op)
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, StrictnessInfo)
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
462 -> (tyvars, arg_tys, res_ty)
464 -- primOpUsg is like primOpSig but the types it yields are the
465 -- appropriate sigma (i.e., usage-annotated) types,
466 -- as required by the UsageSP inference.
468 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
469 #include "primop-usage.hs-incl"
471 -- Things with no Haskell pointers inside: in actuality, usages are
472 -- irrelevant here (hence it doesn't matter that some of these
473 -- apparently permit duplication; since such arguments are never
474 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
475 -- except insofar as it propagates to infect other values that *are*
479 -- Helper bits & pieces for usage info.
481 mkZ = mkUTy usOnce -- pointed argument used zero
482 mkO = mkUTy usOnce -- pointed argument used once
483 mkM = mkUTy usMany -- pointed argument used multiply
484 mkP = mkUTy usOnce -- unpointed argument
485 mkR = mkUTy usMany -- unpointed result
488 = case primOpSig op of
489 (tyvars, arg_tys, res_ty, _, _)
490 -> (tyvars, map mkP arg_tys, mkR res_ty)
493 = case primOpSig op of
494 (tyvars, arg_tys, res_ty, _, _)
495 -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
498 = case splitFunTy_maybe ty of
499 Just (a,b) -> mkFunTy (f a) (g b)
500 Nothing -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
503 = case splitTyConApp ty of
504 (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
505 mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg" ($) fs tys)
509 data PrimOpResultInfo
510 = ReturnsPrim PrimRep
513 -- Some PrimOps need not return a manifest primitive or algebraic value
514 -- (i.e. they might return a polymorphic value). These PrimOps *must*
515 -- be out of line, or the code generator won't work.
517 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
518 getPrimOpResultInfo op
519 = case (primOpInfo op) of
520 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
521 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
522 Compare _ ty -> ReturnsAlg boolTyCon
523 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
524 | otherwise -> ReturnsAlg tc
526 tc = tyConAppTyCon ty
527 -- All primops return a tycon-app result
528 -- The tycon can be an unboxed tuple, though, which
529 -- gives rise to a ReturnAlg
532 The commutable ops are those for which we will try to move constants
533 to the right hand side for strength reduction.
536 commutableOp :: PrimOp -> Bool
537 #include "primop-commutable.hs-incl"
542 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
543 monadic_fun_ty ty = mkFunTy ty ty
544 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
549 pprPrimOp :: PrimOp -> SDoc
551 = getPprStyle $ \ sty ->
552 if ifaceStyle sty then -- For interfaces Print it qualified with PrelGHC.
553 ptext SLIT("PrelGHC.") <> pprOccName occ
557 occ = primOpOcc other_op