1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2004
5 * Out-of-line primitive operations
7 * This file contains the implementations of all the primitive
8 * operations ("primops") which are not expanded inline. See
9 * ghc/compiler/prelude/primops.txt.pp for a list of all the primops;
10 * this file contains code for most of those with the attribute
13 * Entry convention: the entry convention for a primop is that all the
14 * args are in Stg registers (R1, R2, etc.). This is to make writing
15 * the primops easier. (see compiler/codeGen/CgCallConv.hs).
17 * Return convention: results from a primop are generally returned
18 * using the ordinary unboxed tuple return convention. The C-- parser
19 * implements the RET_xxxx() macros to perform unboxed-tuple returns
20 * based on the prevailing return convention.
22 * This file is written in a subset of C--, extended with various
23 * features specific to GHC. It is compiled by GHC directly. For the
24 * syntax of .cmm files, see the parser in ghc/compiler/cmm/CmmParse.y.
26 * ---------------------------------------------------------------------------*/
40 import __gmpz_tdiv_qr;
41 import __gmpz_fdiv_qr;
42 import __gmpz_divexact;
47 import base_GHCziIOBase_NestedAtomically_closure;
48 import pthread_mutex_lock;
49 import pthread_mutex_unlock;
52 /*-----------------------------------------------------------------------------
55 Basically just new*Array - the others are all inline macros.
57 The size arg is always passed in R1, and the result returned in R1.
59 The slow entry point is for returning from a heap check, the saved
60 size argument must be re-loaded from the stack.
61 -------------------------------------------------------------------------- */
63 /* for objects that are *less* than the size of a word, make sure we
64 * round up to the nearest word for the size of the array.
69 W_ words, payload_words, n, p;
70 MAYBE_GC(NO_PTRS,newByteArrayzh_fast);
72 payload_words = ROUNDUP_BYTES_TO_WDS(n);
73 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
74 ("ptr" p) = foreign "C" allocateLocal(MyCapability() "ptr",words) [];
75 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
76 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
77 StgArrWords_words(p) = payload_words;
81 newPinnedByteArrayzh_fast
83 W_ words, payload_words, n, p;
85 MAYBE_GC(NO_PTRS,newPinnedByteArrayzh_fast);
87 payload_words = ROUNDUP_BYTES_TO_WDS(n);
89 // We want an 8-byte aligned array. allocatePinned() gives us
90 // 8-byte aligned memory by default, but we want to align the
91 // *goods* inside the ArrWords object, so we have to check the
92 // size of the ArrWords header and adjust our size accordingly.
93 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
94 if ((SIZEOF_StgArrWords & 7) != 0) {
98 ("ptr" p) = foreign "C" allocatePinned(words) [];
99 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
101 // Again, if the ArrWords header isn't a multiple of 8 bytes, we
102 // have to push the object forward one word so that the goods
103 // fall on an 8-byte boundary.
104 if ((SIZEOF_StgArrWords & 7) != 0) {
108 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
109 StgArrWords_words(p) = payload_words;
115 W_ words, n, init, arr, p;
116 /* Args: R1 = words, R2 = initialisation value */
119 MAYBE_GC(R2_PTR,newArrayzh_fast);
121 words = BYTES_TO_WDS(SIZEOF_StgMutArrPtrs) + n;
122 ("ptr" arr) = foreign "C" allocateLocal(MyCapability() "ptr",words) [R2];
123 TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(n), 0);
125 SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, W_[CCCS]);
126 StgMutArrPtrs_ptrs(arr) = n;
128 // Initialise all elements of the the array with the value in R2
130 p = arr + SIZEOF_StgMutArrPtrs;
132 if (p < arr + WDS(words)) {
141 unsafeThawArrayzh_fast
143 // SUBTLETY TO DO WITH THE OLD GEN MUTABLE LIST
145 // A MUT_ARR_PTRS lives on the mutable list, but a MUT_ARR_PTRS_FROZEN
146 // normally doesn't. However, when we freeze a MUT_ARR_PTRS, we leave
147 // it on the mutable list for the GC to remove (removing something from
148 // the mutable list is not easy, because the mut_list is only singly-linked).
150 // So that we can tell whether a MUT_ARR_PTRS_FROZEN is on the mutable list,
151 // when we freeze it we set the info ptr to be MUT_ARR_PTRS_FROZEN0
152 // to indicate that it is still on the mutable list.
154 // So, when we thaw a MUT_ARR_PTRS_FROZEN, we must cope with two cases:
155 // either it is on a mut_list, or it isn't. We adopt the convention that
156 // the closure type is MUT_ARR_PTRS_FROZEN0 if it is on the mutable list,
157 // and MUT_ARR_PTRS_FROZEN otherwise. In fact it wouldn't matter if
158 // we put it on the mutable list more than once, but it would get scavenged
159 // multiple times during GC, which would be unnecessarily slow.
161 if (StgHeader_info(R1) != stg_MUT_ARR_PTRS_FROZEN0_info) {
162 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
163 recordMutable(R1, R1);
164 // must be done after SET_INFO, because it ASSERTs closure_MUTABLE()
167 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
172 /* -----------------------------------------------------------------------------
174 -------------------------------------------------------------------------- */
179 /* Args: R1 = initialisation value */
181 ALLOC_PRIM( SIZEOF_StgMutVar, R1_PTR, newMutVarzh_fast);
183 mv = Hp - SIZEOF_StgMutVar + WDS(1);
184 SET_HDR(mv,stg_MUT_VAR_DIRTY_info,W_[CCCS]);
185 StgMutVar_var(mv) = R1;
190 atomicModifyMutVarzh_fast
193 /* Args: R1 :: MutVar#, R2 :: a -> (a,b) */
195 /* If x is the current contents of the MutVar#, then
196 We want to make the new contents point to
200 and the return value is
204 obviously we can share (f x).
206 z = [stg_ap_2 f x] (max (HS + 2) MIN_UPD_SIZE)
207 y = [stg_sel_0 z] (max (HS + 1) MIN_UPD_SIZE)
208 r = [stg_sel_1 z] (max (HS + 1) MIN_UPD_SIZE)
212 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
213 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),WDS(MIN_UPD_SIZE-1))
215 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(1))
216 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),0)
220 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
221 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
223 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(2))
224 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),0)
227 #define SIZE (THUNK_2_SIZE + THUNK_1_SIZE + THUNK_1_SIZE)
229 HP_CHK_GEN_TICKY(SIZE, R1_PTR & R2_PTR, atomicModifyMutVarzh_fast);
231 #if defined(THREADED_RTS)
232 ACQUIRE_LOCK(atomic_modify_mutvar_mutex "ptr") [R1,R2];
235 x = StgMutVar_var(R1);
237 TICK_ALLOC_THUNK_2();
238 CCCS_ALLOC(THUNK_2_SIZE);
239 z = Hp - THUNK_2_SIZE + WDS(1);
240 SET_HDR(z, stg_ap_2_upd_info, W_[CCCS]);
241 LDV_RECORD_CREATE(z);
242 StgThunk_payload(z,0) = R2;
243 StgThunk_payload(z,1) = x;
245 TICK_ALLOC_THUNK_1();
246 CCCS_ALLOC(THUNK_1_SIZE);
247 y = z - THUNK_1_SIZE;
248 SET_HDR(y, stg_sel_0_upd_info, W_[CCCS]);
249 LDV_RECORD_CREATE(y);
250 StgThunk_payload(y,0) = z;
252 StgMutVar_var(R1) = y;
253 foreign "C" dirty_MUT_VAR(BaseReg "ptr", R1 "ptr") [R1];
255 TICK_ALLOC_THUNK_1();
256 CCCS_ALLOC(THUNK_1_SIZE);
257 r = y - THUNK_1_SIZE;
258 SET_HDR(r, stg_sel_1_upd_info, W_[CCCS]);
259 LDV_RECORD_CREATE(r);
260 StgThunk_payload(r,0) = z;
262 #if defined(THREADED_RTS)
263 RELEASE_LOCK(atomic_modify_mutvar_mutex "ptr") [];
269 /* -----------------------------------------------------------------------------
270 Weak Pointer Primitives
271 -------------------------------------------------------------------------- */
273 STRING(stg_weak_msg,"New weak pointer at %p\n")
279 R3 = finalizer (or NULL)
284 R3 = stg_NO_FINALIZER_closure;
287 ALLOC_PRIM( SIZEOF_StgWeak, R1_PTR & R2_PTR & R3_PTR, mkWeakzh_fast );
289 w = Hp - SIZEOF_StgWeak + WDS(1);
290 SET_HDR(w, stg_WEAK_info, W_[CCCS]);
293 StgWeak_value(w) = R2;
294 StgWeak_finalizer(w) = R3;
296 StgWeak_link(w) = W_[weak_ptr_list];
297 W_[weak_ptr_list] = w;
299 IF_DEBUG(weak, foreign "C" debugBelch(stg_weak_msg,w) []);
314 if (GET_INFO(w) == stg_DEAD_WEAK_info) {
315 RET_NP(0,stg_NO_FINALIZER_closure);
321 // A weak pointer is inherently used, so we do not need to call
322 // LDV_recordDead_FILL_SLOP_DYNAMIC():
323 // LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
324 // or, LDV_recordDead():
325 // LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
326 // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
327 // large as weak pointers, so there is no need to fill the slop, either.
328 // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
332 // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
334 SET_INFO(w,stg_DEAD_WEAK_info);
335 LDV_RECORD_CREATE(w);
337 f = StgWeak_finalizer(w);
338 StgDeadWeak_link(w) = StgWeak_link(w);
340 /* return the finalizer */
341 if (f == stg_NO_FINALIZER_closure) {
342 RET_NP(0,stg_NO_FINALIZER_closure);
354 if (GET_INFO(w) == stg_WEAK_info) {
356 val = StgWeak_value(w);
364 /* -----------------------------------------------------------------------------
365 Arbitrary-precision Integer operations.
367 There are some assumptions in this code that mp_limb_t == W_. This is
368 the case for all the platforms that GHC supports, currently.
369 -------------------------------------------------------------------------- */
373 /* arguments: R1 = Int# */
375 W_ val, s, p; /* to avoid aliasing */
378 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, int2Integerzh_fast );
380 p = Hp - SIZEOF_StgArrWords;
381 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
382 StgArrWords_words(p) = 1;
384 /* mpz_set_si is inlined here, makes things simpler */
397 /* returns (# size :: Int#,
406 /* arguments: R1 = Word# */
408 W_ val, s, p; /* to avoid aliasing */
412 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, word2Integerzh_fast);
414 p = Hp - SIZEOF_StgArrWords;
415 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
416 StgArrWords_words(p) = 1;
425 /* returns (# size :: Int#,
426 data :: ByteArray# #)
433 * 'long long' primops for converting to/from Integers.
436 #ifdef SUPPORT_LONG_LONGS
438 int64ToIntegerzh_fast
440 /* arguments: L1 = Int64# */
443 W_ hi, lo, s, neg, words_needed, p;
448 hi = TO_W_(val >> 32);
451 if ( hi != 0 && hi != 0xFFFFFFFF ) {
454 // minimum is one word
458 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
459 NO_PTRS, int64ToIntegerzh_fast );
461 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
462 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
463 StgArrWords_words(p) = words_needed;
475 if ( words_needed == 2 ) {
483 } else /* val==0 */ {
491 /* returns (# size :: Int#,
492 data :: ByteArray# #)
496 word64ToIntegerzh_fast
498 /* arguments: L1 = Word64# */
501 W_ hi, lo, s, words_needed, p;
504 hi = TO_W_(val >> 32);
513 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
514 NO_PTRS, word64ToIntegerzh_fast );
516 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
517 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
518 StgArrWords_words(p) = words_needed;
528 } else /* val==0 */ {
533 /* returns (# size :: Int#,
534 data :: ByteArray# #)
541 #endif /* SUPPORT_LONG_LONGS */
543 /* ToDo: this is shockingly inefficient */
548 bits8 [SIZEOF_MP_INT];
553 bits8 [SIZEOF_MP_INT];
558 bits8 [SIZEOF_MP_INT];
563 bits8 [SIZEOF_MP_INT];
568 #define FETCH_MP_TEMP(X) \
570 X = BaseReg + (OFFSET_StgRegTable_r ## X);
572 #define FETCH_MP_TEMP(X) /* Nothing */
575 #define GMP_TAKE2_RET1(name,mp_fun) \
580 FETCH_MP_TEMP(mp_tmp1); \
581 FETCH_MP_TEMP(mp_tmp2); \
582 FETCH_MP_TEMP(mp_result1) \
583 FETCH_MP_TEMP(mp_result2); \
585 /* call doYouWantToGC() */ \
586 MAYBE_GC(R2_PTR & R4_PTR, name); \
593 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
594 MP_INT__mp_size(mp_tmp1) = (s1); \
595 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
596 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
597 MP_INT__mp_size(mp_tmp2) = (s2); \
598 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
600 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
602 /* Perform the operation */ \
603 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
605 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
606 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
609 #define GMP_TAKE1_RET1(name,mp_fun) \
614 FETCH_MP_TEMP(mp_tmp1); \
615 FETCH_MP_TEMP(mp_result1) \
617 /* call doYouWantToGC() */ \
618 MAYBE_GC(R2_PTR, name); \
623 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
624 MP_INT__mp_size(mp_tmp1) = (s1); \
625 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
627 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
629 /* Perform the operation */ \
630 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr") []; \
632 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
633 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
636 #define GMP_TAKE2_RET2(name,mp_fun) \
641 FETCH_MP_TEMP(mp_tmp1); \
642 FETCH_MP_TEMP(mp_tmp2); \
643 FETCH_MP_TEMP(mp_result1) \
644 FETCH_MP_TEMP(mp_result2) \
646 /* call doYouWantToGC() */ \
647 MAYBE_GC(R2_PTR & R4_PTR, name); \
654 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
655 MP_INT__mp_size(mp_tmp1) = (s1); \
656 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
657 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
658 MP_INT__mp_size(mp_tmp2) = (s2); \
659 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
661 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
662 foreign "C" __gmpz_init(mp_result2 "ptr") []; \
664 /* Perform the operation */ \
665 foreign "C" mp_fun(mp_result1 "ptr",mp_result2 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
667 RET_NPNP(TO_W_(MP_INT__mp_size(mp_result1)), \
668 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords, \
669 TO_W_(MP_INT__mp_size(mp_result2)), \
670 MP_INT__mp_d(mp_result2) - SIZEOF_StgArrWords); \
673 GMP_TAKE2_RET1(plusIntegerzh_fast, __gmpz_add)
674 GMP_TAKE2_RET1(minusIntegerzh_fast, __gmpz_sub)
675 GMP_TAKE2_RET1(timesIntegerzh_fast, __gmpz_mul)
676 GMP_TAKE2_RET1(gcdIntegerzh_fast, __gmpz_gcd)
677 GMP_TAKE2_RET1(quotIntegerzh_fast, __gmpz_tdiv_q)
678 GMP_TAKE2_RET1(remIntegerzh_fast, __gmpz_tdiv_r)
679 GMP_TAKE2_RET1(divExactIntegerzh_fast, __gmpz_divexact)
680 GMP_TAKE2_RET1(andIntegerzh_fast, __gmpz_and)
681 GMP_TAKE2_RET1(orIntegerzh_fast, __gmpz_ior)
682 GMP_TAKE2_RET1(xorIntegerzh_fast, __gmpz_xor)
683 GMP_TAKE1_RET1(complementIntegerzh_fast, __gmpz_com)
685 GMP_TAKE2_RET2(quotRemIntegerzh_fast, __gmpz_tdiv_qr)
686 GMP_TAKE2_RET2(divModIntegerzh_fast, __gmpz_fdiv_qr)
690 mp_tmp_w: W_; // NB. mp_tmp_w is really an here mp_limb_t
696 /* R1 = the first Int#; R2 = the second Int# */
698 FETCH_MP_TEMP(mp_tmp_w);
701 (r) = foreign "C" __gmpn_gcd_1(mp_tmp_w "ptr", 1, R2) [];
704 /* Result parked in R1, return via info-pointer at TOS */
705 jump %ENTRY_CODE(Sp(0));
711 /* R1 = s1; R2 = d1; R3 = the int */
713 (s1) = foreign "C" __gmpn_gcd_1( BYTE_ARR_CTS(R2) "ptr", R1, R3) [];
716 /* Result parked in R1, return via info-pointer at TOS */
717 jump %ENTRY_CODE(Sp(0));
723 /* R1 = s1; R2 = d1; R3 = the int */
724 W_ usize, vsize, v_digit, u_digit;
730 // paraphrased from __gmpz_cmp_si() in the GMP sources
731 if (%gt(v_digit,0)) {
734 if (%lt(v_digit,0)) {
740 if (usize != vsize) {
742 jump %ENTRY_CODE(Sp(0));
747 jump %ENTRY_CODE(Sp(0));
750 u_digit = W_[BYTE_ARR_CTS(R2)];
752 if (u_digit == v_digit) {
754 jump %ENTRY_CODE(Sp(0));
757 if (%gtu(u_digit,v_digit)) { // NB. unsigned: these are mp_limb_t's
763 jump %ENTRY_CODE(Sp(0));
768 /* R1 = s1; R2 = d1; R3 = s2; R4 = d2 */
769 W_ usize, vsize, size, up, vp;
772 // paraphrased from __gmpz_cmp() in the GMP sources
776 if (usize != vsize) {
778 jump %ENTRY_CODE(Sp(0));
783 jump %ENTRY_CODE(Sp(0));
786 if (%lt(usize,0)) { // NB. not <, which is unsigned
792 up = BYTE_ARR_CTS(R2);
793 vp = BYTE_ARR_CTS(R4);
795 (cmp) = foreign "C" __gmpn_cmp(up "ptr", vp "ptr", size) [];
797 if (cmp == 0 :: CInt) {
799 jump %ENTRY_CODE(Sp(0));
802 if (%lt(cmp,0 :: CInt) == %lt(usize,0)) {
807 /* Result parked in R1, return via info-pointer at TOS */
808 jump %ENTRY_CODE(Sp(0));
820 r = W_[R2 + SIZEOF_StgArrWords];
825 /* Result parked in R1, return via info-pointer at TOS */
827 jump %ENTRY_CODE(Sp(0));
839 r = W_[R2 + SIZEOF_StgArrWords];
844 /* Result parked in R1, return via info-pointer at TOS */
846 jump %ENTRY_CODE(Sp(0));
853 FETCH_MP_TEMP(mp_tmp1);
854 FETCH_MP_TEMP(mp_tmp_w);
856 /* arguments: F1 = Float# */
859 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, decodeFloatzh_fast );
861 /* Be prepared to tell Lennart-coded __decodeFloat
862 where mantissa._mp_d can be put (it does not care about the rest) */
863 p = Hp - SIZEOF_StgArrWords;
864 SET_HDR(p,stg_ARR_WORDS_info,W_[CCCS]);
865 StgArrWords_words(p) = 1;
866 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
868 /* Perform the operation */
869 foreign "C" __decodeFloat(mp_tmp1 "ptr",mp_tmp_w "ptr" ,arg) [];
871 /* returns: (Int# (expn), Int#, ByteArray#) */
872 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
875 #define DOUBLE_MANTISSA_SIZE SIZEOF_DOUBLE
876 #define ARR_SIZE (SIZEOF_StgArrWords + DOUBLE_MANTISSA_SIZE)
882 FETCH_MP_TEMP(mp_tmp1);
883 FETCH_MP_TEMP(mp_tmp_w);
885 /* arguments: D1 = Double# */
888 ALLOC_PRIM( ARR_SIZE, NO_PTRS, decodeDoublezh_fast );
890 /* Be prepared to tell Lennart-coded __decodeDouble
891 where mantissa.d can be put (it does not care about the rest) */
892 p = Hp - ARR_SIZE + WDS(1);
893 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
894 StgArrWords_words(p) = BYTES_TO_WDS(DOUBLE_MANTISSA_SIZE);
895 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
897 /* Perform the operation */
898 foreign "C" __decodeDouble(mp_tmp1 "ptr", mp_tmp_w "ptr",arg) [];
900 /* returns: (Int# (expn), Int#, ByteArray#) */
901 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
904 /* -----------------------------------------------------------------------------
905 * Concurrency primitives
906 * -------------------------------------------------------------------------- */
910 /* args: R1 = closure to spark */
912 MAYBE_GC(R1_PTR, forkzh_fast);
918 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
919 RtsFlags_GcFlags_initialStkSize(RtsFlags),
921 foreign "C" scheduleThread(MyCapability() "ptr", threadid "ptr") [];
923 // switch at the earliest opportunity
924 CInt[context_switch] = 1 :: CInt;
931 /* args: R1 = cpu, R2 = closure to spark */
933 MAYBE_GC(R2_PTR, forkOnzh_fast);
941 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
942 RtsFlags_GcFlags_initialStkSize(RtsFlags),
944 foreign "C" scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr") [];
946 // switch at the earliest opportunity
947 CInt[context_switch] = 1 :: CInt;
954 jump stg_yield_noregs;
969 foreign "C" labelThread(R1 "ptr", R2 "ptr") [];
971 jump %ENTRY_CODE(Sp(0));
974 isCurrentThreadBoundzh_fast
978 (r) = foreign "C" isThreadBound(CurrentTSO) [];
983 /* -----------------------------------------------------------------------------
985 * -------------------------------------------------------------------------- */
989 #define IF_NOT_REG_R1(x)
992 #define IF_NOT_REG_R1(x) x
995 // Catch retry frame ------------------------------------------------------------
997 INFO_TABLE_RET(stg_catch_retry_frame, CATCH_RETRY_FRAME,
998 #if defined(PROFILING)
999 W_ unused1, W_ unused2,
1001 W_ unused3, "ptr" W_ unused4, "ptr" W_ unused5)
1003 W_ r, frame, trec, outer;
1004 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1007 trec = StgTSO_trec(CurrentTSO);
1008 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1009 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1011 /* Succeeded (either first branch or second branch) */
1012 StgTSO_trec(CurrentTSO) = outer;
1013 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1014 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1015 jump %ENTRY_CODE(Sp(SP_OFF));
1017 /* Did not commit: re-execute */
1019 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1020 StgTSO_trec(CurrentTSO) = new_trec;
1021 if (StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1022 R1 = StgCatchRetryFrame_alt_code(frame);
1024 R1 = StgCatchRetryFrame_first_code(frame);
1031 // Atomically frame ------------------------------------------------------------
1033 INFO_TABLE_RET(stg_atomically_frame, ATOMICALLY_FRAME,
1034 #if defined(PROFILING)
1035 W_ unused1, W_ unused2,
1037 "ptr" W_ unused3, "ptr" W_ unused4)
1039 W_ frame, trec, valid, next_invariant, q, outer;
1040 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1043 trec = StgTSO_trec(CurrentTSO);
1044 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1046 if (outer == NO_TREC) {
1047 /* First time back at the atomically frame -- pick up invariants */
1048 ("ptr" q) = foreign "C" stmGetInvariantsToCheck(MyCapability() "ptr", trec "ptr") [];
1049 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1052 /* Second/subsequent time back at the atomically frame -- abort the
1053 * tx that's checking the invariant and move on to the next one */
1054 StgTSO_trec(CurrentTSO) = outer;
1055 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1056 StgInvariantCheckQueue_my_execution(q) = trec;
1057 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1058 /* Don't free trec -- it's linked from q and will be stashed in the
1059 * invariant if we eventually commit. */
1060 q = StgInvariantCheckQueue_next_queue_entry(q);
1061 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1065 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1067 if (q != END_INVARIANT_CHECK_QUEUE) {
1068 /* We can't commit yet: another invariant to check */
1069 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [];
1070 StgTSO_trec(CurrentTSO) = trec;
1072 next_invariant = StgInvariantCheckQueue_invariant(q);
1073 R1 = StgAtomicInvariant_code(next_invariant);
1078 /* We've got no more invariants to check, try to commit */
1079 (valid) = foreign "C" stmCommitTransaction(MyCapability() "ptr", trec "ptr") [];
1081 /* Transaction was valid: commit succeeded */
1082 StgTSO_trec(CurrentTSO) = NO_TREC;
1083 Sp = Sp + SIZEOF_StgAtomicallyFrame;
1084 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1085 jump %ENTRY_CODE(Sp(SP_OFF));
1087 /* Transaction was not valid: try again */
1088 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1089 StgTSO_trec(CurrentTSO) = trec;
1090 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1091 R1 = StgAtomicallyFrame_code(frame);
1097 INFO_TABLE_RET(stg_atomically_waiting_frame, ATOMICALLY_FRAME,
1098 #if defined(PROFILING)
1099 W_ unused1, W_ unused2,
1101 "ptr" W_ unused3, "ptr" W_ unused4)
1103 W_ frame, trec, valid;
1104 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1108 /* The TSO is currently waiting: should we stop waiting? */
1109 (valid) = foreign "C" stmReWait(MyCapability() "ptr", CurrentTSO "ptr") [];
1111 /* Previous attempt is still valid: no point trying again yet */
1112 IF_NOT_REG_R1(Sp_adj(-2);
1113 Sp(1) = stg_NO_FINALIZER_closure;
1114 Sp(0) = stg_ut_1_0_unreg_info;)
1115 jump stg_block_noregs;
1117 /* Previous attempt is no longer valid: try again */
1118 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1119 StgTSO_trec(CurrentTSO) = trec;
1120 StgHeader_info(frame) = stg_atomically_frame_info;
1121 R1 = StgAtomicallyFrame_code(frame);
1126 // STM catch frame --------------------------------------------------------------
1134 /* Catch frames are very similar to update frames, but when entering
1135 * one we just pop the frame off the stack and perform the correct
1136 * kind of return to the activation record underneath us on the stack.
1139 INFO_TABLE_RET(stg_catch_stm_frame, CATCH_STM_FRAME,
1140 #if defined(PROFILING)
1141 W_ unused1, W_ unused2,
1143 "ptr" W_ unused3, "ptr" W_ unused4)
1145 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1146 W_ r, frame, trec, outer;
1148 trec = StgTSO_trec(CurrentTSO);
1149 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1150 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1152 /* Commit succeeded */
1153 StgTSO_trec(CurrentTSO) = outer;
1154 Sp = Sp + SIZEOF_StgCatchSTMFrame;
1155 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1160 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1161 StgTSO_trec(CurrentTSO) = new_trec;
1162 R1 = StgCatchSTMFrame_code(frame);
1168 // Primop definition ------------------------------------------------------------
1176 // stmStartTransaction may allocate
1177 MAYBE_GC (R1_PTR, atomicallyzh_fast);
1179 /* Args: R1 = m :: STM a */
1180 STK_CHK_GEN(SIZEOF_StgAtomicallyFrame + WDS(1), R1_PTR, atomicallyzh_fast);
1182 old_trec = StgTSO_trec(CurrentTSO);
1184 /* Nested transactions are not allowed; raise an exception */
1185 if (old_trec != NO_TREC) {
1186 R1 = base_GHCziIOBase_NestedAtomically_closure;
1190 /* Set up the atomically frame */
1191 Sp = Sp - SIZEOF_StgAtomicallyFrame;
1194 SET_HDR(frame,stg_atomically_frame_info, W_[CCCS]);
1195 StgAtomicallyFrame_code(frame) = R1;
1196 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1198 /* Start the memory transcation */
1199 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", old_trec "ptr") [R1];
1200 StgTSO_trec(CurrentTSO) = new_trec;
1202 /* Apply R1 to the realworld token */
1211 /* Args: R1 :: STM a */
1212 /* Args: R2 :: Exception -> STM a */
1213 STK_CHK_GEN(SIZEOF_StgCatchSTMFrame + WDS(1), R1_PTR & R2_PTR, catchSTMzh_fast);
1215 /* Set up the catch frame */
1216 Sp = Sp - SIZEOF_StgCatchSTMFrame;
1219 SET_HDR(frame, stg_catch_stm_frame_info, W_[CCCS]);
1220 StgCatchSTMFrame_handler(frame) = R2;
1221 StgCatchSTMFrame_code(frame) = R1;
1223 /* Start a nested transaction to run the body of the try block in */
1226 cur_trec = StgTSO_trec(CurrentTSO);
1227 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", cur_trec "ptr");
1228 StgTSO_trec(CurrentTSO) = new_trec;
1230 /* Apply R1 to the realworld token */
1241 // stmStartTransaction may allocate
1242 MAYBE_GC (R1_PTR & R2_PTR, catchRetryzh_fast);
1244 /* Args: R1 :: STM a */
1245 /* Args: R2 :: STM a */
1246 STK_CHK_GEN(SIZEOF_StgCatchRetryFrame + WDS(1), R1_PTR & R2_PTR, catchRetryzh_fast);
1248 /* Start a nested transaction within which to run the first code */
1249 trec = StgTSO_trec(CurrentTSO);
1250 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [R1,R2];
1251 StgTSO_trec(CurrentTSO) = new_trec;
1253 /* Set up the catch-retry frame */
1254 Sp = Sp - SIZEOF_StgCatchRetryFrame;
1257 SET_HDR(frame, stg_catch_retry_frame_info, W_[CCCS]);
1258 StgCatchRetryFrame_running_alt_code(frame) = 0 :: CInt; // false;
1259 StgCatchRetryFrame_first_code(frame) = R1;
1260 StgCatchRetryFrame_alt_code(frame) = R2;
1262 /* Apply R1 to the realworld token */
1275 MAYBE_GC (NO_PTRS, retryzh_fast); // STM operations may allocate
1277 // Find the enclosing ATOMICALLY_FRAME or CATCH_RETRY_FRAME
1279 StgTSO_sp(CurrentTSO) = Sp;
1280 (frame_type) = foreign "C" findRetryFrameHelper(CurrentTSO "ptr") [];
1281 Sp = StgTSO_sp(CurrentTSO);
1283 trec = StgTSO_trec(CurrentTSO);
1284 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1286 if (frame_type == CATCH_RETRY_FRAME) {
1287 // The retry reaches a CATCH_RETRY_FRAME before the atomic frame
1288 ASSERT(outer != NO_TREC);
1289 // Abort the transaction attempting the current branch
1290 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1291 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1292 if (!StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1293 // Retry in the first branch: try the alternative
1294 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1295 StgTSO_trec(CurrentTSO) = trec;
1296 StgCatchRetryFrame_running_alt_code(frame) = 1 :: CInt; // true;
1297 R1 = StgCatchRetryFrame_alt_code(frame);
1300 // Retry in the alternative code: propagate the retry
1301 StgTSO_trec(CurrentTSO) = outer;
1302 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1303 goto retry_pop_stack;
1307 // We've reached the ATOMICALLY_FRAME: attempt to wait
1308 ASSERT(frame_type == ATOMICALLY_FRAME);
1309 if (outer != NO_TREC) {
1310 // We called retry while checking invariants, so abort the current
1311 // invariant check (merging its TVar accesses into the parents read
1312 // set so we'll wait on them)
1313 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1314 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1316 StgTSO_trec(CurrentTSO) = trec;
1317 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1319 ASSERT(outer == NO_TREC);
1321 (r) = foreign "C" stmWait(MyCapability() "ptr", CurrentTSO "ptr", trec "ptr") [];
1323 // Transaction was valid: stmWait put us on the TVars' queues, we now block
1324 StgHeader_info(frame) = stg_atomically_waiting_frame_info;
1326 // Fix up the stack in the unregisterised case: the return convention is different.
1327 IF_NOT_REG_R1(Sp_adj(-2);
1328 Sp(1) = stg_NO_FINALIZER_closure;
1329 Sp(0) = stg_ut_1_0_unreg_info;)
1330 R3 = trec; // passing to stmWaitUnblock()
1331 jump stg_block_stmwait;
1333 // Transaction was not valid: retry immediately
1334 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1335 StgTSO_trec(CurrentTSO) = trec;
1336 R1 = StgAtomicallyFrame_code(frame);
1347 /* Args: R1 = invariant closure */
1348 MAYBE_GC (R1_PTR, checkzh_fast);
1350 trec = StgTSO_trec(CurrentTSO);
1352 foreign "C" stmAddInvariantToCheck(MyCapability() "ptr",
1356 jump %ENTRY_CODE(Sp(0));
1365 /* Args: R1 = initialisation value */
1367 MAYBE_GC (R1_PTR, newTVarzh_fast);
1369 ("ptr" tv) = foreign "C" stmNewTVar(MyCapability() "ptr", new_value "ptr") [];
1380 /* Args: R1 = TVar closure */
1382 MAYBE_GC (R1_PTR, readTVarzh_fast); // Call to stmReadTVar may allocate
1383 trec = StgTSO_trec(CurrentTSO);
1385 ("ptr" result) = foreign "C" stmReadTVar(MyCapability() "ptr", trec "ptr", tvar "ptr") [];
1397 /* Args: R1 = TVar closure */
1398 /* R2 = New value */
1400 MAYBE_GC (R1_PTR & R2_PTR, writeTVarzh_fast); // Call to stmWriteTVar may allocate
1401 trec = StgTSO_trec(CurrentTSO);
1404 foreign "C" stmWriteTVar(MyCapability() "ptr", trec "ptr", tvar "ptr", new_value "ptr") [];
1406 jump %ENTRY_CODE(Sp(0));
1410 /* -----------------------------------------------------------------------------
1413 * take & putMVar work as follows. Firstly, an important invariant:
1415 * If the MVar is full, then the blocking queue contains only
1416 * threads blocked on putMVar, and if the MVar is empty then the
1417 * blocking queue contains only threads blocked on takeMVar.
1420 * MVar empty : then add ourselves to the blocking queue
1421 * MVar full : remove the value from the MVar, and
1422 * blocking queue empty : return
1423 * blocking queue non-empty : perform the first blocked putMVar
1424 * from the queue, and wake up the
1425 * thread (MVar is now full again)
1427 * putMVar is just the dual of the above algorithm.
1429 * How do we "perform a putMVar"? Well, we have to fiddle around with
1430 * the stack of the thread waiting to do the putMVar. See
1431 * stg_block_putmvar and stg_block_takemvar in HeapStackCheck.c for
1432 * the stack layout, and the PerformPut and PerformTake macros below.
1434 * It is important that a blocked take or put is woken up with the
1435 * take/put already performed, because otherwise there would be a
1436 * small window of vulnerability where the thread could receive an
1437 * exception and never perform its take or put, and we'd end up with a
1440 * -------------------------------------------------------------------------- */
1444 /* args: R1 = MVar closure */
1446 if (GET_INFO(R1) == stg_EMPTY_MVAR_info) {
1458 ALLOC_PRIM ( SIZEOF_StgMVar, NO_PTRS, newMVarzh_fast );
1460 mvar = Hp - SIZEOF_StgMVar + WDS(1);
1461 SET_HDR(mvar,stg_EMPTY_MVAR_info,W_[CCCS]);
1462 StgMVar_head(mvar) = stg_END_TSO_QUEUE_closure;
1463 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1464 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1469 /* If R1 isn't available, pass it on the stack */
1471 #define PerformTake(tso, value) \
1472 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1473 W_[StgTSO_sp(tso) + WDS(0)] = stg_gc_unpt_r1_info;
1475 #define PerformTake(tso, value) \
1476 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1477 W_[StgTSO_sp(tso) + WDS(0)] = stg_ut_1_0_unreg_info;
1480 #define PerformPut(tso,lval) \
1481 StgTSO_sp(tso) = StgTSO_sp(tso) + WDS(3); \
1482 lval = W_[StgTSO_sp(tso) - WDS(1)];
1486 W_ mvar, val, info, tso;
1488 /* args: R1 = MVar closure */
1491 #if defined(THREADED_RTS)
1492 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1494 info = GET_INFO(mvar);
1497 /* If the MVar is empty, put ourselves on its blocking queue,
1498 * and wait until we're woken up.
1500 if (info == stg_EMPTY_MVAR_info) {
1501 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1502 StgMVar_head(mvar) = CurrentTSO;
1504 StgTSO_link(StgMVar_tail(mvar)) = CurrentTSO;
1506 StgTSO_link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1507 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1508 StgTSO_block_info(CurrentTSO) = mvar;
1509 StgMVar_tail(mvar) = CurrentTSO;
1511 jump stg_block_takemvar;
1514 /* we got the value... */
1515 val = StgMVar_value(mvar);
1517 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure)
1519 /* There are putMVar(s) waiting...
1520 * wake up the first thread on the queue
1522 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1524 /* actually perform the putMVar for the thread that we just woke up */
1525 tso = StgMVar_head(mvar);
1526 PerformPut(tso,StgMVar_value(mvar));
1529 #if defined(GRAN) || defined(PAR)
1530 /* ToDo: check 2nd arg (mvar) is right */
1531 ("ptr" tso) = foreign "C" unblockOne(StgMVar_head(mvar),mvar) [];
1532 StgMVar_head(mvar) = tso;
1534 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr",
1535 StgMVar_head(mvar) "ptr") [];
1536 StgMVar_head(mvar) = tso;
1539 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1540 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1543 #if defined(THREADED_RTS)
1544 unlockClosure(mvar, stg_FULL_MVAR_info);
1550 /* No further putMVars, MVar is now empty */
1551 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1553 #if defined(THREADED_RTS)
1554 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1556 SET_INFO(mvar,stg_EMPTY_MVAR_info);
1566 W_ mvar, val, info, tso;
1568 /* args: R1 = MVar closure */
1572 #if defined(THREADED_RTS)
1573 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1575 info = GET_INFO(mvar);
1578 if (info == stg_EMPTY_MVAR_info) {
1579 #if defined(THREADED_RTS)
1580 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1582 /* HACK: we need a pointer to pass back,
1583 * so we abuse NO_FINALIZER_closure
1585 RET_NP(0, stg_NO_FINALIZER_closure);
1588 /* we got the value... */
1589 val = StgMVar_value(mvar);
1591 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1593 /* There are putMVar(s) waiting...
1594 * wake up the first thread on the queue
1596 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1598 /* actually perform the putMVar for the thread that we just woke up */
1599 tso = StgMVar_head(mvar);
1600 PerformPut(tso,StgMVar_value(mvar));
1603 #if defined(GRAN) || defined(PAR)
1604 /* ToDo: check 2nd arg (mvar) is right */
1605 ("ptr" tso) = foreign "C" unblockOne(StgMVar_head(mvar) "ptr", mvar "ptr") [];
1606 StgMVar_head(mvar) = tso;
1608 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr",
1609 StgMVar_head(mvar) "ptr") [];
1610 StgMVar_head(mvar) = tso;
1613 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1614 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1616 #if defined(THREADED_RTS)
1617 unlockClosure(mvar, stg_FULL_MVAR_info);
1622 /* No further putMVars, MVar is now empty */
1623 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1624 #if defined(THREADED_RTS)
1625 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1627 SET_INFO(mvar,stg_EMPTY_MVAR_info);
1639 /* args: R1 = MVar, R2 = value */
1642 #if defined(THREADED_RTS)
1643 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1645 info = GET_INFO(mvar);
1648 if (info == stg_FULL_MVAR_info) {
1649 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1650 StgMVar_head(mvar) = CurrentTSO;
1652 StgTSO_link(StgMVar_tail(mvar)) = CurrentTSO;
1654 StgTSO_link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1655 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1656 StgTSO_block_info(CurrentTSO) = mvar;
1657 StgMVar_tail(mvar) = CurrentTSO;
1659 jump stg_block_putmvar;
1662 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1664 /* There are takeMVar(s) waiting: wake up the first one
1666 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1668 /* actually perform the takeMVar */
1669 tso = StgMVar_head(mvar);
1670 PerformTake(tso, R2);
1673 #if defined(GRAN) || defined(PAR)
1674 /* ToDo: check 2nd arg (mvar) is right */
1675 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr",mvar "ptr") [];
1676 StgMVar_head(mvar) = tso;
1678 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr") [];
1679 StgMVar_head(mvar) = tso;
1682 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1683 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1686 #if defined(THREADED_RTS)
1687 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1689 jump %ENTRY_CODE(Sp(0));
1693 /* No further takes, the MVar is now full. */
1694 StgMVar_value(mvar) = R2;
1696 #if defined(THREADED_RTS)
1697 unlockClosure(mvar, stg_FULL_MVAR_info);
1699 SET_INFO(mvar,stg_FULL_MVAR_info);
1701 jump %ENTRY_CODE(Sp(0));
1704 /* ToDo: yield afterward for better communication performance? */
1712 /* args: R1 = MVar, R2 = value */
1715 #if defined(THREADED_RTS)
1716 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1718 info = GET_INFO(mvar);
1721 if (info == stg_FULL_MVAR_info) {
1722 #if defined(THREADED_RTS)
1723 unlockClosure(mvar, stg_FULL_MVAR_info);
1728 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1730 /* There are takeMVar(s) waiting: wake up the first one
1732 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1734 /* actually perform the takeMVar */
1735 tso = StgMVar_head(mvar);
1736 PerformTake(tso, R2);
1739 #if defined(GRAN) || defined(PAR)
1740 /* ToDo: check 2nd arg (mvar) is right */
1741 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr",mvar "ptr") [];
1742 StgMVar_head(mvar) = tso;
1744 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr") [];
1745 StgMVar_head(mvar) = tso;
1748 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1749 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1752 #if defined(THREADED_RTS)
1753 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1758 /* No further takes, the MVar is now full. */
1759 StgMVar_value(mvar) = R2;
1761 #if defined(THREADED_RTS)
1762 unlockClosure(mvar, stg_FULL_MVAR_info);
1764 SET_INFO(mvar,stg_FULL_MVAR_info);
1769 /* ToDo: yield afterward for better communication performance? */
1773 /* -----------------------------------------------------------------------------
1774 Stable pointer primitives
1775 ------------------------------------------------------------------------- */
1777 makeStableNamezh_fast
1781 ALLOC_PRIM( SIZEOF_StgStableName, R1_PTR, makeStableNamezh_fast );
1783 (index) = foreign "C" lookupStableName(R1 "ptr") [];
1785 /* Is there already a StableName for this heap object?
1786 * stable_ptr_table is a pointer to an array of snEntry structs.
1788 if ( snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) == NULL ) {
1789 sn_obj = Hp - SIZEOF_StgStableName + WDS(1);
1790 SET_HDR(sn_obj, stg_STABLE_NAME_info, W_[CCCS]);
1791 StgStableName_sn(sn_obj) = index;
1792 snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) = sn_obj;
1794 sn_obj = snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry);
1801 makeStablePtrzh_fast
1805 MAYBE_GC(R1_PTR, makeStablePtrzh_fast);
1806 ("ptr" sp) = foreign "C" getStablePtr(R1 "ptr") [];
1810 deRefStablePtrzh_fast
1812 /* Args: R1 = the stable ptr */
1815 r = snEntry_addr(W_[stable_ptr_table] + sp*SIZEOF_snEntry);
1819 /* -----------------------------------------------------------------------------
1820 Bytecode object primitives
1821 ------------------------------------------------------------------------- */
1831 W_ bco, bitmap_arr, bytes, words;
1835 words = BYTES_TO_WDS(SIZEOF_StgBCO) + StgArrWords_words(bitmap_arr);
1838 ALLOC_PRIM( bytes, R1_PTR&R2_PTR&R3_PTR&R5_PTR, newBCOzh_fast );
1840 bco = Hp - bytes + WDS(1);
1841 SET_HDR(bco, stg_BCO_info, W_[CCCS]);
1843 StgBCO_instrs(bco) = R1;
1844 StgBCO_literals(bco) = R2;
1845 StgBCO_ptrs(bco) = R3;
1846 StgBCO_arity(bco) = HALF_W_(R4);
1847 StgBCO_size(bco) = HALF_W_(words);
1849 // Copy the arity/bitmap info into the BCO
1853 if (i < StgArrWords_words(bitmap_arr)) {
1854 StgBCO_bitmap(bco,i) = StgArrWords_payload(bitmap_arr,i);
1865 // R1 = the BCO# for the AP
1869 // This function is *only* used to wrap zero-arity BCOs in an
1870 // updatable wrapper (see ByteCodeLink.lhs). An AP thunk is always
1871 // saturated and always points directly to a FUN or BCO.
1872 ASSERT(%INFO_TYPE(%GET_STD_INFO(R1)) == HALF_W_(BCO) &&
1873 StgBCO_arity(R1) == HALF_W_(0));
1875 HP_CHK_GEN_TICKY(SIZEOF_StgAP, R1_PTR, mkApUpd0zh_fast);
1876 TICK_ALLOC_UP_THK(0, 0);
1877 CCCS_ALLOC(SIZEOF_StgAP);
1879 ap = Hp - SIZEOF_StgAP + WDS(1);
1880 SET_HDR(ap, stg_AP_info, W_[CCCS]);
1882 StgAP_n_args(ap) = HALF_W_(0);
1888 unpackClosurezh_fast
1890 /* args: R1 = closure to analyze */
1891 // TODO: Consider the absence of ptrs or nonptrs as a special case ?
1893 W_ info, ptrs, nptrs, p, ptrs_arr, nptrs_arr;
1894 info = %GET_STD_INFO(UNTAG(R1));
1896 // Some closures have non-standard layout, so we omit those here.
1898 type = TO_W_(%INFO_TYPE(info));
1899 switch [0 .. N_CLOSURE_TYPES] type {
1900 case THUNK_SELECTOR : {
1905 case THUNK, THUNK_1_0, THUNK_0_1, THUNK_2_0, THUNK_1_1,
1906 THUNK_0_2, THUNK_STATIC, AP, PAP, AP_STACK, BCO : {
1912 ptrs = TO_W_(%INFO_PTRS(info));
1913 nptrs = TO_W_(%INFO_NPTRS(info));
1918 W_ ptrs_arr_sz, nptrs_arr_sz;
1919 nptrs_arr_sz = SIZEOF_StgArrWords + WDS(nptrs);
1920 ptrs_arr_sz = SIZEOF_StgMutArrPtrs + WDS(ptrs);
1922 ALLOC_PRIM (ptrs_arr_sz + nptrs_arr_sz, R1_PTR, unpackClosurezh_fast);
1927 ptrs_arr = Hp - nptrs_arr_sz - ptrs_arr_sz + WDS(1);
1928 nptrs_arr = Hp - nptrs_arr_sz + WDS(1);
1930 SET_HDR(ptrs_arr, stg_MUT_ARR_PTRS_FROZEN_info, W_[CCCS]);
1931 StgMutArrPtrs_ptrs(ptrs_arr) = ptrs;
1935 W_[ptrs_arr + SIZEOF_StgMutArrPtrs + WDS(p)] = StgClosure_payload(clos,p);
1940 SET_HDR(nptrs_arr, stg_ARR_WORDS_info, W_[CCCS]);
1941 StgArrWords_words(nptrs_arr) = nptrs;
1945 W_[BYTE_ARR_CTS(nptrs_arr) + WDS(p)] = StgClosure_payload(clos, p+ptrs);
1949 RET_NPP(info, ptrs_arr, nptrs_arr);
1952 /* -----------------------------------------------------------------------------
1953 Thread I/O blocking primitives
1954 -------------------------------------------------------------------------- */
1956 /* Add a thread to the end of the blocked queue. (C-- version of the C
1957 * macro in Schedule.h).
1959 #define APPEND_TO_BLOCKED_QUEUE(tso) \
1960 ASSERT(StgTSO_link(tso) == END_TSO_QUEUE); \
1961 if (W_[blocked_queue_hd] == END_TSO_QUEUE) { \
1962 W_[blocked_queue_hd] = tso; \
1964 StgTSO_link(W_[blocked_queue_tl]) = tso; \
1966 W_[blocked_queue_tl] = tso;
1972 foreign "C" barf("waitRead# on threaded RTS") never returns;
1975 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
1976 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
1977 StgTSO_block_info(CurrentTSO) = R1;
1978 // No locking - we're not going to use this interface in the
1979 // threaded RTS anyway.
1980 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
1981 jump stg_block_noregs;
1989 foreign "C" barf("waitWrite# on threaded RTS") never returns;
1992 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
1993 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
1994 StgTSO_block_info(CurrentTSO) = R1;
1995 // No locking - we're not going to use this interface in the
1996 // threaded RTS anyway.
1997 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
1998 jump stg_block_noregs;
2003 STRING(stg_delayzh_malloc_str, "delayzh_fast")
2006 #ifdef mingw32_HOST_OS
2014 foreign "C" barf("delay# on threaded RTS") never returns;
2017 /* args: R1 (microsecond delay amount) */
2018 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2019 StgTSO_why_blocked(CurrentTSO) = BlockedOnDelay::I16;
2021 #ifdef mingw32_HOST_OS
2023 /* could probably allocate this on the heap instead */
2024 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2025 stg_delayzh_malloc_str);
2026 (reqID) = foreign "C" addDelayRequest(R1);
2027 StgAsyncIOResult_reqID(ares) = reqID;
2028 StgAsyncIOResult_len(ares) = 0;
2029 StgAsyncIOResult_errCode(ares) = 0;
2030 StgTSO_block_info(CurrentTSO) = ares;
2032 /* Having all async-blocked threads reside on the blocked_queue
2033 * simplifies matters, so change the status to OnDoProc put the
2034 * delayed thread on the blocked_queue.
2036 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2037 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2038 jump stg_block_async_void;
2044 (time) = foreign "C" getourtimeofday() [R1];
2045 divisor = TO_W_(RtsFlags_MiscFlags_tickInterval(RtsFlags))*1000;
2046 target = ((R1 + divisor - 1) / divisor) /* divide rounding up */
2047 + time + 1; /* Add 1 as getourtimeofday rounds down */
2048 StgTSO_block_info(CurrentTSO) = target;
2050 /* Insert the new thread in the sleeping queue. */
2052 t = W_[sleeping_queue];
2054 if (t != END_TSO_QUEUE && StgTSO_block_info(t) < target) {
2060 StgTSO_link(CurrentTSO) = t;
2062 W_[sleeping_queue] = CurrentTSO;
2064 StgTSO_link(prev) = CurrentTSO;
2066 jump stg_block_noregs;
2068 #endif /* !THREADED_RTS */
2072 #ifdef mingw32_HOST_OS
2073 STRING(stg_asyncReadzh_malloc_str, "asyncReadzh_fast")
2080 foreign "C" barf("asyncRead# on threaded RTS") never returns;
2083 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2084 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2085 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2087 /* could probably allocate this on the heap instead */
2088 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2089 stg_asyncReadzh_malloc_str)
2091 (reqID) = foreign "C" addIORequest(R1, 0/*FALSE*/,R2,R3,R4 "ptr") [];
2092 StgAsyncIOResult_reqID(ares) = reqID;
2093 StgAsyncIOResult_len(ares) = 0;
2094 StgAsyncIOResult_errCode(ares) = 0;
2095 StgTSO_block_info(CurrentTSO) = ares;
2096 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2097 jump stg_block_async;
2101 STRING(stg_asyncWritezh_malloc_str, "asyncWritezh_fast")
2108 foreign "C" barf("asyncWrite# on threaded RTS") never returns;
2111 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2112 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2113 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2115 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2116 stg_asyncWritezh_malloc_str)
2118 (reqID) = foreign "C" addIORequest(R1, 1/*TRUE*/,R2,R3,R4 "ptr") [];
2120 StgAsyncIOResult_reqID(ares) = reqID;
2121 StgAsyncIOResult_len(ares) = 0;
2122 StgAsyncIOResult_errCode(ares) = 0;
2123 StgTSO_block_info(CurrentTSO) = ares;
2124 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2125 jump stg_block_async;
2129 STRING(stg_asyncDoProczh_malloc_str, "asyncDoProczh_fast")
2136 foreign "C" barf("asyncDoProc# on threaded RTS") never returns;
2139 /* args: R1 = proc, R2 = param */
2140 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2141 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2143 /* could probably allocate this on the heap instead */
2144 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2145 stg_asyncDoProczh_malloc_str)
2147 (reqID) = foreign "C" addDoProcRequest(R1 "ptr",R2 "ptr") [];
2148 StgAsyncIOResult_reqID(ares) = reqID;
2149 StgAsyncIOResult_len(ares) = 0;
2150 StgAsyncIOResult_errCode(ares) = 0;
2151 StgTSO_block_info(CurrentTSO) = ares;
2152 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2153 jump stg_block_async;
2158 // noDuplicate# tries to ensure that none of the thunks under
2159 // evaluation by the current thread are also under evaluation by
2160 // another thread. It relies on *both* threads doing noDuplicate#;
2161 // the second one will get blocked if they are duplicating some work.
2164 SAVE_THREAD_STATE();
2165 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2166 foreign "C" threadPaused (MyCapability() "ptr", CurrentTSO "ptr") [];
2168 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
2169 jump stg_threadFinished;
2171 LOAD_THREAD_STATE();
2172 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2173 jump %ENTRY_CODE(Sp(0));
2177 getApStackValzh_fast
2179 W_ ap_stack, offset, val, ok;
2181 /* args: R1 = AP_STACK, R2 = offset */
2185 if (%INFO_PTR(ap_stack) == stg_AP_STACK_info) {
2187 val = StgAP_STACK_payload(ap_stack,offset);