never executed always true always false
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4 \section[PrimOp]{Primitive operations (machine-level)}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module GHC.Builtin.PrimOps (
10 PrimOp(..), PrimOpVecCat(..), allThePrimOps,
11 primOpType, primOpSig, primOpResultType,
12 primOpTag, maxPrimOpTag, primOpOcc,
13 primOpWrapperId,
14
15 tagToEnumKey,
16
17 primOpOutOfLine, primOpCodeSize,
18 primOpOkForSpeculation, primOpOkForSideEffects,
19 primOpIsCheap, primOpFixity, primOpDocs,
20 primOpIsDiv,
21
22 getPrimOpResultInfo, isComparisonPrimOp, PrimOpResultInfo(..),
23
24 PrimCall(..)
25 ) where
26
27 import GHC.Prelude
28
29 import GHC.Builtin.Types.Prim
30 import GHC.Builtin.Types
31
32 import GHC.Cmm.Type
33 import GHC.Types.Demand
34 import GHC.Types.Id ( Id, mkVanillaGlobalWithInfo )
35 import GHC.Types.Id.Info ( vanillaIdInfo, setCafInfo, CafInfo(NoCafRefs) )
36 import GHC.Types.Name
37 import GHC.Builtin.Names ( gHC_PRIMOPWRAPPERS )
38 import GHC.Core.TyCon ( TyCon, isPrimTyCon, PrimRep(..) )
39 import GHC.Core.Type
40 import GHC.Types.RepType ( tyConPrimRep1 )
41 import GHC.Types.Basic ( Arity )
42 import GHC.Types.Fixity ( Fixity(..), FixityDirection(..) )
43 import GHC.Types.SrcLoc ( wiredInSrcSpan )
44 import GHC.Types.ForeignCall ( CLabelString )
45 import GHC.Types.SourceText ( SourceText(..) )
46 import GHC.Types.Unique ( Unique)
47 import GHC.Builtin.Uniques (mkPrimOpIdUnique, mkPrimOpWrapperUnique )
48 import GHC.Unit.Types ( Unit )
49 import GHC.Utils.Outputable
50 import GHC.Data.FastString
51
52 {-
53 ************************************************************************
54 * *
55 \subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
56 * *
57 ************************************************************************
58
59 These are in \tr{state-interface.verb} order.
60 -}
61
62 -- supplies:
63 -- data PrimOp = ...
64 #include "primop-data-decl.hs-incl"
65
66 -- supplies
67 -- primOpTag :: PrimOp -> Int
68 #include "primop-tag.hs-incl"
69 primOpTag _ = error "primOpTag: unknown primop"
70
71
72 instance Eq PrimOp where
73 op1 == op2 = primOpTag op1 == primOpTag op2
74
75 instance Ord PrimOp where
76 op1 < op2 = primOpTag op1 < primOpTag op2
77 op1 <= op2 = primOpTag op1 <= primOpTag op2
78 op1 >= op2 = primOpTag op1 >= primOpTag op2
79 op1 > op2 = primOpTag op1 > primOpTag 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 data PrimOpVecCat = IntVec
88 | WordVec
89 | FloatVec
90
91 -- An @Enum@-derived list would be better; meanwhile... (ToDo)
92
93 allThePrimOps :: [PrimOp]
94 allThePrimOps =
95 #include "primop-list.hs-incl"
96
97 tagToEnumKey :: Unique
98 tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
99
100 {-
101 ************************************************************************
102 * *
103 \subsection[PrimOp-info]{The essential info about each @PrimOp@}
104 * *
105 ************************************************************************
106 -}
107
108 data PrimOpInfo
109 = Compare OccName -- string :: T -> T -> Int#
110 Type
111 | GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
112 [TyVarBinder]
113 [Type]
114 Type
115
116 mkCompare :: FastString -> Type -> PrimOpInfo
117 mkCompare str ty = Compare (mkVarOccFS str) ty
118
119 mkGenPrimOp :: FastString -> [TyVarBinder] -> [Type] -> Type -> PrimOpInfo
120 mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
121
122 {-
123 ************************************************************************
124 * *
125 \subsubsection{Strictness}
126 * *
127 ************************************************************************
128
129 Not all primops are strict!
130 -}
131
132 primOpStrictness :: PrimOp -> Arity -> DmdSig
133 -- See Demand.DmdSig for discussion of what the results
134 -- The arity should be the arity of the primop; that's why
135 -- this function isn't exported.
136 #include "primop-strictness.hs-incl"
137
138 {-
139 ************************************************************************
140 * *
141 \subsubsection{Fixity}
142 * *
143 ************************************************************************
144 -}
145
146 primOpFixity :: PrimOp -> Maybe Fixity
147 #include "primop-fixity.hs-incl"
148
149 {-
150 ************************************************************************
151 * *
152 \subsubsection{Docs}
153 * *
154 ************************************************************************
155
156 See Note [GHC.Prim Docs]
157 -}
158
159 primOpDocs :: [(String, String)]
160 #include "primop-docs.hs-incl"
161
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
173 primOpInfo :: PrimOp -> PrimOpInfo
174 #include "primop-primop-info.hs-incl"
175 primOpInfo _ = error "primOpInfo: unknown primop"
176
177 {-
178 Here are a load of comments from the old primOp info:
179
180 A @Word#@ is an unsigned @Int#@.
181
182 @decodeFloat#@ is given w/ Integer-stuff (it's similar).
183
184 @decodeDouble#@ is given w/ Integer-stuff (it's similar).
185
186 Decoding of floating-point numbers is sorta Integer-related. Encoding
187 is done with plain ccalls now (see PrelNumExtra.hs).
188
189 A @Weak@ Pointer is created by the @mkWeak#@ primitive:
190
191 mkWeak# :: k -> v -> f -> State# RealWorld
192 -> (# State# RealWorld, Weak# v #)
193
194 In practice, you'll use the higher-level
195
196 data Weak v = Weak# v
197 mkWeak :: k -> v -> IO () -> IO (Weak v)
198
199 The following operation dereferences a weak pointer. The weak pointer
200 may have been finalized, so the operation returns a result code which
201 must be inspected before looking at the dereferenced value.
202
203 deRefWeak# :: Weak# v -> State# RealWorld ->
204 (# State# RealWorld, v, Int# #)
205
206 Only look at v if the Int# returned is /= 0 !!
207
208 The higher-level op is
209
210 deRefWeak :: Weak v -> IO (Maybe v)
211
212 Weak pointers can be finalized early by using the finalize# operation:
213
214 finalizeWeak# :: Weak# v -> State# RealWorld ->
215 (# State# RealWorld, Int#, IO () #)
216
217 The Int# returned is either
218
219 0 if the weak pointer has already been finalized, or it has no
220 finalizer (the third component is then invalid).
221
222 1 if the weak pointer is still alive, with the finalizer returned
223 as the third component.
224
225 A {\em stable name/pointer} is an index into a table of stable name
226 entries. Since the garbage collector is told about stable pointers,
227 it is safe to pass a stable pointer to external systems such as C
228 routines.
229
230 \begin{verbatim}
231 makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
232 freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
233 deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
234 eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
235 \end{verbatim}
236
237 It may seem a bit surprising that @makeStablePtr#@ is a @IO@
238 operation since it doesn't (directly) involve IO operations. The
239 reason is that if some optimisation pass decided to duplicate calls to
240 @makeStablePtr#@ and we only pass one of the stable pointers over, a
241 massive space leak can result. Putting it into the IO monad
242 prevents this. (Another reason for putting them in a monad is to
243 ensure correct sequencing wrt the side-effecting @freeStablePtr@
244 operation.)
245
246 An important property of stable pointers is that if you call
247 makeStablePtr# twice on the same object you get the same stable
248 pointer back.
249
250 Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
251 besides, it's not likely to be used from Haskell) so it's not a
252 primop.
253
254 Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
255
256 Stable Names
257 ~~~~~~~~~~~~
258
259 A stable name is like a stable pointer, but with three important differences:
260
261 (a) You can't deRef one to get back to the original object.
262 (b) You can convert one to an Int.
263 (c) You don't need to 'freeStableName'
264
265 The existence of a stable name doesn't guarantee to keep the object it
266 points to alive (unlike a stable pointer), hence (a).
267
268 Invariants:
269
270 (a) makeStableName always returns the same value for a given
271 object (same as stable pointers).
272
273 (b) if two stable names are equal, it implies that the objects
274 from which they were created were the same.
275
276 (c) stableNameToInt always returns the same Int for a given
277 stable name.
278
279
280 These primops are pretty weird.
281
282 tagToEnum# :: Int -> a (result type must be an enumerated type)
283
284 The constraints aren't currently checked by the front end, but the
285 code generator will fall over if they aren't satisfied.
286
287 ************************************************************************
288 * *
289 Which PrimOps are out-of-line
290 * *
291 ************************************************************************
292
293 Some PrimOps need to be called out-of-line because they either need to
294 perform a heap check or they block.
295 -}
296
297 primOpOutOfLine :: PrimOp -> Bool
298 #include "primop-out-of-line.hs-incl"
299
300 {-
301 ************************************************************************
302 * *
303 Failure and side effects
304 * *
305 ************************************************************************
306
307 Note [Checking versus non-checking primops]
308 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
309
310 In GHC primops break down into two classes:
311
312 a. Checking primops behave, for instance, like division. In this
313 case the primop may throw an exception (e.g. division-by-zero)
314 and is consequently is marked with the can_fail flag described below.
315 The ability to fail comes at the expense of precluding some optimizations.
316
317 b. Non-checking primops behavior, for instance, like addition. While
318 addition can overflow it does not produce an exception. So can_fail is
319 set to False, and we get more optimisation opportunities. But we must
320 never throw an exception, so we cannot rewrite to a call to error.
321
322 It is important that a non-checking primop never be transformed in a way that
323 would cause it to bottom. Doing so would violate Core's let/app invariant
324 (see Note [Core let/app invariant] in GHC.Core) which is critical to
325 the simplifier's ability to float without fear of changing program meaning.
326
327
328 Note [PrimOp can_fail and has_side_effects]
329 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
330 Both can_fail and has_side_effects mean that the primop has
331 some effect that is not captured entirely by its result value.
332
333 ---------- has_side_effects ---------------------
334 A primop "has_side_effects" if it has some side effect, visible
335 elsewhere, apart from the result it returns
336 - reading or writing to the world (I/O)
337 - reading or writing to a mutable data structure (writeIORef)
338 - throwing a synchronous Haskell exception
339
340 Often such primops have a type like
341 State -> input -> (State, output)
342 so the state token guarantees ordering. In general we rely on
343 data dependencies of the state token to enforce write-effect ordering,
344 but as the notes below make clear, the matter is a bit more complicated
345 than that.
346
347 * NB1: if you inline unsafePerformIO, you may end up with
348 side-effecting ops whose 'state' output is discarded.
349 And programmers may do that by hand; see #9390.
350 That is why we (conservatively) do not discard write-effecting
351 primops even if both their state and result is discarded.
352
353 * NB2: We consider primops, such as raiseIO#, that can raise a
354 (Haskell) synchronous exception to "have_side_effects" but not
355 "can_fail". We must be careful about not discarding such things;
356 see the paper "A semantics for imprecise exceptions".
357
358 * NB3: *Read* effects on *mutable* cells (like reading an IORef or a
359 MutableArray#) /are/ included. You may find this surprising because it
360 doesn't matter if we don't do them, or do them more than once. *Sequencing*
361 is maintained by the data dependency of the state token. But see
362 "Duplication" below under
363 Note [Transformations affected by can_fail and has_side_effects]
364
365 Note that read operations on *immutable* values (like indexArray#) do not
366 have has_side_effects. (They might be marked can_fail, however, because
367 you might index out of bounds.)
368
369 Using has_side_effects in this way is a bit of a blunt instrument. We could
370 be more refined by splitting read and write effects (see comments with #3207
371 and #20195)
372
373 ---------- can_fail ----------------------------
374 A primop "can_fail" if it can fail with an *unchecked* exception on
375 some elements of its input domain. Main examples:
376 division (fails on zero denominator)
377 array indexing (fails if the index is out of bounds)
378
379 An "unchecked exception" is one that is an outright error, (not
380 turned into a Haskell exception,) such as seg-fault or
381 divide-by-zero error. Such can_fail primops are ALWAYS surrounded
382 with a test that checks for the bad cases, but we need to be
383 very careful about code motion that might move it out of
384 the scope of the test.
385
386 Note [Transformations affected by can_fail and has_side_effects]
387 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
388 The can_fail and has_side_effects properties have the following effect
389 on program transformations. Summary table is followed by details.
390
391 can_fail has_side_effects
392 Discard YES NO
393 Float in YES YES
394 Float out NO NO
395 Duplicate YES NO
396
397 * Discarding. case (a `op` b) of _ -> rhs ===> rhs
398 You should not discard a has_side_effects primop; e.g.
399 case (writeIntArray# a i v s of (# _, _ #) -> True
400 Arguably you should be able to discard this, since the
401 returned stat token is not used, but that relies on NEVER
402 inlining unsafePerformIO, and programmers sometimes write
403 this kind of stuff by hand (#9390). So we (conservatively)
404 never discard a has_side_effects primop.
405
406 However, it's fine to discard a can_fail primop. For example
407 case (indexIntArray# a i) of _ -> True
408 We can discard indexIntArray#; it has can_fail, but not
409 has_side_effects; see #5658 which was all about this.
410 Notice that indexIntArray# is (in a more general handling of
411 effects) read effect, but we don't care about that here, and
412 treat read effects as *not* has_side_effects.
413
414 Similarly (a `/#` b) can be discarded. It can seg-fault or
415 cause a hardware exception, but not a synchronous Haskell
416 exception.
417
418
419
420 Synchronous Haskell exceptions, e.g. from raiseIO#, are treated
421 as has_side_effects and hence are not discarded.
422
423 * Float in. You can float a can_fail or has_side_effects primop
424 *inwards*, but not inside a lambda (see Duplication below).
425
426 * Float out. You must not float a can_fail primop *outwards* lest
427 you escape the dynamic scope of the test. Example:
428 case d ># 0# of
429 True -> case x /# d of r -> r +# 1
430 False -> 0
431 Here we must not float the case outwards to give
432 case x/# d of r ->
433 case d ># 0# of
434 True -> r +# 1
435 False -> 0
436
437 Nor can you float out a has_side_effects primop. For example:
438 if blah then case writeMutVar# v True s0 of (# s1 #) -> s1
439 else s0
440 Notice that s0 is mentioned in both branches of the 'if', but
441 only one of these two will actually be consumed. But if we
442 float out to
443 case writeMutVar# v True s0 of (# s1 #) ->
444 if blah then s1 else s0
445 the writeMutVar will be performed in both branches, which is
446 utterly wrong.
447
448 * Duplication. You cannot duplicate a has_side_effect primop. You
449 might wonder how this can occur given the state token threading, but
450 just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get
451 something like this
452 p = case readMutVar# s v of
453 (# s', r #) -> (State# s', r)
454 s' = case p of (s', r) -> s'
455 r = case p of (s', r) -> r
456
457 (All these bindings are boxed.) If we inline p at its two call
458 sites, we get a catastrophe: because the read is performed once when
459 s' is demanded, and once when 'r' is demanded, which may be much
460 later. Utterly wrong. #3207 is real example of this happening.
461
462 However, it's fine to duplicate a can_fail primop. That is really
463 the only difference between can_fail and has_side_effects.
464
465 Note [Implementation: how can_fail/has_side_effects affect transformations]
466 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
467 How do we ensure that floating/duplication/discarding are done right
468 in the simplifier?
469
470 Two main predicates on primpops test these flags:
471 primOpOkForSideEffects <=> not has_side_effects
472 primOpOkForSpeculation <=> not (has_side_effects || can_fail)
473
474 * The "no-float-out" thing is achieved by ensuring that we never
475 let-bind a can_fail or has_side_effects primop. The RHS of a
476 let-binding (which can float in and out freely) satisfies
477 exprOkForSpeculation; this is the let/app invariant. And
478 exprOkForSpeculation is false of can_fail and has_side_effects.
479
480 * So can_fail and has_side_effects primops will appear only as the
481 scrutinees of cases, and that's why the FloatIn pass is capable
482 of floating case bindings inwards.
483
484 * The no-duplicate thing is done via primOpIsCheap, by making
485 has_side_effects things (very very very) not-cheap!
486 -}
487
488 primOpHasSideEffects :: PrimOp -> Bool
489 #include "primop-has-side-effects.hs-incl"
490
491 primOpCanFail :: PrimOp -> Bool
492 #include "primop-can-fail.hs-incl"
493
494 primOpOkForSpeculation :: PrimOp -> Bool
495 -- See Note [PrimOp can_fail and has_side_effects]
496 -- See comments with GHC.Core.Utils.exprOkForSpeculation
497 -- primOpOkForSpeculation => primOpOkForSideEffects
498 primOpOkForSpeculation op
499 = primOpOkForSideEffects op
500 && not (primOpOutOfLine op || primOpCanFail op)
501 -- I think the "out of line" test is because out of line things can
502 -- be expensive (eg sine, cosine), and so we may not want to speculate them
503
504 primOpOkForSideEffects :: PrimOp -> Bool
505 primOpOkForSideEffects op
506 = not (primOpHasSideEffects op)
507
508 {-
509 Note [primOpIsCheap]
510 ~~~~~~~~~~~~~~~~~~~~
511
512 @primOpIsCheap@, as used in GHC.Core.Opt.Simplify.Utils. For now (HACK
513 WARNING), we just borrow some other predicates for a
514 what-should-be-good-enough test. "Cheap" means willing to call it more
515 than once, and/or push it inside a lambda. The latter could change the
516 behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
517 -}
518
519 primOpIsCheap :: PrimOp -> Bool
520 -- See Note [PrimOp can_fail and has_side_effects]
521 primOpIsCheap op = primOpOkForSpeculation op
522 -- In March 2001, we changed this to
523 -- primOpIsCheap op = False
524 -- thereby making *no* primops seem cheap. But this killed eta
525 -- expansion on case (x ==# y) of True -> \s -> ...
526 -- which is bad. In particular a loop like
527 -- doLoop n = loop 0
528 -- where
529 -- loop i | i == n = return ()
530 -- | otherwise = bar i >> loop (i+1)
531 -- allocated a closure every time round because it doesn't eta expand.
532 --
533 -- The problem that originally gave rise to the change was
534 -- let x = a +# b *# c in x +# x
535 -- were we don't want to inline x. But primopIsCheap doesn't control
536 -- that (it's exprIsDupable that does) so the problem doesn't occur
537 -- even if primOpIsCheap sometimes says 'True'.
538
539
540 -- | True of dyadic operators that can fail only if the second arg is zero!
541 --
542 -- This function probably belongs in an automagically generated file.. but it's
543 -- such a special case I thought I'd leave it here for now.
544 primOpIsDiv :: PrimOp -> Bool
545 primOpIsDiv op = case op of
546
547 -- TODO: quotRemWord2, Int64, Word64
548 IntQuotOp -> True
549 Int8QuotOp -> True
550 Int16QuotOp -> True
551 Int32QuotOp -> True
552
553 IntRemOp -> True
554 Int8RemOp -> True
555 Int16RemOp -> True
556 Int32RemOp -> True
557
558 IntQuotRemOp -> True
559 Int8QuotRemOp -> True
560 Int16QuotRemOp -> True
561 Int32QuotRemOp -> True
562
563 WordQuotOp -> True
564 Word8QuotOp -> True
565 Word16QuotOp -> True
566 Word32QuotOp -> True
567
568 WordRemOp -> True
569 Word8RemOp -> True
570 Word16RemOp -> True
571 Word32RemOp -> True
572
573 WordQuotRemOp -> True
574 Word8QuotRemOp -> True
575 Word16QuotRemOp -> True
576 Word32QuotRemOp -> True
577
578 FloatDivOp -> True
579 DoubleDivOp -> True
580 _ -> False
581
582
583
584 {-
585 ************************************************************************
586 * *
587 PrimOp code size
588 * *
589 ************************************************************************
590
591 primOpCodeSize
592 ~~~~~~~~~~~~~~
593 Gives an indication of the code size of a primop, for the purposes of
594 calculating unfolding sizes; see GHC.Core.Unfold.sizeExpr.
595 -}
596
597 primOpCodeSize :: PrimOp -> Int
598 #include "primop-code-size.hs-incl"
599
600 primOpCodeSizeDefault :: Int
601 primOpCodeSizeDefault = 1
602 -- GHC.Core.Unfold.primOpSize already takes into account primOpOutOfLine
603 -- and adds some further costs for the args in that case.
604
605 primOpCodeSizeForeignCall :: Int
606 primOpCodeSizeForeignCall = 4
607
608 {-
609 ************************************************************************
610 * *
611 PrimOp types
612 * *
613 ************************************************************************
614 -}
615
616 primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
617 primOpType op
618 = case primOpInfo op of
619 Compare _occ ty -> compare_fun_ty ty
620
621 GenPrimOp _occ tyvars arg_tys res_ty ->
622 mkForAllTys tyvars (mkVisFunTysMany arg_tys res_ty)
623
624 primOpResultType :: PrimOp -> Type
625 primOpResultType op
626 = case primOpInfo op of
627 Compare _occ _ty -> intPrimTy
628 GenPrimOp _occ _tyvars _arg_tys res_ty -> res_ty
629
630 primOpOcc :: PrimOp -> OccName
631 primOpOcc op = case primOpInfo op of
632 Compare occ _ -> occ
633 GenPrimOp occ _ _ _ -> occ
634
635 {- Note [Primop wrappers]
636 ~~~~~~~~~~~~~~~~~~~~~~~~~
637
638 To support (limited) use of primops in GHCi genprimopcode generates the
639 GHC.PrimopWrappers module. This module contains a "primop wrapper"
640 binding for each primop. These are standard Haskell functions mirroring the
641 types of the primops they wrap. For instance, in the case of plusInt# we would
642 have:
643
644 module GHC.PrimopWrappers where
645 import GHC.Prim as P
646
647 plusInt# :: Int# -> Int# -> Int#
648 plusInt# a b = P.plusInt# a b
649
650 The Id for the wrapper of a primop can be found using
651 'GHC.Builtin.PrimOps.primOpWrapperId'. However, GHCi does not use this mechanism
652 to link primops; it rather does a rather hacky symbol lookup (see
653 GHC.ByteCode.Linker.primopToCLabel). TODO: Perhaps this should be changed?
654
655 Note that these wrappers aren't *quite* as expressive as their unwrapped
656 breathren, in that they may exhibit less representation polymorphism.
657 For instance, consider the case of mkWeakNoFinalizer#, which has type:
658
659 mkWeakNoFinalizer# :: forall (r :: RuntimeRep) (k :: TYPE r) (v :: Type).
660 k -> v
661 -> State# RealWorld
662 -> (# State# RealWorld, Weak# v #)
663
664 Naively we could generate a wrapper of the form,
665
666
667 mkWeakNoFinalizer# k v s = GHC.Prim.mkWeakNoFinalizer# k v s
668
669 However, this would require that 'k' bind the representation-polymorphic key,
670 which is disallowed by our representation polymorphism validity checks
671 (see Note [Representation polymorphism invariants] in GHC.Core).
672 Consequently, we give the wrapper the simpler, less polymorphic type
673
674 mkWeakNoFinalizer# :: forall (k :: Type) (v :: Type).
675 k -> v
676 -> State# RealWorld
677 -> (# State# RealWorld, Weak# v #)
678
679 This simplification tends to be good enough for GHCi uses given that there are
680 few representation-polymorphic primops, and we do little simplification
681 on interpreted code anyways.
682
683 TODO: This behavior is actually wrong; a program becomes ill-typed upon
684 replacing a real primop occurrence with one of its wrapper due to the fact that
685 the former has an additional type binder. Hmmm....
686
687 Note [Eta expanding primops]
688 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
689
690 STG requires that primop applications be saturated. This makes code generation
691 significantly simpler since otherwise we would need to define a calling
692 convention for curried applications that can accommodate representation
693 polymorphism.
694
695 To ensure saturation, CorePrep eta expands all primop applications as
696 described in Note [Eta expansion of hasNoBinding things in CorePrep] in
697 GHC.Core.Prep.
698
699 Historical Note:
700
701 For a short period around GHC 8.8 we rewrote unsaturated primop applications to
702 rather use the primop's wrapper (see Note [Primop wrappers] in
703 GHC.Builtin.PrimOps) instead of eta expansion. This was because at the time
704 CoreTidy would try to predict the CAFfyness of bindings that would be produced
705 by CorePrep for inclusion in interface files. Eta expanding during CorePrep
706 proved to be very difficult to predict, leading to nasty inconsistencies in
707 CAFfyness determinations (see #16846).
708
709 Thankfully, we now no longer try to predict CAFfyness but rather compute it on
710 GHC STG (see Note [SRTs] in GHC.Cmm.Info.Build) and inject it into the interface
711 file after code generation (see TODO: Refer to whatever falls out of #18096).
712 This is much simpler and avoids the potential for inconsistency, allowing us to
713 return to the somewhat simpler eta expansion approach for unsaturated primops.
714
715 See #18079.
716 -}
717
718 -- | Returns the 'Id' of the wrapper associated with the given 'PrimOp'.
719 -- See Note [Primop wrappers].
720 primOpWrapperId :: PrimOp -> Id
721 primOpWrapperId op = mkVanillaGlobalWithInfo name ty info
722 where
723 info = setCafInfo vanillaIdInfo NoCafRefs
724 name = mkExternalName uniq gHC_PRIMOPWRAPPERS (primOpOcc op) wiredInSrcSpan
725 uniq = mkPrimOpWrapperUnique (primOpTag op)
726 ty = primOpType op
727
728 isComparisonPrimOp :: PrimOp -> Bool
729 isComparisonPrimOp op = case primOpInfo op of
730 Compare {} -> True
731 GenPrimOp {} -> False
732
733 -- primOpSig is like primOpType but gives the result split apart:
734 -- (type variables, argument types, result type)
735 -- It also gives arity, strictness info
736
737 primOpSig :: PrimOp -> ([TyVarBinder], [Type], Type, Arity, DmdSig)
738 primOpSig op
739 = (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
740 where
741 arity = length arg_tys
742 (tyvars, arg_tys, res_ty)
743 = case (primOpInfo op) of
744 Compare _occ ty -> ([], [ty,ty], intPrimTy)
745 GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty )
746
747 data PrimOpResultInfo
748 = ReturnsPrim PrimRep
749 | ReturnsAlg TyCon
750
751 -- Some PrimOps need not return a manifest primitive or algebraic value
752 -- (i.e. they might return a polymorphic value). These PrimOps *must*
753 -- be out of line, or the code generator won't work.
754
755 getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
756 getPrimOpResultInfo op
757 = case (primOpInfo op) of
758 Compare _ _ -> ReturnsPrim (tyConPrimRep1 intPrimTyCon)
759 GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep1 tc)
760 | otherwise -> ReturnsAlg tc
761 where
762 tc = tyConAppTyCon ty
763 -- All primops return a tycon-app result
764 -- The tycon can be an unboxed tuple or sum, though,
765 -- which gives rise to a ReturnAlg
766
767 {-
768 We do not currently make use of whether primops are commutable.
769
770 We used to try to move constants to the right hand side for strength
771 reduction.
772 -}
773
774 {-
775 commutableOp :: PrimOp -> Bool
776 #include "primop-commutable.hs-incl"
777 -}
778
779 -- Utils:
780
781 compare_fun_ty :: Type -> Type
782 compare_fun_ty ty = mkVisFunTysMany [ty, ty] intPrimTy
783
784 -- Output stuff:
785
786 pprPrimOp :: PrimOp -> SDoc
787 pprPrimOp other_op = pprOccName (primOpOcc other_op)
788
789 {-
790 ************************************************************************
791 * *
792 \subsubsection[PrimCall]{User-imported primitive calls}
793 * *
794 ************************************************************************
795 -}
796
797 data PrimCall = PrimCall CLabelString Unit
798
799 instance Outputable PrimCall where
800 ppr (PrimCall lbl pkgId)
801 = text "__primcall" <+> ppr pkgId <+> ppr lbl