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