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