Whitespace only in nativeGen/RegAlloc/Graph/TrivColorable.hs
[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, primOpCodeSize,
22         primOpOkForSpeculation, primOpIsCheap,
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 primOpCodeSize
367 ~~~~~~~~~~~~~~
368 Gives an indication of the code size of a primop, for the purposes of
369 calculating unfolding sizes; see CoreUnfold.sizeExpr.
370
371 \begin{code}
372 primOpCodeSize :: PrimOp -> Int
373 #include "primop-code-size.hs-incl"
374
375 primOpCodeSizeDefault :: Int
376 primOpCodeSizeDefault = 1
377   -- CoreUnfold.primOpSize already takes into account primOpOutOfLine
378   -- and adds some further costs for the args in that case.
379
380 primOpCodeSizeForeignCall :: Int
381 primOpCodeSizeForeignCall = 4
382 \end{code}
383
384 \begin{code}
385 primOpCanFail :: PrimOp -> Bool
386 #include "primop-can-fail.hs-incl"
387 \end{code}
388
389 And some primops have side-effects and so, for example, must not be
390 duplicated.
391
392 This predicate means a little more than just "modifies the state of
393 the world".  What it really means is "it cosumes the state on its
394 input".  To see what this means, consider
395
396  let
397      t = case readMutVar# v s0 of (# s1, x #) -> (S# s1, x)
398      y = case t of (s,x) -> x
399  in
400      ... y ... y ...
401
402 Now, this is part of an ST or IO thread, so we are guaranteed by
403 construction that the program uses the state in a single-threaded way.
404 Whenever the state resulting from the readMutVar# is demanded, the
405 readMutVar# will be performed, and it will be ordered correctly with
406 respect to other operations in the monad.
407
408 But there's another way this could go wrong: GHC can inline t into y,
409 and inline y.  Then although the original readMutVar# will still be
410 correctly ordered with respect to the other operations, there will be
411 one or more extra readMutVar#s performed later, possibly out-of-order.
412 This really happened; see #3207.
413
414 The property we need to capture about readMutVar# is that it consumes
415 the State# value on its input.  We must retain the linearity of the
416 State#.
417
418 Our fix for this is to declare any primop that must be used linearly
419 as having side-effects.  When primOpHasSideEffects is True,
420 primOpOkForSpeculation will be False, and hence primOpIsCheap will
421 also be False, and applications of the primop will never be
422 duplicated.
423
424 \begin{code}
425 primOpHasSideEffects :: PrimOp -> Bool
426 #include "primop-has-side-effects.hs-incl"
427 \end{code}
428
429 \begin{code}
430 primOpType :: PrimOp -> Type  -- you may want to use primOpSig instead
431 primOpType op
432   = case primOpInfo op of
433     Dyadic  _occ ty -> dyadic_fun_ty ty
434     Monadic _occ ty -> monadic_fun_ty ty
435     Compare _occ ty -> compare_fun_ty ty
436
437     GenPrimOp _occ tyvars arg_tys res_ty -> 
438         mkForAllTys tyvars (mkFunTys arg_tys res_ty)
439
440 primOpOcc :: PrimOp -> OccName
441 primOpOcc op = case primOpInfo op of
442                Dyadic    occ _     -> occ
443                Monadic   occ _     -> occ
444                Compare   occ _     -> occ
445                GenPrimOp occ _ _ _ -> occ
446
447 -- primOpSig is like primOpType but gives the result split apart:
448 -- (type variables, argument types, result type)
449 -- It also gives arity, strictness info
450
451 primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
452 primOpSig op
453   = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
454   where
455     arity = length arg_tys
456     (tyvars, arg_tys, res_ty)
457       = case (primOpInfo op) of
458         Monadic   _occ ty                    -> ([],     [ty],    ty    )
459         Dyadic    _occ ty                    -> ([],     [ty,ty], ty    )
460         Compare   _occ ty                    -> ([],     [ty,ty], boolTy)
461         GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty)
462 \end{code}
463
464 \begin{code}
465 data PrimOpResultInfo
466   = ReturnsPrim     PrimRep
467   | ReturnsAlg      TyCon
468
469 -- Some PrimOps need not return a manifest primitive or algebraic value
470 -- (i.e. they might return a polymorphic value).  These PrimOps *must*
471 -- be out of line, or the code generator won't work.
472
473 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
474 getPrimOpResultInfo op
475   = case (primOpInfo op) of
476       Dyadic  _ ty                        -> ReturnsPrim (typePrimRep ty)
477       Monadic _ ty                        -> ReturnsPrim (typePrimRep ty)
478       Compare _ _                         -> ReturnsAlg boolTyCon
479       GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
480                          | otherwise      -> ReturnsAlg tc
481                          where
482                            tc = tyConAppTyCon ty
483                         -- All primops return a tycon-app result
484                         -- The tycon can be an unboxed tuple, though, which
485                         -- gives rise to a ReturnAlg
486 \end{code}
487
488 The commutable ops are those for which we will try to move constants
489 to the right hand side for strength reduction.
490
491 \begin{code}
492 commutableOp :: PrimOp -> Bool
493 #include "primop-commutable.hs-incl"
494 \end{code}
495
496 Utils:
497 \begin{code}
498 dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
499 dyadic_fun_ty  ty = mkFunTys [ty, ty] ty
500 monadic_fun_ty ty = mkFunTy  ty ty
501 compare_fun_ty ty = mkFunTys [ty, ty] boolTy
502 \end{code}
503
504 Output stuff:
505 \begin{code}
506 pprPrimOp  :: PrimOp -> SDoc
507 pprPrimOp other_op = pprOccName (primOpOcc other_op)
508 \end{code}
509
510
511 %************************************************************************
512 %*                                                                      *
513 \subsubsection[PrimCall]{User-imported primitive calls}
514 %*                                                                      *
515 %************************************************************************
516
517 \begin{code}
518 data PrimCall = PrimCall CLabelString PackageId
519
520 instance Outputable PrimCall where
521   ppr (PrimCall lbl pkgId) 
522         = text "__primcall" <+> ppr pkgId <+> ppr lbl
523
524 \end{code}