[project @ 2002-09-13 15:02:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / prelude / PrimOp.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[PrimOp]{Primitive operations (machine-level)}
5
6 \begin{code}
7 module PrimOp (
8         PrimOp(..), allThePrimOps,
9         primOpType, primOpSig, primOpArity,
10         mkPrimOpIdName, primOpTag, primOpOcc,
11
12         commutableOp,
13
14         primOpOutOfLine, primOpNeedsWrapper, 
15         primOpOkForSpeculation, primOpIsCheap, primOpIsDupable,
16         primOpHasSideEffects,
17
18         getPrimOpResultInfo,  PrimOpResultInfo(..),
19
20         eqCharName, eqIntName, neqIntName,
21         ltCharName, eqWordName, ltWordName, eqAddrName, ltAddrName,
22         eqFloatName, ltFloatName, eqDoubleName, ltDoubleName, 
23         ltIntName, geIntName, leIntName, minusIntName, tagToEnumName    
24     ) where
25
26 #include "HsVersions.h"
27
28 import PrimRep          -- most of it
29 import TysPrim
30 import TysWiredIn
31
32 import NewDemand
33 import Var              ( TyVar )
34 import Name             ( Name, mkWiredInName )
35 import OccName          ( OccName, pprOccName, mkVarOcc )
36 import TyCon            ( TyCon, isPrimTyCon, tyConPrimRep )
37 import Type             ( Type, mkForAllTys, mkFunTy, mkFunTys, typePrimRep, tyConAppTyCon )
38 import PprType          () -- get at Outputable Type instance.
39 import Unique           ( mkPrimOpIdUnique )
40 import BasicTypes       ( Arity, Boxity(..) )
41 import PrelNames        ( gHC_PRIM )
42 import Outputable
43 import FastTypes
44 \end{code}
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
49 %*                                                                      *
50 %************************************************************************
51
52 These are in \tr{state-interface.verb} order.
53
54 \begin{code}
55
56 -- supplies: 
57 -- data PrimOp = ...
58 #include "primop-data-decl.hs-incl"
59 \end{code}
60
61 Used for the Ord instance
62
63 \begin{code}
64 primOpTag :: PrimOp -> Int
65 primOpTag op = iBox (tagOf_PrimOp op)
66
67 -- supplies   
68 -- tagOf_PrimOp :: PrimOp -> FastInt
69 #include "primop-tag.hs-incl"
70 tagOf_PrimOp op = pprPanic# "tagOf_PrimOp: pattern-match" (ppr op)
71
72
73 instance Eq PrimOp where
74     op1 == op2 = tagOf_PrimOp op1 ==# tagOf_PrimOp op2
75
76 instance Ord PrimOp where
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 >  op2 =  tagOf_PrimOp op1 ># tagOf_PrimOp op2
81     op1 `compare` op2 | op1 < op2  = LT
82                       | op1 == op2 = EQ
83                       | otherwise  = GT
84
85 instance Outputable PrimOp where
86     ppr op = pprPrimOp op
87
88 instance Show PrimOp where
89     showsPrec p op = showsPrecSDoc p (pprPrimOp op)
90 \end{code}
91
92 An @Enum@-derived list would be better; meanwhile... (ToDo)
93 \begin{code}
94 allThePrimOps :: [PrimOp]
95 allThePrimOps =
96 #include "primop-list.hs-incl"
97 \end{code}
98
99 %************************************************************************
100 %*                                                                      *
101 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
102 %*                                                                      *
103 %************************************************************************
104
105 The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
106 refer to the primitive operation.  The conventional \tr{#}-for-
107 unboxed ops is added on later.
108
109 The reason for the funny characters in the names is so we do not
110 interfere with the programmer's Haskell name spaces.
111
112 We use @PrimKinds@ for the ``type'' information, because they're
113 (slightly) more convenient to use than @TyCons@.
114 \begin{code}
115 data PrimOpInfo
116   = Dyadic      OccName         -- string :: T -> T -> T
117                 Type
118   | Monadic     OccName         -- string :: T -> T
119                 Type
120   | Compare     OccName         -- string :: T -> T -> Bool
121                 Type
122
123   | GenPrimOp   OccName         -- string :: \/a1..an . T1 -> .. -> Tk -> T
124                 [TyVar] 
125                 [Type] 
126                 Type 
127
128 mkDyadic str  ty = Dyadic  (mkVarOcc str) ty
129 mkMonadic str ty = Monadic (mkVarOcc str) ty
130 mkCompare str ty = Compare (mkVarOcc str) ty
131 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOcc str) tvs tys ty
132 \end{code}
133
134 %************************************************************************
135 %*                                                                      *
136 \subsubsection{Strictness}
137 %*                                                                      *
138 %************************************************************************
139
140 Not all primops are strict!
141
142 \begin{code}
143 primOpStrictness :: PrimOp -> Arity -> StrictSig
144         -- See Demand.StrictnessInfo for discussion of what the results
145         -- The arity should be the arity of the primop; that's why
146         -- this function isn't exported.
147 #include "primop-strictness.hs-incl"
148 \end{code}
149
150 %************************************************************************
151 %*                                                                      *
152 \subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
153 %*                                                                      *
154 %************************************************************************
155
156 @primOpInfo@ gives all essential information (from which everything
157 else, notably a type, can be constructed) for each @PrimOp@.
158
159 \begin{code}
160 primOpInfo :: PrimOp -> PrimOpInfo
161 #include "primop-primop-info.hs-incl"
162 \end{code}
163
164 Here are a load of comments from the old primOp info:
165
166 A @Word#@ is an unsigned @Int#@.
167
168 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
169
170 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
171
172 Decoding of floating-point numbers is sorta Integer-related.  Encoding
173 is done with plain ccalls now (see PrelNumExtra.lhs).
174
175 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
176
177         mkWeak# :: k -> v -> f -> State# RealWorld 
178                         -> (# State# RealWorld, Weak# v #)
179
180 In practice, you'll use the higher-level
181
182         data Weak v = Weak# v
183         mkWeak :: k -> v -> IO () -> IO (Weak v)
184
185 The following operation dereferences a weak pointer.  The weak pointer
186 may have been finalized, so the operation returns a result code which
187 must be inspected before looking at the dereferenced value.
188
189         deRefWeak# :: Weak# v -> State# RealWorld ->
190                         (# State# RealWorld, v, Int# #)
191
192 Only look at v if the Int# returned is /= 0 !!
193
194 The higher-level op is
195
196         deRefWeak :: Weak v -> IO (Maybe v)
197
198 Weak pointers can be finalized early by using the finalize# operation:
199         
200         finalizeWeak# :: Weak# v -> State# RealWorld -> 
201                            (# State# RealWorld, Int#, IO () #)
202
203 The Int# returned is either
204
205         0 if the weak pointer has already been finalized, or it has no
206           finalizer (the third component is then invalid).
207
208         1 if the weak pointer is still alive, with the finalizer returned
209           as the third component.
210
211 A {\em stable name/pointer} is an index into a table of stable name
212 entries.  Since the garbage collector is told about stable pointers,
213 it is safe to pass a stable pointer to external systems such as C
214 routines.
215
216 \begin{verbatim}
217 makeStablePtr#  :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
218 freeStablePtr   :: StablePtr# a -> State# RealWorld -> State# RealWorld
219 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
220 eqStablePtr#    :: StablePtr# a -> StablePtr# a -> Int#
221 \end{verbatim}
222
223 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
224 operation since it doesn't (directly) involve IO operations.  The
225 reason is that if some optimisation pass decided to duplicate calls to
226 @makeStablePtr#@ and we only pass one of the stable pointers over, a
227 massive space leak can result.  Putting it into the IO monad
228 prevents this.  (Another reason for putting them in a monad is to
229 ensure correct sequencing wrt the side-effecting @freeStablePtr@
230 operation.)
231
232 An important property of stable pointers is that if you call
233 makeStablePtr# twice on the same object you get the same stable
234 pointer back.
235
236 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
237 besides, it's not likely to be used from Haskell) so it's not a
238 primop.
239
240 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
241
242 Stable Names
243 ~~~~~~~~~~~~
244
245 A stable name is like a stable pointer, but with three important differences:
246
247         (a) You can't deRef one to get back to the original object.
248         (b) You can convert one to an Int.
249         (c) You don't need to 'freeStableName'
250
251 The existence of a stable name doesn't guarantee to keep the object it
252 points to alive (unlike a stable pointer), hence (a).
253
254 Invariants:
255         
256         (a) makeStableName always returns the same value for a given
257             object (same as stable pointers).
258
259         (b) if two stable names are equal, it implies that the objects
260             from which they were created were the same.
261
262         (c) stableNameToInt always returns the same Int for a given
263             stable name.
264
265
266 -- HWL: The first 4 Int# in all par... annotations denote:
267 --   name, granularity info, size of result, degree of parallelism
268 --      Same  structure as _seq_ i.e. returns Int#
269 -- KSW: v, the second arg in parAt# and parAtForNow#, is used only to determine
270 --   `the processor containing the expression v'; it is not evaluated
271
272 These primops are pretty wierd.
273
274         dataToTag# :: a -> Int    (arg must be an evaluated data type)
275         tagToEnum# :: Int -> a    (result type must be an enumerated type)
276
277 The constraints aren't currently checked by the front end, but the
278 code generator will fall over if they aren't satisfied.
279
280 \begin{code}
281 #ifdef DEBUG
282 primOpInfo op = pprPanic "primOpInfo:" (ppr op)
283 #endif
284 \end{code}
285
286 %************************************************************************
287 %*                                                                      *
288 \subsubsection[PrimOp-ool]{Which PrimOps are out-of-line}
289 %*                                                                      *
290 %************************************************************************
291
292 Some PrimOps need to be called out-of-line because they either need to
293 perform a heap check or they block.
294
295
296 \begin{code}
297 primOpOutOfLine :: PrimOp -> Bool
298 #include "primop-out-of-line.hs-incl"
299 \end{code}
300
301
302 primOpOkForSpeculation
303 ~~~~~~~~~~~~~~~~~~~~~~
304 Sometimes we may choose to execute a PrimOp even though it isn't
305 certain that its result will be required; ie execute them
306 ``speculatively''.  The same thing as ``cheap eagerness.'' Usually
307 this is OK, because PrimOps are usually cheap, but it isn't OK for
308 (a)~expensive PrimOps and (b)~PrimOps which can fail.
309
310 PrimOps that have side effects also should not be executed speculatively.
311
312 Ok-for-speculation also means that it's ok *not* to execute the
313 primop. For example
314         case op a b of
315           r -> 3
316 Here the result is not used, so we can discard the primop.  Anything
317 that has side effects mustn't be dicarded in this way, of course!
318
319 See also @primOpIsCheap@ (below).
320
321
322 \begin{code}
323 primOpOkForSpeculation :: PrimOp -> Bool
324         -- See comments with CoreUtils.exprOkForSpeculation
325 primOpOkForSpeculation op 
326   = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op)
327 \end{code}
328
329
330 primOpIsCheap
331 ~~~~~~~~~~~~~
332 @primOpIsCheap@, as used in \tr{SimplUtils.lhs}.  For now (HACK
333 WARNING), we just borrow some other predicates for a
334 what-should-be-good-enough test.  "Cheap" means willing to call it more
335 than once.  Evaluation order is unaffected.
336
337 \begin{code}
338 primOpIsCheap :: PrimOp -> Bool
339 primOpIsCheap op = False
340         -- March 2001: be less eager to inline PrimOps
341         -- Was: not (primOpHasSideEffects op || primOpOutOfLine op)
342 \end{code}
343
344 primOpIsDupable
345 ~~~~~~~~~~~~~~~
346 primOpIsDupable means that the use of the primop is small enough to
347 duplicate into different case branches.  See CoreUtils.exprIsDupable.
348
349 \begin{code}
350 primOpIsDupable :: PrimOp -> Bool
351         -- See comments with CoreUtils.exprIsDupable
352         -- We say it's dupable it isn't implemented by a C call with a wrapper
353 primOpIsDupable op = not (primOpNeedsWrapper op)
354 \end{code}
355
356
357 \begin{code}
358 primOpCanFail :: PrimOp -> Bool
359 #include "primop-can-fail.hs-incl"
360 \end{code}
361
362 And some primops have side-effects and so, for example, must not be
363 duplicated.
364
365 \begin{code}
366 primOpHasSideEffects :: PrimOp -> Bool
367 #include "primop-has-side-effects.hs-incl"
368 \end{code}
369
370 Inline primitive operations that perform calls need wrappers to save
371 any live variables that are stored in caller-saves registers.
372
373 \begin{code}
374 primOpNeedsWrapper :: PrimOp -> Bool
375 #include "primop-needs-wrapper.hs-incl"
376 \end{code}
377
378 \begin{code}
379 primOpArity :: PrimOp -> Arity
380 primOpArity op 
381   = case (primOpInfo op) of
382       Monadic occ ty                      -> 1
383       Dyadic occ ty                       -> 2
384       Compare occ ty                      -> 2
385       GenPrimOp occ tyvars arg_tys res_ty -> length arg_tys
386                 
387 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
388 primOpType op
389   = case (primOpInfo op) of
390       Dyadic occ ty ->      dyadic_fun_ty ty
391       Monadic occ ty ->     monadic_fun_ty ty
392       Compare occ ty ->     compare_fun_ty ty
393
394       GenPrimOp occ tyvars arg_tys res_ty -> 
395         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
396
397 mkPrimOpIdName :: PrimOp -> Name
398         -- Make the name for the PrimOp's Id
399         -- We have to pass in the Id itself because it's a WiredInId
400         -- and hence recursive
401 mkPrimOpIdName op
402   = mkWiredInName gHC_PRIM (primOpOcc op) (mkPrimOpIdUnique (primOpTag op))
403
404 primOpOcc :: PrimOp -> OccName
405 primOpOcc op = case (primOpInfo op) of
406                               Dyadic    occ _     -> occ
407                               Monadic   occ _     -> occ
408                               Compare   occ _     -> occ
409                               GenPrimOp occ _ _ _ -> occ
410
411 -- primOpSig is like primOpType but gives the result split apart:
412 -- (type variables, argument types, result type)
413 -- It also gives arity, strictness info
414
415 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
416 primOpSig op
417   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
418   where
419     arity = length arg_tys
420     (tyvars, arg_tys, res_ty)
421       = case (primOpInfo op) of
422           Monadic   occ ty -> ([],     [ty],    ty    )
423           Dyadic    occ ty -> ([],     [ty,ty], ty    )
424           Compare   occ ty -> ([],     [ty,ty], boolTy)
425           GenPrimOp occ tyvars arg_tys res_ty
426                            -> (tyvars, arg_tys, res_ty)
427 \end{code}
428
429 \begin{code}
430 data PrimOpResultInfo
431   = ReturnsPrim     PrimRep
432   | ReturnsAlg      TyCon
433
434 -- Some PrimOps need not return a manifest primitive or algebraic value
435 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
436 -- be out of line, or the code generator won't work.
437
438 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
439 getPrimOpResultInfo op
440   = case (primOpInfo op) of
441       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
442       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
443       Compare _ ty                        -> ReturnsAlg boolTyCon
444       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
445                          | otherwise      -> ReturnsAlg tc
446                          where
447                            tc = tyConAppTyCon ty
448                         -- All primops return a tycon-app result
449                         -- The tycon can be an unboxed tuple, though, which
450                         -- gives rise to a ReturnAlg
451 \end{code}
452
453 The commutable ops are those for which we will try to move constants
454 to the right hand side for strength reduction.
455
456 \begin{code}
457 commutableOp :: PrimOp -> Bool
458 #include "primop-commutable.hs-incl"
459 \end{code}
460
461 Utils:
462 \begin{code}
463 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
464 monadic_fun_ty ty = mkFunTy  ty ty
465 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
466 \end{code}
467
468 Output stuff:
469 \begin{code}
470 pprPrimOp  :: PrimOp -> SDoc
471 pprPrimOp other_op = pprOccName (primOpOcc other_op)
472 \end{code}
473
474
475 %************************************************************************
476 %*                                                                      *
477         Names for some primops (for ndpFlatten/FlattenMonad.lhs)
478 %*                                                                      *
479 %************************************************************************
480
481 \begin{code}
482 eqIntName       = mkPrimOpIdName IntEqOp
483 ltIntName       = mkPrimOpIdName IntLtOp
484 geIntName       = mkPrimOpIdName IntGeOp
485 leIntName       = mkPrimOpIdName IntLeOp
486 neqIntName      = mkPrimOpIdName IntNeOp
487 minusIntName    = mkPrimOpIdName IntSubOp
488
489 eqCharName      = mkPrimOpIdName CharEqOp
490 ltCharName      = mkPrimOpIdName CharLtOp
491
492 eqFloatName     = mkPrimOpIdName FloatEqOp
493 ltFloatName     = mkPrimOpIdName FloatLtOp
494
495 eqDoubleName    = mkPrimOpIdName DoubleEqOp
496 ltDoubleName    = mkPrimOpIdName DoubleLtOp
497
498 eqWordName      = mkPrimOpIdName WordEqOp
499 ltWordName      = mkPrimOpIdName WordLtOp
500
501 eqAddrName      = mkPrimOpIdName AddrEqOp
502 ltAddrName      = mkPrimOpIdName AddrLtOp
503
504 tagToEnumName   = mkPrimOpIdName TagToEnumOp
505 \end{code}