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