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