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 * ---------------------------------------------------------------------------*/
39 import __gmpz_tdiv_qr;
40 import __gmpz_fdiv_qr;
41 import __gmpz_divexact;
46 import base_GHCziIOBase_NestedAtomically_closure;
47 import pthread_mutex_lock;
48 import pthread_mutex_unlock;
50 /*-----------------------------------------------------------------------------
53 Basically just new*Array - the others are all inline macros.
55 The size arg is always passed in R1, and the result returned in R1.
57 The slow entry point is for returning from a heap check, the saved
58 size argument must be re-loaded from the stack.
59 -------------------------------------------------------------------------- */
61 /* for objects that are *less* than the size of a word, make sure we
62 * round up to the nearest word for the size of the array.
67 W_ words, payload_words, n, p;
68 MAYBE_GC(NO_PTRS,newByteArrayzh_fast);
70 payload_words = ROUNDUP_BYTES_TO_WDS(n);
71 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
72 ("ptr" p) = foreign "C" allocateLocal(MyCapability() "ptr",words) [];
73 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
74 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
75 StgArrWords_words(p) = payload_words;
79 newPinnedByteArrayzh_fast
81 W_ words, payload_words, n, p;
83 MAYBE_GC(NO_PTRS,newPinnedByteArrayzh_fast);
85 payload_words = ROUNDUP_BYTES_TO_WDS(n);
87 // We want an 8-byte aligned array. allocatePinned() gives us
88 // 8-byte aligned memory by default, but we want to align the
89 // *goods* inside the ArrWords object, so we have to check the
90 // size of the ArrWords header and adjust our size accordingly.
91 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
92 if ((SIZEOF_StgArrWords & 7) != 0) {
96 ("ptr" p) = foreign "C" allocatePinned(words) [];
97 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
99 // Again, if the ArrWords header isn't a multiple of 8 bytes, we
100 // have to push the object forward one word so that the goods
101 // fall on an 8-byte boundary.
102 if ((SIZEOF_StgArrWords & 7) != 0) {
106 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
107 StgArrWords_words(p) = payload_words;
113 W_ words, n, init, arr, p;
114 /* Args: R1 = words, R2 = initialisation value */
117 MAYBE_GC(R2_PTR,newArrayzh_fast);
119 words = BYTES_TO_WDS(SIZEOF_StgMutArrPtrs) + n;
120 ("ptr" arr) = foreign "C" allocateLocal(MyCapability() "ptr",words) [R2];
121 TICK_ALLOC_PRIM(SIZEOF_StgMutArrPtrs, WDS(n), 0);
123 SET_HDR(arr, stg_MUT_ARR_PTRS_DIRTY_info, W_[CCCS]);
124 StgMutArrPtrs_ptrs(arr) = n;
126 // Initialise all elements of the the array with the value in R2
128 p = arr + SIZEOF_StgMutArrPtrs;
130 if (p < arr + WDS(words)) {
139 unsafeThawArrayzh_fast
141 // SUBTLETY TO DO WITH THE OLD GEN MUTABLE LIST
143 // A MUT_ARR_PTRS lives on the mutable list, but a MUT_ARR_PTRS_FROZEN
144 // normally doesn't. However, when we freeze a MUT_ARR_PTRS, we leave
145 // it on the mutable list for the GC to remove (removing something from
146 // the mutable list is not easy, because the mut_list is only singly-linked).
148 // So that we can tell whether a MUT_ARR_PTRS_FROZEN is on the mutable list,
149 // when we freeze it we set the info ptr to be MUT_ARR_PTRS_FROZEN0
150 // to indicate that it is still on the mutable list.
152 // So, when we thaw a MUT_ARR_PTRS_FROZEN, we must cope with two cases:
153 // either it is on a mut_list, or it isn't. We adopt the convention that
154 // the closure type is MUT_ARR_PTRS_FROZEN0 if it is on the mutable list,
155 // and MUT_ARR_PTRS_FROZEN otherwise. In fact it wouldn't matter if
156 // we put it on the mutable list more than once, but it would get scavenged
157 // multiple times during GC, which would be unnecessarily slow.
159 if (StgHeader_info(R1) != stg_MUT_ARR_PTRS_FROZEN0_info) {
160 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
161 recordMutable(R1, R1);
162 // must be done after SET_INFO, because it ASSERTs closure_MUTABLE()
165 SET_INFO(R1,stg_MUT_ARR_PTRS_DIRTY_info);
170 /* -----------------------------------------------------------------------------
172 -------------------------------------------------------------------------- */
177 /* Args: R1 = initialisation value */
179 ALLOC_PRIM( SIZEOF_StgMutVar, R1_PTR, newMutVarzh_fast);
181 mv = Hp - SIZEOF_StgMutVar + WDS(1);
182 SET_HDR(mv,stg_MUT_VAR_DIRTY_info,W_[CCCS]);
183 StgMutVar_var(mv) = R1;
188 atomicModifyMutVarzh_fast
191 /* Args: R1 :: MutVar#, R2 :: a -> (a,b) */
193 /* If x is the current contents of the MutVar#, then
194 We want to make the new contents point to
198 and the return value is
202 obviously we can share (f x).
204 z = [stg_ap_2 f x] (max (HS + 2) MIN_UPD_SIZE)
205 y = [stg_sel_0 z] (max (HS + 1) MIN_UPD_SIZE)
206 r = [stg_sel_1 z] (max (HS + 1) MIN_UPD_SIZE)
210 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
211 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),WDS(MIN_UPD_SIZE-1))
213 #define THUNK_1_SIZE (SIZEOF_StgThunkHeader + WDS(1))
214 #define TICK_ALLOC_THUNK_1() TICK_ALLOC_UP_THK(WDS(1),0)
218 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(MIN_UPD_SIZE))
219 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),WDS(MIN_UPD_SIZE-2))
221 #define THUNK_2_SIZE (SIZEOF_StgThunkHeader + WDS(2))
222 #define TICK_ALLOC_THUNK_2() TICK_ALLOC_UP_THK(WDS(2),0)
225 #define SIZE (THUNK_2_SIZE + THUNK_1_SIZE + THUNK_1_SIZE)
227 HP_CHK_GEN_TICKY(SIZE, R1_PTR & R2_PTR, atomicModifyMutVarzh_fast);
229 #if defined(THREADED_RTS)
230 foreign "C" ACQUIRE_LOCK(atomic_modify_mutvar_mutex "ptr") [R1,R2];
233 x = StgMutVar_var(R1);
235 TICK_ALLOC_THUNK_2();
236 CCCS_ALLOC(THUNK_2_SIZE);
237 z = Hp - THUNK_2_SIZE + WDS(1);
238 SET_HDR(z, stg_ap_2_upd_info, W_[CCCS]);
239 LDV_RECORD_CREATE(z);
240 StgThunk_payload(z,0) = R2;
241 StgThunk_payload(z,1) = x;
243 TICK_ALLOC_THUNK_1();
244 CCCS_ALLOC(THUNK_1_SIZE);
245 y = z - THUNK_1_SIZE;
246 SET_HDR(y, stg_sel_0_upd_info, W_[CCCS]);
247 LDV_RECORD_CREATE(y);
248 StgThunk_payload(y,0) = z;
250 StgMutVar_var(R1) = y;
251 foreign "C" dirty_MUT_VAR(BaseReg "ptr", R1 "ptr") [R1];
253 TICK_ALLOC_THUNK_1();
254 CCCS_ALLOC(THUNK_1_SIZE);
255 r = y - THUNK_1_SIZE;
256 SET_HDR(r, stg_sel_1_upd_info, W_[CCCS]);
257 LDV_RECORD_CREATE(r);
258 StgThunk_payload(r,0) = z;
260 #if defined(THREADED_RTS)
261 foreign "C" RELEASE_LOCK(atomic_modify_mutvar_mutex "ptr") [];
267 /* -----------------------------------------------------------------------------
268 Weak Pointer Primitives
269 -------------------------------------------------------------------------- */
271 STRING(stg_weak_msg,"New weak pointer at %p\n")
277 R3 = finalizer (or NULL)
282 R3 = stg_NO_FINALIZER_closure;
285 ALLOC_PRIM( SIZEOF_StgWeak, R1_PTR & R2_PTR & R3_PTR, mkWeakzh_fast );
287 w = Hp - SIZEOF_StgWeak + WDS(1);
288 SET_HDR(w, stg_WEAK_info, W_[CCCS]);
291 StgWeak_value(w) = R2;
292 StgWeak_finalizer(w) = R3;
294 StgWeak_link(w) = W_[weak_ptr_list];
295 W_[weak_ptr_list] = w;
297 IF_DEBUG(weak, foreign "C" debugBelch(stg_weak_msg,w) []);
312 if (GET_INFO(w) == stg_DEAD_WEAK_info) {
313 RET_NP(0,stg_NO_FINALIZER_closure);
319 // A weak pointer is inherently used, so we do not need to call
320 // LDV_recordDead_FILL_SLOP_DYNAMIC():
321 // LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
322 // or, LDV_recordDead():
323 // LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
324 // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
325 // large as weak pointers, so there is no need to fill the slop, either.
326 // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
330 // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
332 SET_INFO(w,stg_DEAD_WEAK_info);
333 LDV_RECORD_CREATE(w);
335 f = StgWeak_finalizer(w);
336 StgDeadWeak_link(w) = StgWeak_link(w);
338 /* return the finalizer */
339 if (f == stg_NO_FINALIZER_closure) {
340 RET_NP(0,stg_NO_FINALIZER_closure);
352 if (GET_INFO(w) == stg_WEAK_info) {
354 val = StgWeak_value(w);
362 /* -----------------------------------------------------------------------------
363 Arbitrary-precision Integer operations.
365 There are some assumptions in this code that mp_limb_t == W_. This is
366 the case for all the platforms that GHC supports, currently.
367 -------------------------------------------------------------------------- */
371 /* arguments: R1 = Int# */
373 W_ val, s, p; /* to avoid aliasing */
376 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, int2Integerzh_fast );
378 p = Hp - SIZEOF_StgArrWords;
379 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
380 StgArrWords_words(p) = 1;
382 /* mpz_set_si is inlined here, makes things simpler */
395 /* returns (# size :: Int#,
404 /* arguments: R1 = Word# */
406 W_ val, s, p; /* to avoid aliasing */
410 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, word2Integerzh_fast);
412 p = Hp - SIZEOF_StgArrWords;
413 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
414 StgArrWords_words(p) = 1;
423 /* returns (# size :: Int#,
424 data :: ByteArray# #)
431 * 'long long' primops for converting to/from Integers.
434 #ifdef SUPPORT_LONG_LONGS
436 int64ToIntegerzh_fast
438 /* arguments: L1 = Int64# */
441 W_ hi, lo, s, neg, words_needed, p;
446 hi = TO_W_(val >> 32);
449 if ( hi != 0 && hi != 0xFFFFFFFF ) {
452 // minimum is one word
456 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
457 NO_PTRS, int64ToIntegerzh_fast );
459 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
460 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
461 StgArrWords_words(p) = words_needed;
473 if ( words_needed == 2 ) {
481 } else /* val==0 */ {
489 /* returns (# size :: Int#,
490 data :: ByteArray# #)
494 word64ToIntegerzh_fast
496 /* arguments: L1 = Word64# */
499 W_ hi, lo, s, words_needed, p;
502 hi = TO_W_(val >> 32);
511 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
512 NO_PTRS, word64ToIntegerzh_fast );
514 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
515 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
516 StgArrWords_words(p) = words_needed;
526 } else /* val==0 */ {
531 /* returns (# size :: Int#,
532 data :: ByteArray# #)
539 #endif /* SUPPORT_LONG_LONGS */
541 /* ToDo: this is shockingly inefficient */
546 bits8 [SIZEOF_MP_INT];
551 bits8 [SIZEOF_MP_INT];
556 bits8 [SIZEOF_MP_INT];
561 bits8 [SIZEOF_MP_INT];
566 #define FETCH_MP_TEMP(X) \
568 X = BaseReg + (OFFSET_StgRegTable_r ## X);
570 #define FETCH_MP_TEMP(X) /* Nothing */
573 #define GMP_TAKE2_RET1(name,mp_fun) \
578 FETCH_MP_TEMP(mp_tmp1); \
579 FETCH_MP_TEMP(mp_tmp2); \
580 FETCH_MP_TEMP(mp_result1) \
581 FETCH_MP_TEMP(mp_result2); \
583 /* call doYouWantToGC() */ \
584 MAYBE_GC(R2_PTR & R4_PTR, name); \
591 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
592 MP_INT__mp_size(mp_tmp1) = (s1); \
593 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
594 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
595 MP_INT__mp_size(mp_tmp2) = (s2); \
596 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
598 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
600 /* Perform the operation */ \
601 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
603 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
604 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
607 #define GMP_TAKE1_RET1(name,mp_fun) \
612 FETCH_MP_TEMP(mp_tmp1); \
613 FETCH_MP_TEMP(mp_result1) \
615 /* call doYouWantToGC() */ \
616 MAYBE_GC(R2_PTR, name); \
621 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
622 MP_INT__mp_size(mp_tmp1) = (s1); \
623 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
625 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
627 /* Perform the operation */ \
628 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr") []; \
630 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
631 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
634 #define GMP_TAKE2_RET2(name,mp_fun) \
639 FETCH_MP_TEMP(mp_tmp1); \
640 FETCH_MP_TEMP(mp_tmp2); \
641 FETCH_MP_TEMP(mp_result1) \
642 FETCH_MP_TEMP(mp_result2) \
644 /* call doYouWantToGC() */ \
645 MAYBE_GC(R2_PTR & R4_PTR, name); \
652 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
653 MP_INT__mp_size(mp_tmp1) = (s1); \
654 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
655 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
656 MP_INT__mp_size(mp_tmp2) = (s2); \
657 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
659 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
660 foreign "C" __gmpz_init(mp_result2 "ptr") []; \
662 /* Perform the operation */ \
663 foreign "C" mp_fun(mp_result1 "ptr",mp_result2 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
665 RET_NPNP(TO_W_(MP_INT__mp_size(mp_result1)), \
666 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords, \
667 TO_W_(MP_INT__mp_size(mp_result2)), \
668 MP_INT__mp_d(mp_result2) - SIZEOF_StgArrWords); \
671 GMP_TAKE2_RET1(plusIntegerzh_fast, __gmpz_add)
672 GMP_TAKE2_RET1(minusIntegerzh_fast, __gmpz_sub)
673 GMP_TAKE2_RET1(timesIntegerzh_fast, __gmpz_mul)
674 GMP_TAKE2_RET1(gcdIntegerzh_fast, __gmpz_gcd)
675 GMP_TAKE2_RET1(quotIntegerzh_fast, __gmpz_tdiv_q)
676 GMP_TAKE2_RET1(remIntegerzh_fast, __gmpz_tdiv_r)
677 GMP_TAKE2_RET1(divExactIntegerzh_fast, __gmpz_divexact)
678 GMP_TAKE2_RET1(andIntegerzh_fast, __gmpz_and)
679 GMP_TAKE2_RET1(orIntegerzh_fast, __gmpz_ior)
680 GMP_TAKE2_RET1(xorIntegerzh_fast, __gmpz_xor)
681 GMP_TAKE1_RET1(complementIntegerzh_fast, __gmpz_com)
683 GMP_TAKE2_RET2(quotRemIntegerzh_fast, __gmpz_tdiv_qr)
684 GMP_TAKE2_RET2(divModIntegerzh_fast, __gmpz_fdiv_qr)
688 mp_tmp_w: W_; // NB. mp_tmp_w is really an here mp_limb_t
694 /* R1 = the first Int#; R2 = the second Int# */
696 FETCH_MP_TEMP(mp_tmp_w);
699 (r) = foreign "C" __gmpn_gcd_1(mp_tmp_w "ptr", 1, R2) [];
702 /* Result parked in R1, return via info-pointer at TOS */
703 jump %ENTRY_CODE(Sp(0));
709 /* R1 = s1; R2 = d1; R3 = the int */
711 (s1) = foreign "C" __gmpn_gcd_1( BYTE_ARR_CTS(R2) "ptr", R1, R3) [];
714 /* Result parked in R1, return via info-pointer at TOS */
715 jump %ENTRY_CODE(Sp(0));
721 /* R1 = s1; R2 = d1; R3 = the int */
722 W_ usize, vsize, v_digit, u_digit;
728 // paraphrased from __gmpz_cmp_si() in the GMP sources
729 if (%gt(v_digit,0)) {
732 if (%lt(v_digit,0)) {
738 if (usize != vsize) {
740 jump %ENTRY_CODE(Sp(0));
745 jump %ENTRY_CODE(Sp(0));
748 u_digit = W_[BYTE_ARR_CTS(R2)];
750 if (u_digit == v_digit) {
752 jump %ENTRY_CODE(Sp(0));
755 if (%gtu(u_digit,v_digit)) { // NB. unsigned: these are mp_limb_t's
761 jump %ENTRY_CODE(Sp(0));
766 /* R1 = s1; R2 = d1; R3 = s2; R4 = d2 */
767 W_ usize, vsize, size, up, vp;
770 // paraphrased from __gmpz_cmp() in the GMP sources
774 if (usize != vsize) {
776 jump %ENTRY_CODE(Sp(0));
781 jump %ENTRY_CODE(Sp(0));
784 if (%lt(usize,0)) { // NB. not <, which is unsigned
790 up = BYTE_ARR_CTS(R2);
791 vp = BYTE_ARR_CTS(R4);
793 (cmp) = foreign "C" __gmpn_cmp(up "ptr", vp "ptr", size) [];
795 if (cmp == 0 :: CInt) {
797 jump %ENTRY_CODE(Sp(0));
800 if (%lt(cmp,0 :: CInt) == %lt(usize,0)) {
805 /* Result parked in R1, return via info-pointer at TOS */
806 jump %ENTRY_CODE(Sp(0));
818 r = W_[R2 + SIZEOF_StgArrWords];
823 /* Result parked in R1, return via info-pointer at TOS */
825 jump %ENTRY_CODE(Sp(0));
837 r = W_[R2 + SIZEOF_StgArrWords];
842 /* Result parked in R1, return via info-pointer at TOS */
844 jump %ENTRY_CODE(Sp(0));
851 FETCH_MP_TEMP(mp_tmp1);
852 FETCH_MP_TEMP(mp_tmp_w);
854 /* arguments: F1 = Float# */
857 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, decodeFloatzh_fast );
859 /* Be prepared to tell Lennart-coded __decodeFloat
860 where mantissa._mp_d can be put (it does not care about the rest) */
861 p = Hp - SIZEOF_StgArrWords;
862 SET_HDR(p,stg_ARR_WORDS_info,W_[CCCS]);
863 StgArrWords_words(p) = 1;
864 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
866 /* Perform the operation */
867 foreign "C" __decodeFloat(mp_tmp1 "ptr",mp_tmp_w "ptr" ,arg) [];
869 /* returns: (Int# (expn), Int#, ByteArray#) */
870 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
873 #define DOUBLE_MANTISSA_SIZE SIZEOF_DOUBLE
874 #define ARR_SIZE (SIZEOF_StgArrWords + DOUBLE_MANTISSA_SIZE)
880 FETCH_MP_TEMP(mp_tmp1);
881 FETCH_MP_TEMP(mp_tmp_w);
883 /* arguments: D1 = Double# */
886 ALLOC_PRIM( ARR_SIZE, NO_PTRS, decodeDoublezh_fast );
888 /* Be prepared to tell Lennart-coded __decodeDouble
889 where mantissa.d can be put (it does not care about the rest) */
890 p = Hp - ARR_SIZE + WDS(1);
891 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
892 StgArrWords_words(p) = BYTES_TO_WDS(DOUBLE_MANTISSA_SIZE);
893 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
895 /* Perform the operation */
896 foreign "C" __decodeDouble(mp_tmp1 "ptr", mp_tmp_w "ptr",arg) [];
898 /* returns: (Int# (expn), Int#, ByteArray#) */
899 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
902 /* -----------------------------------------------------------------------------
903 * Concurrency primitives
904 * -------------------------------------------------------------------------- */
908 /* args: R1 = closure to spark */
910 MAYBE_GC(R1_PTR, forkzh_fast);
916 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
917 RtsFlags_GcFlags_initialStkSize(RtsFlags),
919 foreign "C" scheduleThread(MyCapability() "ptr", threadid "ptr") [];
921 // switch at the earliest opportunity
922 CInt[context_switch] = 1 :: CInt;
929 /* args: R1 = cpu, R2 = closure to spark */
931 MAYBE_GC(R2_PTR, forkOnzh_fast);
939 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
940 RtsFlags_GcFlags_initialStkSize(RtsFlags),
942 foreign "C" scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr") [];
944 // switch at the earliest opportunity
945 CInt[context_switch] = 1 :: CInt;
952 jump stg_yield_noregs;
967 foreign "C" labelThread(R1 "ptr", R2 "ptr") [];
969 jump %ENTRY_CODE(Sp(0));
972 isCurrentThreadBoundzh_fast
976 (r) = foreign "C" isThreadBound(CurrentTSO) [];
981 /* -----------------------------------------------------------------------------
983 * -------------------------------------------------------------------------- */
987 #define IF_NOT_REG_R1(x)
990 #define IF_NOT_REG_R1(x) x
993 // Catch retry frame ------------------------------------------------------------
995 INFO_TABLE_RET(stg_catch_retry_frame, CATCH_RETRY_FRAME,
996 #if defined(PROFILING)
997 W_ unused1, W_ unused2,
999 W_ unused3, "ptr" W_ unused4, "ptr" W_ unused5)
1001 W_ r, frame, trec, outer;
1002 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1005 trec = StgTSO_trec(CurrentTSO);
1006 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1007 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1009 /* Succeeded (either first branch or second branch) */
1010 StgTSO_trec(CurrentTSO) = outer;
1011 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1012 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1013 jump %ENTRY_CODE(Sp(SP_OFF));
1015 /* Did not commit: re-execute */
1017 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1018 StgTSO_trec(CurrentTSO) = new_trec;
1019 if (StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1020 R1 = StgCatchRetryFrame_alt_code(frame);
1022 R1 = StgCatchRetryFrame_first_code(frame);
1029 // Atomically frame ------------------------------------------------------------
1031 INFO_TABLE_RET(stg_atomically_frame, ATOMICALLY_FRAME,
1032 #if defined(PROFILING)
1033 W_ unused1, W_ unused2,
1035 "ptr" W_ unused3, "ptr" W_ unused4)
1037 W_ frame, trec, valid, next_invariant, q, outer;
1038 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1041 trec = StgTSO_trec(CurrentTSO);
1042 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1044 if (outer == NO_TREC) {
1045 /* First time back at the atomically frame -- pick up invariants */
1046 ("ptr" q) = foreign "C" stmGetInvariantsToCheck(MyCapability() "ptr", trec "ptr") [];
1047 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1050 /* Second/subsequent time back at the atomically frame -- abort the
1051 * tx that's checking the invariant and move on to the next one */
1052 StgTSO_trec(CurrentTSO) = outer;
1053 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1054 StgInvariantCheckQueue_my_execution(q) = trec;
1055 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1056 /* Don't free trec -- it's linked from q and will be stashed in the
1057 * invariant if we eventually commit. */
1058 q = StgInvariantCheckQueue_next_queue_entry(q);
1059 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1063 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1065 if (q != END_INVARIANT_CHECK_QUEUE) {
1066 /* We can't commit yet: another invariant to check */
1067 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [];
1068 StgTSO_trec(CurrentTSO) = trec;
1070 next_invariant = StgInvariantCheckQueue_invariant(q);
1071 R1 = StgAtomicInvariant_code(next_invariant);
1076 /* We've got no more invariants to check, try to commit */
1077 (valid) = foreign "C" stmCommitTransaction(MyCapability() "ptr", trec "ptr") [];
1079 /* Transaction was valid: commit succeeded */
1080 StgTSO_trec(CurrentTSO) = NO_TREC;
1081 Sp = Sp + SIZEOF_StgAtomicallyFrame;
1082 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1083 jump %ENTRY_CODE(Sp(SP_OFF));
1085 /* Transaction was not valid: try again */
1086 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1087 StgTSO_trec(CurrentTSO) = trec;
1088 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1089 R1 = StgAtomicallyFrame_code(frame);
1095 INFO_TABLE_RET(stg_atomically_waiting_frame, ATOMICALLY_FRAME,
1096 #if defined(PROFILING)
1097 W_ unused1, W_ unused2,
1099 "ptr" W_ unused3, "ptr" W_ unused4)
1101 W_ frame, trec, valid;
1102 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1106 /* The TSO is currently waiting: should we stop waiting? */
1107 (valid) = foreign "C" stmReWait(MyCapability() "ptr", CurrentTSO "ptr") [];
1109 /* Previous attempt is still valid: no point trying again yet */
1110 IF_NOT_REG_R1(Sp_adj(-2);
1111 Sp(1) = stg_NO_FINALIZER_closure;
1112 Sp(0) = stg_ut_1_0_unreg_info;)
1113 jump stg_block_noregs;
1115 /* Previous attempt is no longer valid: try again */
1116 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1117 StgTSO_trec(CurrentTSO) = trec;
1118 StgHeader_info(frame) = stg_atomically_frame_info;
1119 R1 = StgAtomicallyFrame_code(frame);
1124 // STM catch frame --------------------------------------------------------------
1132 /* Catch frames are very similar to update frames, but when entering
1133 * one we just pop the frame off the stack and perform the correct
1134 * kind of return to the activation record underneath us on the stack.
1137 INFO_TABLE_RET(stg_catch_stm_frame, CATCH_STM_FRAME,
1138 #if defined(PROFILING)
1139 W_ unused1, W_ unused2,
1141 "ptr" W_ unused3, "ptr" W_ unused4)
1143 IF_NOT_REG_R1(W_ rval; rval = Sp(0); Sp_adj(1); )
1144 W_ r, frame, trec, outer;
1146 trec = StgTSO_trec(CurrentTSO);
1147 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1148 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1150 /* Commit succeeded */
1151 StgTSO_trec(CurrentTSO) = outer;
1152 Sp = Sp + SIZEOF_StgCatchSTMFrame;
1153 IF_NOT_REG_R1(Sp_adj(-1); Sp(0) = rval;)
1158 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1159 StgTSO_trec(CurrentTSO) = new_trec;
1160 R1 = StgCatchSTMFrame_code(frame);
1166 // Primop definition ------------------------------------------------------------
1174 // stmStartTransaction may allocate
1175 MAYBE_GC (R1_PTR, atomicallyzh_fast);
1177 /* Args: R1 = m :: STM a */
1178 STK_CHK_GEN(SIZEOF_StgAtomicallyFrame + WDS(1), R1_PTR, atomicallyzh_fast);
1180 old_trec = StgTSO_trec(CurrentTSO);
1182 /* Nested transactions are not allowed; raise an exception */
1183 if (old_trec != NO_TREC) {
1184 R1 = base_GHCziIOBase_NestedAtomically_closure;
1188 /* Set up the atomically frame */
1189 Sp = Sp - SIZEOF_StgAtomicallyFrame;
1192 SET_HDR(frame,stg_atomically_frame_info, W_[CCCS]);
1193 StgAtomicallyFrame_code(frame) = R1;
1194 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1196 /* Start the memory transcation */
1197 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", old_trec "ptr") [R1];
1198 StgTSO_trec(CurrentTSO) = new_trec;
1200 /* Apply R1 to the realworld token */
1209 /* Args: R1 :: STM a */
1210 /* Args: R2 :: Exception -> STM a */
1211 STK_CHK_GEN(SIZEOF_StgCatchSTMFrame + WDS(1), R1_PTR & R2_PTR, catchSTMzh_fast);
1213 /* Set up the catch frame */
1214 Sp = Sp - SIZEOF_StgCatchSTMFrame;
1217 SET_HDR(frame, stg_catch_stm_frame_info, W_[CCCS]);
1218 StgCatchSTMFrame_handler(frame) = R2;
1219 StgCatchSTMFrame_code(frame) = R1;
1221 /* Start a nested transaction to run the body of the try block in */
1224 cur_trec = StgTSO_trec(CurrentTSO);
1225 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", cur_trec "ptr");
1226 StgTSO_trec(CurrentTSO) = new_trec;
1228 /* Apply R1 to the realworld token */
1239 // stmStartTransaction may allocate
1240 MAYBE_GC (R1_PTR & R2_PTR, catchRetryzh_fast);
1242 /* Args: R1 :: STM a */
1243 /* Args: R2 :: STM a */
1244 STK_CHK_GEN(SIZEOF_StgCatchRetryFrame + WDS(1), R1_PTR & R2_PTR, catchRetryzh_fast);
1246 /* Start a nested transaction within which to run the first code */
1247 trec = StgTSO_trec(CurrentTSO);
1248 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [R1,R2];
1249 StgTSO_trec(CurrentTSO) = new_trec;
1251 /* Set up the catch-retry frame */
1252 Sp = Sp - SIZEOF_StgCatchRetryFrame;
1255 SET_HDR(frame, stg_catch_retry_frame_info, W_[CCCS]);
1256 StgCatchRetryFrame_running_alt_code(frame) = 0 :: CInt; // false;
1257 StgCatchRetryFrame_first_code(frame) = R1;
1258 StgCatchRetryFrame_alt_code(frame) = R2;
1260 /* Apply R1 to the realworld token */
1273 MAYBE_GC (NO_PTRS, retryzh_fast); // STM operations may allocate
1275 // Find the enclosing ATOMICALLY_FRAME or CATCH_RETRY_FRAME
1277 StgTSO_sp(CurrentTSO) = Sp;
1278 (frame_type) = foreign "C" findRetryFrameHelper(CurrentTSO "ptr") [];
1279 Sp = StgTSO_sp(CurrentTSO);
1281 trec = StgTSO_trec(CurrentTSO);
1282 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1284 if (frame_type == CATCH_RETRY_FRAME) {
1285 // The retry reaches a CATCH_RETRY_FRAME before the atomic frame
1286 ASSERT(outer != NO_TREC);
1287 // Abort the transaction attempting the current branch
1288 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1289 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1290 if (!StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1291 // Retry in the first branch: try the alternative
1292 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1293 StgTSO_trec(CurrentTSO) = trec;
1294 StgCatchRetryFrame_running_alt_code(frame) = 1 :: CInt; // true;
1295 R1 = StgCatchRetryFrame_alt_code(frame);
1298 // Retry in the alternative code: propagate the retry
1299 StgTSO_trec(CurrentTSO) = outer;
1300 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1301 goto retry_pop_stack;
1305 // We've reached the ATOMICALLY_FRAME: attempt to wait
1306 ASSERT(frame_type == ATOMICALLY_FRAME);
1307 if (outer != NO_TREC) {
1308 // We called retry while checking invariants, so abort the current
1309 // invariant check (merging its TVar accesses into the parents read
1310 // set so we'll wait on them)
1311 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1312 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1314 StgTSO_trec(CurrentTSO) = trec;
1315 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1317 ASSERT(outer == NO_TREC);
1319 (r) = foreign "C" stmWait(MyCapability() "ptr", CurrentTSO "ptr", trec "ptr") [];
1321 // Transaction was valid: stmWait put us on the TVars' queues, we now block
1322 StgHeader_info(frame) = stg_atomically_waiting_frame_info;
1324 // Fix up the stack in the unregisterised case: the return convention is different.
1325 IF_NOT_REG_R1(Sp_adj(-2);
1326 Sp(1) = stg_NO_FINALIZER_closure;
1327 Sp(0) = stg_ut_1_0_unreg_info;)
1328 R3 = trec; // passing to stmWaitUnblock()
1329 jump stg_block_stmwait;
1331 // Transaction was not valid: retry immediately
1332 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1333 StgTSO_trec(CurrentTSO) = trec;
1334 R1 = StgAtomicallyFrame_code(frame);
1345 /* Args: R1 = invariant closure */
1346 MAYBE_GC (R1_PTR, checkzh_fast);
1348 trec = StgTSO_trec(CurrentTSO);
1350 foreign "C" stmAddInvariantToCheck(MyCapability() "ptr",
1354 jump %ENTRY_CODE(Sp(0));
1363 /* Args: R1 = initialisation value */
1365 MAYBE_GC (R1_PTR, newTVarzh_fast);
1367 ("ptr" tv) = foreign "C" stmNewTVar(MyCapability() "ptr", new_value "ptr") [];
1378 /* Args: R1 = TVar closure */
1380 MAYBE_GC (R1_PTR, readTVarzh_fast); // Call to stmReadTVar may allocate
1381 trec = StgTSO_trec(CurrentTSO);
1383 ("ptr" result) = foreign "C" stmReadTVar(MyCapability() "ptr", trec "ptr", tvar "ptr") [];
1395 /* Args: R1 = TVar closure */
1396 /* R2 = New value */
1398 MAYBE_GC (R1_PTR & R2_PTR, writeTVarzh_fast); // Call to stmWriteTVar may allocate
1399 trec = StgTSO_trec(CurrentTSO);
1402 foreign "C" stmWriteTVar(MyCapability() "ptr", trec "ptr", tvar "ptr", new_value "ptr") [];
1404 jump %ENTRY_CODE(Sp(0));
1408 /* -----------------------------------------------------------------------------
1411 * take & putMVar work as follows. Firstly, an important invariant:
1413 * If the MVar is full, then the blocking queue contains only
1414 * threads blocked on putMVar, and if the MVar is empty then the
1415 * blocking queue contains only threads blocked on takeMVar.
1418 * MVar empty : then add ourselves to the blocking queue
1419 * MVar full : remove the value from the MVar, and
1420 * blocking queue empty : return
1421 * blocking queue non-empty : perform the first blocked putMVar
1422 * from the queue, and wake up the
1423 * thread (MVar is now full again)
1425 * putMVar is just the dual of the above algorithm.
1427 * How do we "perform a putMVar"? Well, we have to fiddle around with
1428 * the stack of the thread waiting to do the putMVar. See
1429 * stg_block_putmvar and stg_block_takemvar in HeapStackCheck.c for
1430 * the stack layout, and the PerformPut and PerformTake macros below.
1432 * It is important that a blocked take or put is woken up with the
1433 * take/put already performed, because otherwise there would be a
1434 * small window of vulnerability where the thread could receive an
1435 * exception and never perform its take or put, and we'd end up with a
1438 * -------------------------------------------------------------------------- */
1442 /* args: R1 = MVar closure */
1444 if (GET_INFO(R1) == stg_EMPTY_MVAR_info) {
1456 ALLOC_PRIM ( SIZEOF_StgMVar, NO_PTRS, newMVarzh_fast );
1458 mvar = Hp - SIZEOF_StgMVar + WDS(1);
1459 SET_HDR(mvar,stg_EMPTY_MVAR_info,W_[CCCS]);
1460 StgMVar_head(mvar) = stg_END_TSO_QUEUE_closure;
1461 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1462 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1467 /* If R1 isn't available, pass it on the stack */
1469 #define PerformTake(tso, value) \
1470 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1471 W_[StgTSO_sp(tso) + WDS(0)] = stg_gc_unpt_r1_info;
1473 #define PerformTake(tso, value) \
1474 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1475 W_[StgTSO_sp(tso) + WDS(0)] = stg_ut_1_0_unreg_info;
1478 #define PerformPut(tso,lval) \
1479 StgTSO_sp(tso) = StgTSO_sp(tso) + WDS(3); \
1480 lval = W_[StgTSO_sp(tso) - WDS(1)];
1484 W_ mvar, val, info, tso;
1486 /* args: R1 = MVar closure */
1489 #if defined(THREADED_RTS)
1490 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1492 info = GET_INFO(mvar);
1495 /* If the MVar is empty, put ourselves on its blocking queue,
1496 * and wait until we're woken up.
1498 if (info == stg_EMPTY_MVAR_info) {
1499 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1500 StgMVar_head(mvar) = CurrentTSO;
1502 StgTSO_link(StgMVar_tail(mvar)) = CurrentTSO;
1504 StgTSO_link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1505 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1506 StgTSO_block_info(CurrentTSO) = mvar;
1507 StgMVar_tail(mvar) = CurrentTSO;
1509 jump stg_block_takemvar;
1512 /* we got the value... */
1513 val = StgMVar_value(mvar);
1515 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure)
1517 /* There are putMVar(s) waiting...
1518 * wake up the first thread on the queue
1520 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1522 /* actually perform the putMVar for the thread that we just woke up */
1523 tso = StgMVar_head(mvar);
1524 PerformPut(tso,StgMVar_value(mvar));
1527 #if defined(GRAN) || defined(PAR)
1528 /* ToDo: check 2nd arg (mvar) is right */
1529 ("ptr" tso) = foreign "C" unblockOne(StgMVar_head(mvar),mvar) [];
1530 StgMVar_head(mvar) = tso;
1532 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr",
1533 StgMVar_head(mvar) "ptr") [];
1534 StgMVar_head(mvar) = tso;
1537 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1538 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1541 #if defined(THREADED_RTS)
1542 unlockClosure(mvar, stg_FULL_MVAR_info);
1548 /* No further putMVars, MVar is now empty */
1549 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1551 #if defined(THREADED_RTS)
1552 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1554 SET_INFO(mvar,stg_EMPTY_MVAR_info);
1564 W_ mvar, val, info, tso;
1566 /* args: R1 = MVar closure */
1570 #if defined(THREADED_RTS)
1571 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1573 info = GET_INFO(mvar);
1576 if (info == stg_EMPTY_MVAR_info) {
1577 #if defined(THREADED_RTS)
1578 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1580 /* HACK: we need a pointer to pass back,
1581 * so we abuse NO_FINALIZER_closure
1583 RET_NP(0, stg_NO_FINALIZER_closure);
1586 /* we got the value... */
1587 val = StgMVar_value(mvar);
1589 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1591 /* There are putMVar(s) waiting...
1592 * wake up the first thread on the queue
1594 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1596 /* actually perform the putMVar for the thread that we just woke up */
1597 tso = StgMVar_head(mvar);
1598 PerformPut(tso,StgMVar_value(mvar));
1601 #if defined(GRAN) || defined(PAR)
1602 /* ToDo: check 2nd arg (mvar) is right */
1603 ("ptr" tso) = foreign "C" unblockOne(StgMVar_head(mvar) "ptr", mvar "ptr") [];
1604 StgMVar_head(mvar) = tso;
1606 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr",
1607 StgMVar_head(mvar) "ptr") [];
1608 StgMVar_head(mvar) = tso;
1611 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1612 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1614 #if defined(THREADED_RTS)
1615 unlockClosure(mvar, stg_FULL_MVAR_info);
1620 /* No further putMVars, MVar is now empty */
1621 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1622 #if defined(THREADED_RTS)
1623 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1625 SET_INFO(mvar,stg_EMPTY_MVAR_info);
1637 /* args: R1 = MVar, R2 = value */
1640 #if defined(THREADED_RTS)
1641 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1643 info = GET_INFO(mvar);
1646 if (info == stg_FULL_MVAR_info) {
1647 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1648 StgMVar_head(mvar) = CurrentTSO;
1650 StgTSO_link(StgMVar_tail(mvar)) = CurrentTSO;
1652 StgTSO_link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1653 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1654 StgTSO_block_info(CurrentTSO) = mvar;
1655 StgMVar_tail(mvar) = CurrentTSO;
1657 jump stg_block_putmvar;
1660 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1662 /* There are takeMVar(s) waiting: wake up the first one
1664 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1666 /* actually perform the takeMVar */
1667 tso = StgMVar_head(mvar);
1668 PerformTake(tso, R2);
1671 #if defined(GRAN) || defined(PAR)
1672 /* ToDo: check 2nd arg (mvar) is right */
1673 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr",mvar "ptr") [];
1674 StgMVar_head(mvar) = tso;
1676 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr") [];
1677 StgMVar_head(mvar) = tso;
1680 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1681 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1684 #if defined(THREADED_RTS)
1685 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1687 jump %ENTRY_CODE(Sp(0));
1691 /* No further takes, the MVar is now full. */
1692 StgMVar_value(mvar) = R2;
1694 #if defined(THREADED_RTS)
1695 unlockClosure(mvar, stg_FULL_MVAR_info);
1697 SET_INFO(mvar,stg_FULL_MVAR_info);
1699 jump %ENTRY_CODE(Sp(0));
1702 /* ToDo: yield afterward for better communication performance? */
1710 /* args: R1 = MVar, R2 = value */
1713 #if defined(THREADED_RTS)
1714 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1716 info = GET_INFO(mvar);
1719 if (info == stg_FULL_MVAR_info) {
1720 #if defined(THREADED_RTS)
1721 unlockClosure(mvar, stg_FULL_MVAR_info);
1726 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1728 /* There are takeMVar(s) waiting: wake up the first one
1730 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1732 /* actually perform the takeMVar */
1733 tso = StgMVar_head(mvar);
1734 PerformTake(tso, R2);
1737 #if defined(GRAN) || defined(PAR)
1738 /* ToDo: check 2nd arg (mvar) is right */
1739 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr",mvar "ptr") [];
1740 StgMVar_head(mvar) = tso;
1742 ("ptr" tso) = foreign "C" unblockOne(MyCapability() "ptr", StgMVar_head(mvar) "ptr") [];
1743 StgMVar_head(mvar) = tso;
1746 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1747 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1750 #if defined(THREADED_RTS)
1751 unlockClosure(mvar, stg_EMPTY_MVAR_info);
1756 /* No further takes, the MVar is now full. */
1757 StgMVar_value(mvar) = R2;
1759 #if defined(THREADED_RTS)
1760 unlockClosure(mvar, stg_FULL_MVAR_info);
1762 SET_INFO(mvar,stg_FULL_MVAR_info);
1767 /* ToDo: yield afterward for better communication performance? */
1771 /* -----------------------------------------------------------------------------
1772 Stable pointer primitives
1773 ------------------------------------------------------------------------- */
1775 makeStableNamezh_fast
1779 ALLOC_PRIM( SIZEOF_StgStableName, R1_PTR, makeStableNamezh_fast );
1781 (index) = foreign "C" lookupStableName(R1 "ptr") [];
1783 /* Is there already a StableName for this heap object?
1784 * stable_ptr_table is a pointer to an array of snEntry structs.
1786 if ( snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) == NULL ) {
1787 sn_obj = Hp - SIZEOF_StgStableName + WDS(1);
1788 SET_HDR(sn_obj, stg_STABLE_NAME_info, W_[CCCS]);
1789 StgStableName_sn(sn_obj) = index;
1790 snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) = sn_obj;
1792 sn_obj = snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry);
1799 makeStablePtrzh_fast
1803 MAYBE_GC(R1_PTR, makeStablePtrzh_fast);
1804 ("ptr" sp) = foreign "C" getStablePtr(R1 "ptr") [];
1808 deRefStablePtrzh_fast
1810 /* Args: R1 = the stable ptr */
1813 r = snEntry_addr(W_[stable_ptr_table] + sp*SIZEOF_snEntry);
1817 /* -----------------------------------------------------------------------------
1818 Bytecode object primitives
1819 ------------------------------------------------------------------------- */
1829 W_ bco, bitmap_arr, bytes, words;
1833 words = BYTES_TO_WDS(SIZEOF_StgBCO) + StgArrWords_words(bitmap_arr);
1836 ALLOC_PRIM( bytes, R1_PTR&R2_PTR&R3_PTR&R5_PTR, newBCOzh_fast );
1838 bco = Hp - bytes + WDS(1);
1839 SET_HDR(bco, stg_BCO_info, W_[CCCS]);
1841 StgBCO_instrs(bco) = R1;
1842 StgBCO_literals(bco) = R2;
1843 StgBCO_ptrs(bco) = R3;
1844 StgBCO_arity(bco) = HALF_W_(R4);
1845 StgBCO_size(bco) = HALF_W_(words);
1847 // Copy the arity/bitmap info into the BCO
1851 if (i < StgArrWords_words(bitmap_arr)) {
1852 StgBCO_bitmap(bco,i) = StgArrWords_payload(bitmap_arr,i);
1863 // R1 = the BCO# for the AP
1867 // This function is *only* used to wrap zero-arity BCOs in an
1868 // updatable wrapper (see ByteCodeLink.lhs). An AP thunk is always
1869 // saturated and always points directly to a FUN or BCO.
1870 ASSERT(%INFO_TYPE(%GET_STD_INFO(R1)) == HALF_W_(BCO) &&
1871 StgBCO_arity(R1) == HALF_W_(0));
1873 HP_CHK_GEN_TICKY(SIZEOF_StgAP, R1_PTR, mkApUpd0zh_fast);
1874 TICK_ALLOC_UP_THK(0, 0);
1875 CCCS_ALLOC(SIZEOF_StgAP);
1877 ap = Hp - SIZEOF_StgAP + WDS(1);
1878 SET_HDR(ap, stg_AP_info, W_[CCCS]);
1880 StgAP_n_args(ap) = HALF_W_(0);
1886 unpackClosurezh_fast
1888 /* args: R1 = closure to analyze */
1889 // TODO: Consider the absence of ptrs or nonptrs as a special case ?
1891 W_ info, ptrs, nptrs, p, ptrs_arr, nptrs_arr;
1892 info = %GET_STD_INFO(UNTAG(R1));
1894 // Some closures have non-standard layout, so we omit those here.
1896 type = TO_W_(%INFO_TYPE(info));
1897 switch [0 .. N_CLOSURE_TYPES] type {
1898 case THUNK_SELECTOR : {
1903 case THUNK, THUNK_1_0, THUNK_0_1, THUNK_2_0, THUNK_1_1,
1904 THUNK_0_2, THUNK_STATIC, AP, PAP, AP_STACK, BCO : {
1910 ptrs = TO_W_(%INFO_PTRS(info));
1911 nptrs = TO_W_(%INFO_NPTRS(info));
1916 W_ ptrs_arr_sz, nptrs_arr_sz;
1917 nptrs_arr_sz = SIZEOF_StgArrWords + WDS(nptrs);
1918 ptrs_arr_sz = SIZEOF_StgMutArrPtrs + WDS(ptrs);
1920 ALLOC_PRIM (ptrs_arr_sz + nptrs_arr_sz, R1_PTR, unpackClosurezh_fast);
1925 ptrs_arr = Hp - nptrs_arr_sz - ptrs_arr_sz + WDS(1);
1926 nptrs_arr = Hp - nptrs_arr_sz + WDS(1);
1928 SET_HDR(ptrs_arr, stg_MUT_ARR_PTRS_FROZEN_info, W_[CCCS]);
1929 StgMutArrPtrs_ptrs(ptrs_arr) = ptrs;
1933 W_[ptrs_arr + SIZEOF_StgMutArrPtrs + WDS(p)] = StgClosure_payload(clos,p);
1938 SET_HDR(nptrs_arr, stg_ARR_WORDS_info, W_[CCCS]);
1939 StgArrWords_words(nptrs_arr) = nptrs;
1943 W_[BYTE_ARR_CTS(nptrs_arr) + WDS(p)] = StgClosure_payload(clos, p+ptrs);
1947 RET_NPP(info, ptrs_arr, nptrs_arr);
1950 /* -----------------------------------------------------------------------------
1951 Thread I/O blocking primitives
1952 -------------------------------------------------------------------------- */
1954 /* Add a thread to the end of the blocked queue. (C-- version of the C
1955 * macro in Schedule.h).
1957 #define APPEND_TO_BLOCKED_QUEUE(tso) \
1958 ASSERT(StgTSO_link(tso) == END_TSO_QUEUE); \
1959 if (W_[blocked_queue_hd] == END_TSO_QUEUE) { \
1960 W_[blocked_queue_hd] = tso; \
1962 StgTSO_link(W_[blocked_queue_tl]) = tso; \
1964 W_[blocked_queue_tl] = tso;
1970 foreign "C" barf("waitRead# on threaded RTS");
1973 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
1974 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
1975 StgTSO_block_info(CurrentTSO) = R1;
1976 // No locking - we're not going to use this interface in the
1977 // threaded RTS anyway.
1978 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
1979 jump stg_block_noregs;
1987 foreign "C" barf("waitWrite# on threaded RTS");
1990 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
1991 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
1992 StgTSO_block_info(CurrentTSO) = R1;
1993 // No locking - we're not going to use this interface in the
1994 // threaded RTS anyway.
1995 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
1996 jump stg_block_noregs;
2001 STRING(stg_delayzh_malloc_str, "delayzh_fast")
2004 #ifdef mingw32_HOST_OS
2012 foreign "C" barf("delay# on threaded RTS");
2015 /* args: R1 (microsecond delay amount) */
2016 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2017 StgTSO_why_blocked(CurrentTSO) = BlockedOnDelay::I16;
2019 #ifdef mingw32_HOST_OS
2021 /* could probably allocate this on the heap instead */
2022 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2023 stg_delayzh_malloc_str);
2024 (reqID) = foreign "C" addDelayRequest(R1);
2025 StgAsyncIOResult_reqID(ares) = reqID;
2026 StgAsyncIOResult_len(ares) = 0;
2027 StgAsyncIOResult_errCode(ares) = 0;
2028 StgTSO_block_info(CurrentTSO) = ares;
2030 /* Having all async-blocked threads reside on the blocked_queue
2031 * simplifies matters, so change the status to OnDoProc put the
2032 * delayed thread on the blocked_queue.
2034 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2035 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2036 jump stg_block_async_void;
2042 (time) = foreign "C" getourtimeofday() [R1];
2043 divisor = TO_W_(RtsFlags_MiscFlags_tickInterval(RtsFlags))*1000;
2044 target = ((R1 + divisor - 1) / divisor) /* divide rounding up */
2045 + time + 1; /* Add 1 as getourtimeofday rounds down */
2046 StgTSO_block_info(CurrentTSO) = target;
2048 /* Insert the new thread in the sleeping queue. */
2050 t = W_[sleeping_queue];
2052 if (t != END_TSO_QUEUE && StgTSO_block_info(t) < target) {
2058 StgTSO_link(CurrentTSO) = t;
2060 W_[sleeping_queue] = CurrentTSO;
2062 StgTSO_link(prev) = CurrentTSO;
2064 jump stg_block_noregs;
2066 #endif /* !THREADED_RTS */
2070 #ifdef mingw32_HOST_OS
2071 STRING(stg_asyncReadzh_malloc_str, "asyncReadzh_fast")
2078 foreign "C" barf("asyncRead# on threaded RTS");
2081 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2082 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2083 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2085 /* could probably allocate this on the heap instead */
2086 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2087 stg_asyncReadzh_malloc_str)
2089 (reqID) = foreign "C" addIORequest(R1, 0/*FALSE*/,R2,R3,R4 "ptr") [];
2090 StgAsyncIOResult_reqID(ares) = reqID;
2091 StgAsyncIOResult_len(ares) = 0;
2092 StgAsyncIOResult_errCode(ares) = 0;
2093 StgTSO_block_info(CurrentTSO) = ares;
2094 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2095 jump stg_block_async;
2099 STRING(stg_asyncWritezh_malloc_str, "asyncWritezh_fast")
2106 foreign "C" barf("asyncWrite# on threaded RTS");
2109 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2110 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2111 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2113 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2114 stg_asyncWritezh_malloc_str)
2116 (reqID) = foreign "C" addIORequest(R1, 1/*TRUE*/,R2,R3,R4 "ptr") [];
2118 StgAsyncIOResult_reqID(ares) = reqID;
2119 StgAsyncIOResult_len(ares) = 0;
2120 StgAsyncIOResult_errCode(ares) = 0;
2121 StgTSO_block_info(CurrentTSO) = ares;
2122 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2123 jump stg_block_async;
2127 STRING(stg_asyncDoProczh_malloc_str, "asyncDoProczh_fast")
2134 foreign "C" barf("asyncDoProc# on threaded RTS");
2137 /* args: R1 = proc, R2 = param */
2138 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2139 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2141 /* could probably allocate this on the heap instead */
2142 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2143 stg_asyncDoProczh_malloc_str)
2145 (reqID) = foreign "C" addDoProcRequest(R1 "ptr",R2 "ptr") [];
2146 StgAsyncIOResult_reqID(ares) = reqID;
2147 StgAsyncIOResult_len(ares) = 0;
2148 StgAsyncIOResult_errCode(ares) = 0;
2149 StgTSO_block_info(CurrentTSO) = ares;
2150 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2151 jump stg_block_async;
2156 // noDuplicate# tries to ensure that none of the thunks under
2157 // evaluation by the current thread are also under evaluation by
2158 // another thread. It relies on *both* threads doing noDuplicate#;
2159 // the second one will get blocked if they are duplicating some work.
2162 SAVE_THREAD_STATE();
2163 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2164 foreign "C" threadPaused (MyCapability() "ptr", CurrentTSO "ptr") [];
2166 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
2167 jump stg_threadFinished;
2169 LOAD_THREAD_STATE();
2170 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2171 jump %ENTRY_CODE(Sp(0));
2175 getApStackValzh_fast
2177 W_ ap_stack, offset, val, ok;
2179 /* args: R1 = AP_STACK, R2 = offset */
2183 if (%INFO_PTR(ap_stack) == stg_AP_STACK_info) {
2185 val = StgAP_STACK_payload(ap_stack,offset);