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(..),
22 CCall(..), CCallTarget(..), ccallMayGC, ccallIsCasm, pprCCallOp,
23 isDynamicTarget, dynamicTarget, setCCallUnique
26 #include "HsVersions.h"
28 import PrimRep -- most of it
32 import Demand ( wwLazy, wwPrim, wwStrict, StrictnessInfo(..) )
33 import Var ( TyVar, Id )
34 import CallConv ( CallConv, pprCallConv )
35 import Name ( Name, mkWiredInIdName )
36 import RdrName ( RdrName, mkRdrQual )
37 import OccName ( OccName, pprOccName, mkSrcVarOcc )
38 import TyCon ( TyCon, tyConArity )
39 import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, mkTyVarTys,
40 mkTyConApp, typePrimRep,
41 splitFunTy_maybe, splitAlgTyConApp_maybe, splitTyConApp_maybe,
44 import Unique ( Unique, mkPrimOpIdUnique )
45 import BasicTypes ( Arity, Boxity(..) )
46 import CStrings ( CLabelString, pprCLabelString )
47 import PrelNames ( pREL_GHC, pREL_GHC_Name )
49 import Util ( zipWithEqual )
50 import GlaExts ( Int(..), Int#, (==#) )
53 %************************************************************************
55 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
57 %************************************************************************
59 These are in \tr{state-interface.verb} order.
65 #include "primop-data-decl.hs-incl"
66 | CCallOp CCall -- and don't forget to add CCall
69 Used for the Ord instance
72 primOpTag :: PrimOp -> Int
73 primOpTag op = IBOX( tagOf_PrimOp op )
76 -- tagOf_PrimOp :: PrimOp -> FAST_INT
77 #include "primop-tag.hs-incl"
78 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
81 instance Eq PrimOp where
82 op1 == op2 = tagOf_PrimOp op1 _EQ_ tagOf_PrimOp op2
84 instance Ord PrimOp where
85 op1 < op2 = tagOf_PrimOp op1 _LT_ tagOf_PrimOp op2
86 op1 <= op2 = tagOf_PrimOp op1 _LE_ tagOf_PrimOp op2
87 op1 >= op2 = tagOf_PrimOp op1 _GE_ tagOf_PrimOp op2
88 op1 > op2 = tagOf_PrimOp op1 _GT_ tagOf_PrimOp op2
89 op1 `compare` op2 | op1 < op2 = LT
93 instance Outputable PrimOp where
96 instance Show PrimOp where
97 showsPrec p op = showsPrecSDoc p (pprPrimOp op)
100 An @Enum@-derived list would be better; meanwhile... (ToDo)
102 allThePrimOps :: [PrimOp]
104 #include "primop-list.hs-incl"
105 -- Doesn't include CCall, which is really a family of primops
108 %************************************************************************
110 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
112 %************************************************************************
114 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
115 refer to the primitive operation. The conventional \tr{#}-for-
116 unboxed ops is added on later.
118 The reason for the funny characters in the names is so we do not
119 interfere with the programmer's Haskell name spaces.
121 We use @PrimKinds@ for the ``type'' information, because they're
122 (slightly) more convenient to use than @TyCons@.
125 = Dyadic OccName -- string :: T -> T -> T
127 | Monadic OccName -- string :: T -> T
129 | Compare OccName -- string :: T -> T -> Bool
132 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
137 mkDyadic str ty = Dyadic (mkSrcVarOcc str) ty
138 mkMonadic str ty = Monadic (mkSrcVarOcc str) ty
139 mkCompare str ty = Compare (mkSrcVarOcc str) ty
140 mkGenPrimOp str tvs tys ty = GenPrimOp (mkSrcVarOcc str) tvs tys ty
143 %************************************************************************
145 \subsubsection{Strictness}
147 %************************************************************************
149 Not all primops are strict!
152 primOpStrictness :: PrimOp -> Arity -> StrictnessInfo
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 [Alastair Reid is to blame for this!]
277 These days, (Glasgow) Haskell seems to have a bit of everything from
278 other languages: strict operations, mutable variables, sequencing,
279 pointers, etc. About the only thing left is LISP's ability to test
280 for pointer equality. So, let's add it in!
283 reallyUnsafePtrEquality :: a -> a -> Int#
286 which tests any two closures (of the same type) to see if they're the
287 same. (Returns $0$ for @False@, $\neq 0$ for @True@ - to avoid
288 difficulties of trying to box up the result.)
290 NB This is {\em really unsafe\/} because even something as trivial as
291 a garbage collection might change the answer by removing indirections.
292 Still, no-one's forcing you to use it. If you're worried about little
293 things like loss of referential transparency, you might like to wrap
294 it all up in a monad-like thing as John O'Donnell and John Hughes did
295 for non-determinism (1989 (Fraserburgh) Glasgow FP Workshop
298 I'm thinking of using it to speed up a critical equality test in some
299 graphics stuff in a context where the possibility of saying that
300 denotationally equal things aren't isn't a problem (as long as it
301 doesn't happen too often.) ADR
303 To Will: Jim said this was already in, but I can't see it so I'm
304 adding it. Up to you whether you add it. (Note that this could have
305 been readily implemented using a @veryDangerousCCall@ before they were
309 -- HWL: The first 4 Int# in all par... annotations denote:
310 -- name, granularity info, size of result, degree of parallelism
311 -- Same structure as _seq_ i.e. returns Int#
312 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
313 -- `the processor containing the expression v'; it is not evaluated
315 These primops are pretty wierd.
317 dataToTag# :: a -> Int (arg must be an evaluated data type)
318 tagToEnum# :: Int -> a (result type must be an enumerated type)
320 The constraints aren't currently checked by the front end, but the
321 code generator will fall over if they aren't satisfied.
325 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
329 %************************************************************************
331 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
333 %************************************************************************
335 Some PrimOps need to be called out-of-line because they either need to
336 perform a heap check or they block.
339 primOpOutOfLine (CCallOp c_call) = ccallMayGC c_call
340 #include "primop-out-of-line.hs-incl"
344 primOpOkForSpeculation
345 ~~~~~~~~~~~~~~~~~~~~~~
346 Sometimes we may choose to execute a PrimOp even though it isn't
347 certain that its result will be required; ie execute them
348 ``speculatively''. The same thing as ``cheap eagerness.'' Usually
349 this is OK, because PrimOps are usually cheap, but it isn't OK for
350 (a)~expensive PrimOps and (b)~PrimOps which can fail.
352 PrimOps that have side effects also should not be executed speculatively.
354 Ok-for-speculation also means that it's ok *not* to execute the
358 Here the result is not used, so we can discard the primop. Anything
359 that has side effects mustn't be dicarded in this way, of course!
361 See also @primOpIsCheap@ (below).
365 primOpOkForSpeculation :: PrimOp -> Bool
366 -- See comments with CoreUtils.exprOkForSpeculation
367 primOpOkForSpeculation op
368 = primOpIsCheap op && not (primOpCanFail op)
374 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}. For now (HACK
375 WARNING), we just borrow some other predicates for a
376 what-should-be-good-enough test. "Cheap" means willing to call it more
377 than once. Evaluation order is unaffected.
380 primOpIsCheap :: PrimOp -> Bool
381 -- See comments with CoreUtils.exprOkForSpeculation
382 primOpIsCheap op = not (primOpHasSideEffects op || primOpOutOfLine op)
387 primOpIsDupable means that the use of the primop is small enough to
388 duplicate into different case branches. See CoreUtils.exprIsDupable.
391 primOpIsDupable :: PrimOp -> Bool
392 -- See comments with CoreUtils.exprIsDupable
393 -- We say it's dupable it isn't implemented by a C call with a wrapper
394 primOpIsDupable op = not (primOpNeedsWrapper op)
399 primOpCanFail :: PrimOp -> Bool
400 #include "primop-can-fail.hs-incl"
403 And some primops have side-effects and so, for example, must not be
407 primOpHasSideEffects :: PrimOp -> Bool
408 primOpHasSideEffects (CCallOp _) = True
409 #include "primop-has-side-effects.hs-incl"
412 Inline primitive operations that perform calls need wrappers to save
413 any live variables that are stored in caller-saves registers.
416 primOpNeedsWrapper :: PrimOp -> Bool
417 primOpNeedsWrapper (CCallOp _) = True
418 #include "primop-needs-wrapper.hs-incl"
422 primOpArity :: PrimOp -> Arity
424 = case (primOpInfo op) of
428 GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
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 mkPrimOpIdName :: PrimOp -> Id -> Name
441 -- Make the name for the PrimOp's Id
442 -- We have to pass in the Id itself because it's a WiredInId
443 -- and hence recursive
445 = mkWiredInIdName key pREL_GHC occ_name id
447 occ_name = primOpOcc op
448 key = mkPrimOpIdUnique (primOpTag op)
451 primOpRdrName :: PrimOp -> RdrName
452 primOpRdrName op = mkRdrQual pREL_GHC_Name (primOpOcc op)
454 primOpOcc :: PrimOp -> OccName
455 primOpOcc op = case (primOpInfo op) of
459 GenPrimOp occ _ _ _ -> occ
461 -- primOpSig is like primOpType but gives the result split apart:
462 -- (type variables, argument types, result type)
463 -- It also gives arity, strictness info
465 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictnessInfo)
467 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
469 arity = length arg_tys
470 (tyvars, arg_tys, res_ty)
471 = case (primOpInfo op) of
472 Monadic occ ty -> ([], [ty], ty )
473 Dyadic occ ty -> ([], [ty,ty], ty )
474 Compare occ ty -> ([], [ty,ty], boolTy)
475 GenPrimOp occ tyvars arg_tys res_ty
476 -> (tyvars, arg_tys, res_ty)
478 -- primOpUsg is like primOpSig but the types it yields are the
479 -- appropriate sigma (i.e., usage-annotated) types,
480 -- as required by the UsageSP inference.
482 primOpUsg :: PrimOp -> ([TyVar],[Type],Type)
483 primOpUsg p@(CCallOp _) = mangle p [] mkM
484 #include "primop-usage.hs-incl"
486 -- Things with no Haskell pointers inside: in actuality, usages are
487 -- irrelevant here (hence it doesn't matter that some of these
488 -- apparently permit duplication; since such arguments are never
489 -- ENTERed anyway, the usage annotation they get is entirely irrelevant
490 -- except insofar as it propagates to infect other values that *are*
494 -- Helper bits & pieces for usage info.
496 mkZ = mkUsgTy UsOnce -- pointed argument used zero
497 mkO = mkUsgTy UsOnce -- pointed argument used once
498 mkM = mkUsgTy UsMany -- pointed argument used multiply
499 mkP = mkUsgTy UsOnce -- unpointed argument
500 mkR = mkUsgTy UsMany -- unpointed result
503 = case primOpSig op of
504 (tyvars, arg_tys, res_ty, _, _)
505 -> (tyvars, map mkP arg_tys, mkR res_ty)
508 = case primOpSig op of
509 (tyvars, arg_tys, res_ty, _, _)
510 -> (tyvars, zipWithEqual "primOpUsg" ($) fs arg_tys, g res_ty)
513 = case splitFunTy_maybe ty of
514 Just (a,b) -> mkFunTy (f a) (g b)
515 Nothing -> pprPanic "primOpUsg:inFun" (ppr op <+> ppr ty)
518 = case splitTyConApp_maybe ty of
519 Just (tc,tys) -> ASSERT( tc == tupleTyCon Unboxed (length fs) )
520 mkTupleTy Unboxed (length fs) (zipWithEqual "primOpUsg"
522 Nothing -> pprPanic "primOpUsg:inUB" (ppr op <+> ppr ty)
526 data PrimOpResultInfo
527 = ReturnsPrim PrimRep
530 -- Some PrimOps need not return a manifest primitive or algebraic value
531 -- (i.e. they might return a polymorphic value). These PrimOps *must*
532 -- be out of line, or the code generator won't work.
534 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
535 getPrimOpResultInfo (CCallOp _)
536 = ReturnsAlg unboxedPairTyCon
537 getPrimOpResultInfo op
538 = case (primOpInfo op) of
539 Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
540 Monadic _ ty -> ReturnsPrim (typePrimRep ty)
541 Compare _ ty -> ReturnsAlg boolTyCon
542 GenPrimOp _ _ _ ty ->
543 let rep = typePrimRep ty in
545 PtrRep -> case splitAlgTyConApp_maybe ty of
546 Nothing -> panic "getPrimOpResultInfo"
547 Just (tc,_,_) -> ReturnsAlg tc
548 other -> ReturnsPrim other
551 The commutable ops are those for which we will try to move constants
552 to the right hand side for strength reduction.
555 commutableOp :: PrimOp -> Bool
556 #include "primop-commutable.hs-incl"
561 mkPrimTyApp :: [TyVar] -> PrimRep -> ([TyVar], Type)
562 -- CharRep --> ([], Char#)
563 -- StablePtrRep --> ([a], StablePtr# a)
565 = (forall_tvs, mkTyConApp tycon (mkTyVarTys forall_tvs))
567 tycon = primRepTyCon kind
568 forall_tvs = take (tyConArity tycon) tvs
570 dyadic_fun_ty ty = mkFunTys [ty, ty] ty
571 monadic_fun_ty ty = mkFunTy ty ty
572 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
577 pprPrimOp :: PrimOp -> SDoc
579 pprPrimOp (CCallOp c_call) = pprCCallOp c_call
581 = getPprStyle $ \ sty ->
582 if ifaceStyle sty then -- For interfaces Print it qualified with PrelGHC.
583 ptext SLIT("PrelGHC.") <> pprOccName occ
587 occ = primOpOcc other_op
591 %************************************************************************
593 \subsubsection{CCalls}
595 %************************************************************************
597 A special ``trap-door'' to use in making calls direct to C functions:
601 Bool -- True <=> really a "casm"
602 Bool -- True <=> might invoke Haskell GC
603 CallConv -- calling convention to use.
607 = StaticTarget CLabelString -- An "unboxed" ccall# to `fn'.
608 | DynamicTarget Unique -- First argument (an Addr#) is the function pointer
609 -- (unique is used to generate a 'typedef' to cast
610 -- the function pointer if compiling the ccall# down to
611 -- .hc code - can't do this inline for tedious reasons.)
613 instance Eq CCallTarget where
614 (StaticTarget l1) == (StaticTarget l2) = l1 == l2
615 (DynamicTarget _) == (DynamicTarget _) = True
616 -- Ignore the arbitrary unique; this is important when comparing
617 -- a dynamic ccall read from an interface file A.hi with the
618 -- one constructed from A.hs, when deciding whether the interface
622 ccallMayGC :: CCall -> Bool
623 ccallMayGC (CCall _ _ may_gc _) = may_gc
625 ccallIsCasm :: CCall -> Bool
626 ccallIsCasm (CCall _ c_asm _ _) = c_asm
628 isDynamicTarget (DynamicTarget _) = True
629 isDynamicTarget (StaticTarget _) = False
631 dynamicTarget :: CCallTarget
632 dynamicTarget = DynamicTarget (panic "Unique in DynamicTarget not yet set")
633 -- The unique is really only to do with code generation, so it
634 -- is only set in CoreToStg; before then it's just an error message
636 setCCallUnique :: CCall -> Unique -> CCall
637 setCCallUnique (CCall (DynamicTarget _) is_asm may_gc cconv) uniq
638 = CCall (DynamicTarget uniq) is_asm may_gc cconv
639 setCCallUnique ccall uniq = ccall
643 pprCCallOp (CCall fun is_casm may_gc cconv)
644 = hcat [ ifPprDebug callconv
646 , text before , ppr_fun , after]
648 callconv = text "{-" <> pprCallConv cconv <> text "-}"
651 | is_casm && may_gc = "casm_GC ``"
652 | is_casm = "casm ``"
653 | may_gc = "ccall_GC "
654 | otherwise = "ccall "
657 | is_casm = text "''"
660 ppr_dyn = case fun of
661 DynamicTarget _ -> text "dyn_"
664 ppr_fun = case fun of
665 DynamicTarget _ -> text "\"\""
666 StaticTarget fn -> pprCLabelString fn