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