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