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 * ---------------------------------------------------------------------------*/
31 #ifndef mingw32_HOST_OS
41 import __gmpz_tdiv_qr;
42 import __gmpz_fdiv_qr;
43 import __gmpz_divexact;
49 import pthread_mutex_lock;
50 import pthread_mutex_unlock;
52 import base_ControlziExceptionziBase_nestedAtomically_closure;
53 import EnterCriticalSection;
54 import LeaveCriticalSection;
55 import ghczmprim_GHCziBool_False_closure;
57 /*-----------------------------------------------------------------------------
60 Basically just new*Array - the others are all inline macros.
62 The size arg is always passed in R1, and the result returned in R1.
64 The slow entry point is for returning from a heap check, the saved
65 size argument must be re-loaded from the stack.
66 -------------------------------------------------------------------------- */
68 /* for objects that are *less* than the size of a word, make sure we
69 * round up to the nearest word for the size of the array.
74 W_ words, payload_words, n, p;
75 MAYBE_GC(NO_PTRS,newByteArrayzh_fast);
77 payload_words = ROUNDUP_BYTES_TO_WDS(n);
78 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
79 ("ptr" p) = foreign "C" allocateLocal(MyCapability() "ptr",words) [];
80 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
81 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
82 StgArrWords_words(p) = payload_words;
86 newPinnedByteArrayzh_fast
88 W_ words, payload_words, n, p;
90 MAYBE_GC(NO_PTRS,newPinnedByteArrayzh_fast);
92 payload_words = ROUNDUP_BYTES_TO_WDS(n);
94 // We want a 16-byte aligned array. allocatePinned() gives us
95 // 8-byte aligned memory by default, but we want to align the
96 // *goods* inside the ArrWords object, so we have to check the
97 // size of the ArrWords header and adjust our size accordingly.
98 words = payload_words + ((SIZEOF_StgArrWords + 15) & ~15);
100 ("ptr" p) = foreign "C" allocatePinned(words) [];
101 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
103 // Push the pointer forward so that the goods fall on a 16-byte boundary.
104 p = p + ((p + SIZEOF_StgArrWords) & 15);
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
190 W_ mv, f, z, x, y, r, h;
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);
232 TICK_ALLOC_THUNK_2();
233 CCCS_ALLOC(THUNK_2_SIZE);
234 z = Hp - THUNK_2_SIZE + WDS(1);
235 SET_HDR(z, stg_ap_2_upd_info, W_[CCCS]);
236 LDV_RECORD_CREATE(z);
237 StgThunk_payload(z,0) = f;
239 TICK_ALLOC_THUNK_1();
240 CCCS_ALLOC(THUNK_1_SIZE);
241 y = z - THUNK_1_SIZE;
242 SET_HDR(y, stg_sel_0_upd_info, W_[CCCS]);
243 LDV_RECORD_CREATE(y);
244 StgThunk_payload(y,0) = z;
246 TICK_ALLOC_THUNK_1();
247 CCCS_ALLOC(THUNK_1_SIZE);
248 r = y - THUNK_1_SIZE;
249 SET_HDR(r, stg_sel_1_upd_info, W_[CCCS]);
250 LDV_RECORD_CREATE(r);
251 StgThunk_payload(r,0) = z;
254 x = StgMutVar_var(mv);
255 StgThunk_payload(z,1) = x;
257 (h) = foreign "C" cas(mv + SIZEOF_StgHeader + OFFSET_StgMutVar_var, x, y) [];
258 if (h != x) { goto retry; }
260 StgMutVar_var(mv) = y;
263 if (GET_INFO(mv) == stg_MUT_VAR_CLEAN_info) {
264 foreign "C" dirty_MUT_VAR(BaseReg "ptr", mv "ptr") [];
270 /* -----------------------------------------------------------------------------
271 Weak Pointer Primitives
272 -------------------------------------------------------------------------- */
274 STRING(stg_weak_msg,"New weak pointer at %p\n")
280 R3 = finalizer (or NULL)
285 R3 = stg_NO_FINALIZER_closure;
288 ALLOC_PRIM( SIZEOF_StgWeak, R1_PTR & R2_PTR & R3_PTR, mkWeakzh_fast );
290 w = Hp - SIZEOF_StgWeak + WDS(1);
291 SET_HDR(w, stg_WEAK_info, W_[CCCS]);
293 // We don't care about cfinalizer here.
294 // Should StgWeak_cfinalizer(w) be stg_NO_FINALIZER_closure or
298 StgWeak_value(w) = R2;
299 StgWeak_finalizer(w) = R3;
300 StgWeak_cfinalizer(w) = stg_NO_FINALIZER_closure;
302 StgWeak_link(w) = W_[weak_ptr_list];
303 W_[weak_ptr_list] = w;
305 IF_DEBUG(weak, foreign "C" debugBelch(stg_weak_msg,w) []);
310 mkWeakForeignEnvzh_fast
316 R5 = has environment (0 or 1)
319 W_ w, payload_words, words, p;
321 W_ key, val, fptr, ptr, flag, eptr;
330 ALLOC_PRIM( SIZEOF_StgWeak, R1_PTR & R2_PTR & R3_PTR, mkWeakForeignEnvzh_fast );
332 w = Hp - SIZEOF_StgWeak + WDS(1);
333 SET_HDR(w, stg_WEAK_info, W_[CCCS]);
336 words = BYTES_TO_WDS(SIZEOF_StgArrWords) + payload_words;
337 ("ptr" p) = foreign "C" allocateLocal(MyCapability() "ptr", words) [];
339 TICK_ALLOC_PRIM(SIZEOF_StgArrWords,WDS(payload_words),0);
340 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
342 StgArrWords_words(p) = payload_words;
343 StgArrWords_payload(p,0) = fptr;
344 StgArrWords_payload(p,1) = ptr;
345 StgArrWords_payload(p,2) = eptr;
346 StgArrWords_payload(p,3) = flag;
348 // We don't care about the value here.
349 // Should StgWeak_value(w) be stg_NO_FINALIZER_closure or something else?
351 StgWeak_key(w) = key;
352 StgWeak_value(w) = val;
353 StgWeak_finalizer(w) = stg_NO_FINALIZER_closure;
354 StgWeak_cfinalizer(w) = p;
356 StgWeak_link(w) = W_[weak_ptr_list];
357 W_[weak_ptr_list] = w;
359 IF_DEBUG(weak, foreign "C" debugBelch(stg_weak_msg,w) []);
373 if (GET_INFO(w) == stg_DEAD_WEAK_info) {
374 RET_NP(0,stg_NO_FINALIZER_closure);
380 // A weak pointer is inherently used, so we do not need to call
381 // LDV_recordDead_FILL_SLOP_DYNAMIC():
382 // LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
383 // or, LDV_recordDead():
384 // LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
385 // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as
386 // large as weak pointers, so there is no need to fill the slop, either.
387 // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
391 // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
393 SET_INFO(w,stg_DEAD_WEAK_info);
394 LDV_RECORD_CREATE(w);
396 f = StgWeak_finalizer(w);
397 arr = StgWeak_cfinalizer(w);
399 StgDeadWeak_link(w) = StgWeak_link(w);
401 if (arr != stg_NO_FINALIZER_closure) {
402 foreign "C" runCFinalizer(StgArrWords_payload(arr,0),
403 StgArrWords_payload(arr,1),
404 StgArrWords_payload(arr,2),
405 StgArrWords_payload(arr,3)) [];
408 /* return the finalizer */
409 if (f == stg_NO_FINALIZER_closure) {
410 RET_NP(0,stg_NO_FINALIZER_closure);
422 if (GET_INFO(w) == stg_WEAK_info) {
424 val = StgWeak_value(w);
432 /* -----------------------------------------------------------------------------
433 Arbitrary-precision Integer operations.
435 There are some assumptions in this code that mp_limb_t == W_. This is
436 the case for all the platforms that GHC supports, currently.
437 -------------------------------------------------------------------------- */
441 /* arguments: R1 = Int# */
443 W_ val, s, p; /* to avoid aliasing */
446 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, int2Integerzh_fast );
448 p = Hp - SIZEOF_StgArrWords;
449 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
450 StgArrWords_words(p) = 1;
452 /* mpz_set_si is inlined here, makes things simpler */
465 /* returns (# size :: Int#,
474 /* arguments: R1 = Word# */
476 W_ val, s, p; /* to avoid aliasing */
480 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, word2Integerzh_fast);
482 p = Hp - SIZEOF_StgArrWords;
483 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
484 StgArrWords_words(p) = 1;
493 /* returns (# size :: Int#,
494 data :: ByteArray# #)
501 * 'long long' primops for converting to/from Integers.
504 #ifdef SUPPORT_LONG_LONGS
506 int64ToIntegerzh_fast
508 /* arguments: L1 = Int64# */
511 W_ hi, lo, s, neg, words_needed, p;
516 hi = TO_W_(val >> 32);
519 if ( hi == 0 || (hi == 0xFFFFFFFF && lo != 0) ) {
520 // minimum is one word
526 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
527 NO_PTRS, int64ToIntegerzh_fast );
529 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
530 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
531 StgArrWords_words(p) = words_needed;
543 if ( words_needed == 2 ) {
551 } else /* val==0 */ {
559 /* returns (# size :: Int#,
560 data :: ByteArray# #)
564 word64ToIntegerzh_fast
566 /* arguments: L1 = Word64# */
569 W_ hi, lo, s, words_needed, p;
572 hi = TO_W_(val >> 32);
581 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(words_needed),
582 NO_PTRS, word64ToIntegerzh_fast );
584 p = Hp - SIZEOF_StgArrWords - WDS(words_needed) + WDS(1);
585 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
586 StgArrWords_words(p) = words_needed;
596 } else /* val==0 */ {
601 /* returns (# size :: Int#,
602 data :: ByteArray# #)
609 #endif /* SUPPORT_LONG_LONGS */
611 /* ToDo: this is shockingly inefficient */
616 bits8 [SIZEOF_MP_INT];
621 bits8 [SIZEOF_MP_INT];
626 bits8 [SIZEOF_MP_INT];
631 bits8 [SIZEOF_MP_INT];
636 #define FETCH_MP_TEMP(X) \
638 X = BaseReg + (OFFSET_StgRegTable_r ## X);
640 #define FETCH_MP_TEMP(X) /* Nothing */
643 #define GMP_TAKE2_RET1(name,mp_fun) \
648 FETCH_MP_TEMP(mp_tmp1); \
649 FETCH_MP_TEMP(mp_tmp2); \
650 FETCH_MP_TEMP(mp_result1) \
651 FETCH_MP_TEMP(mp_result2); \
653 /* call doYouWantToGC() */ \
654 MAYBE_GC(R2_PTR & R4_PTR, name); \
661 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
662 MP_INT__mp_size(mp_tmp1) = (s1); \
663 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
664 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
665 MP_INT__mp_size(mp_tmp2) = (s2); \
666 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
668 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
670 /* Perform the operation */ \
671 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
673 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
674 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
677 #define GMP_TAKE1_RET1(name,mp_fun) \
682 FETCH_MP_TEMP(mp_tmp1); \
683 FETCH_MP_TEMP(mp_result1) \
685 /* call doYouWantToGC() */ \
686 MAYBE_GC(R2_PTR, name); \
691 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
692 MP_INT__mp_size(mp_tmp1) = (s1); \
693 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
695 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
697 /* Perform the operation */ \
698 foreign "C" mp_fun(mp_result1 "ptr",mp_tmp1 "ptr") []; \
700 RET_NP(TO_W_(MP_INT__mp_size(mp_result1)), \
701 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords); \
704 #define GMP_TAKE2_RET2(name,mp_fun) \
709 FETCH_MP_TEMP(mp_tmp1); \
710 FETCH_MP_TEMP(mp_tmp2); \
711 FETCH_MP_TEMP(mp_result1) \
712 FETCH_MP_TEMP(mp_result2) \
714 /* call doYouWantToGC() */ \
715 MAYBE_GC(R2_PTR & R4_PTR, name); \
722 MP_INT__mp_alloc(mp_tmp1) = W_TO_INT(StgArrWords_words(d1)); \
723 MP_INT__mp_size(mp_tmp1) = (s1); \
724 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(d1); \
725 MP_INT__mp_alloc(mp_tmp2) = W_TO_INT(StgArrWords_words(d2)); \
726 MP_INT__mp_size(mp_tmp2) = (s2); \
727 MP_INT__mp_d(mp_tmp2) = BYTE_ARR_CTS(d2); \
729 foreign "C" __gmpz_init(mp_result1 "ptr") []; \
730 foreign "C" __gmpz_init(mp_result2 "ptr") []; \
732 /* Perform the operation */ \
733 foreign "C" mp_fun(mp_result1 "ptr",mp_result2 "ptr",mp_tmp1 "ptr",mp_tmp2 "ptr") []; \
735 RET_NPNP(TO_W_(MP_INT__mp_size(mp_result1)), \
736 MP_INT__mp_d(mp_result1) - SIZEOF_StgArrWords, \
737 TO_W_(MP_INT__mp_size(mp_result2)), \
738 MP_INT__mp_d(mp_result2) - SIZEOF_StgArrWords); \
741 GMP_TAKE2_RET1(plusIntegerzh_fast, __gmpz_add)
742 GMP_TAKE2_RET1(minusIntegerzh_fast, __gmpz_sub)
743 GMP_TAKE2_RET1(timesIntegerzh_fast, __gmpz_mul)
744 GMP_TAKE2_RET1(gcdIntegerzh_fast, __gmpz_gcd)
745 GMP_TAKE2_RET1(quotIntegerzh_fast, __gmpz_tdiv_q)
746 GMP_TAKE2_RET1(remIntegerzh_fast, __gmpz_tdiv_r)
747 GMP_TAKE2_RET1(divExactIntegerzh_fast, __gmpz_divexact)
748 GMP_TAKE2_RET1(andIntegerzh_fast, __gmpz_and)
749 GMP_TAKE2_RET1(orIntegerzh_fast, __gmpz_ior)
750 GMP_TAKE2_RET1(xorIntegerzh_fast, __gmpz_xor)
751 GMP_TAKE1_RET1(complementIntegerzh_fast, __gmpz_com)
753 GMP_TAKE2_RET2(quotRemIntegerzh_fast, __gmpz_tdiv_qr)
754 GMP_TAKE2_RET2(divModIntegerzh_fast, __gmpz_fdiv_qr)
758 mp_tmp_w: W_; // NB. mp_tmp_w is really an here mp_limb_t
764 /* R1 = the first Int#; R2 = the second Int# */
766 FETCH_MP_TEMP(mp_tmp_w);
769 (r) = foreign "C" __gmpn_gcd_1(mp_tmp_w "ptr", 1, R2) [];
772 /* Result parked in R1, return via info-pointer at TOS */
773 jump %ENTRY_CODE(Sp(0));
779 /* R1 = s1; R2 = d1; R3 = the int */
781 (s1) = foreign "C" __gmpn_gcd_1( BYTE_ARR_CTS(R2) "ptr", R1, R3) [];
784 /* Result parked in R1, return via info-pointer at TOS */
785 jump %ENTRY_CODE(Sp(0));
791 /* R1 = s1; R2 = d1; R3 = the int */
792 W_ usize, vsize, v_digit, u_digit;
798 // paraphrased from __gmpz_cmp_si() in the GMP sources
799 if (%gt(v_digit,0)) {
802 if (%lt(v_digit,0)) {
808 if (usize != vsize) {
810 jump %ENTRY_CODE(Sp(0));
815 jump %ENTRY_CODE(Sp(0));
818 u_digit = W_[BYTE_ARR_CTS(R2)];
820 if (u_digit == v_digit) {
822 jump %ENTRY_CODE(Sp(0));
825 if (%gtu(u_digit,v_digit)) { // NB. unsigned: these are mp_limb_t's
831 jump %ENTRY_CODE(Sp(0));
836 /* R1 = s1; R2 = d1; R3 = s2; R4 = d2 */
837 W_ usize, vsize, size, up, vp;
840 // paraphrased from __gmpz_cmp() in the GMP sources
844 if (usize != vsize) {
846 jump %ENTRY_CODE(Sp(0));
851 jump %ENTRY_CODE(Sp(0));
854 if (%lt(usize,0)) { // NB. not <, which is unsigned
860 up = BYTE_ARR_CTS(R2);
861 vp = BYTE_ARR_CTS(R4);
863 (cmp) = foreign "C" __gmpn_cmp(up "ptr", vp "ptr", size) [];
865 if (cmp == 0 :: CInt) {
867 jump %ENTRY_CODE(Sp(0));
870 if (%lt(cmp,0 :: CInt) == %lt(usize,0)) {
875 /* Result parked in R1, return via info-pointer at TOS */
876 jump %ENTRY_CODE(Sp(0));
888 r = W_[R2 + SIZEOF_StgArrWords];
893 /* Result parked in R1, return via info-pointer at TOS */
895 jump %ENTRY_CODE(Sp(0));
907 r = W_[R2 + SIZEOF_StgArrWords];
912 /* Result parked in R1, return via info-pointer at TOS */
914 jump %ENTRY_CODE(Sp(0));
921 FETCH_MP_TEMP(mp_tmp1);
922 FETCH_MP_TEMP(mp_tmp_w);
924 /* arguments: F1 = Float# */
927 ALLOC_PRIM( SIZEOF_StgArrWords + WDS(1), NO_PTRS, decodeFloatzh_fast );
929 /* Be prepared to tell Lennart-coded __decodeFloat
930 where mantissa._mp_d can be put (it does not care about the rest) */
931 p = Hp - SIZEOF_StgArrWords;
932 SET_HDR(p,stg_ARR_WORDS_info,W_[CCCS]);
933 StgArrWords_words(p) = 1;
934 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
936 /* Perform the operation */
937 foreign "C" __decodeFloat(mp_tmp1 "ptr",mp_tmp_w "ptr" ,arg) [];
939 /* returns: (Int# (expn), Int#, ByteArray#) */
940 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
943 decodeFloatzuIntzh_fast
947 FETCH_MP_TEMP(mp_tmp1);
948 FETCH_MP_TEMP(mp_tmp_w);
950 /* arguments: F1 = Float# */
953 /* Perform the operation */
954 foreign "C" __decodeFloat_Int(mp_tmp1 "ptr", mp_tmp_w "ptr", arg) [];
956 /* returns: (Int# (mantissa), Int# (exponent)) */
957 RET_NN(W_[mp_tmp1], W_[mp_tmp_w]);
960 #define DOUBLE_MANTISSA_SIZE SIZEOF_DOUBLE
961 #define ARR_SIZE (SIZEOF_StgArrWords + DOUBLE_MANTISSA_SIZE)
967 FETCH_MP_TEMP(mp_tmp1);
968 FETCH_MP_TEMP(mp_tmp_w);
970 /* arguments: D1 = Double# */
973 ALLOC_PRIM( ARR_SIZE, NO_PTRS, decodeDoublezh_fast );
975 /* Be prepared to tell Lennart-coded __decodeDouble
976 where mantissa.d can be put (it does not care about the rest) */
977 p = Hp - ARR_SIZE + WDS(1);
978 SET_HDR(p, stg_ARR_WORDS_info, W_[CCCS]);
979 StgArrWords_words(p) = BYTES_TO_WDS(DOUBLE_MANTISSA_SIZE);
980 MP_INT__mp_d(mp_tmp1) = BYTE_ARR_CTS(p);
982 /* Perform the operation */
983 foreign "C" __decodeDouble(mp_tmp1 "ptr", mp_tmp_w "ptr",arg) [];
985 /* returns: (Int# (expn), Int#, ByteArray#) */
986 RET_NNP(W_[mp_tmp_w], TO_W_(MP_INT__mp_size(mp_tmp1)), p);
989 decodeDoublezu2Intzh_fast
993 FETCH_MP_TEMP(mp_tmp1);
994 FETCH_MP_TEMP(mp_tmp2);
995 FETCH_MP_TEMP(mp_result1);
996 FETCH_MP_TEMP(mp_result2);
998 /* arguments: D1 = Double# */
1001 /* Perform the operation */
1002 foreign "C" __decodeDouble_2Int(mp_tmp1 "ptr", mp_tmp2 "ptr",
1003 mp_result1 "ptr", mp_result2 "ptr",
1007 (Int# (mant sign), Word# (mant high), Word# (mant low), Int# (expn)) */
1008 RET_NNNN(W_[mp_tmp1], W_[mp_tmp2], W_[mp_result1], W_[mp_result2]);
1011 /* -----------------------------------------------------------------------------
1012 * Concurrency primitives
1013 * -------------------------------------------------------------------------- */
1017 /* args: R1 = closure to spark */
1019 MAYBE_GC(R1_PTR, forkzh_fast);
1025 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
1026 RtsFlags_GcFlags_initialStkSize(RtsFlags),
1029 /* start blocked if the current thread is blocked */
1030 StgTSO_flags(threadid) =
1031 StgTSO_flags(threadid) | (StgTSO_flags(CurrentTSO) &
1032 (TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32));
1034 foreign "C" scheduleThread(MyCapability() "ptr", threadid "ptr") [];
1036 // switch at the earliest opportunity
1037 Capability_context_switch(MyCapability()) = 1 :: CInt;
1044 /* args: R1 = cpu, R2 = closure to spark */
1046 MAYBE_GC(R2_PTR, forkOnzh_fast);
1054 ("ptr" threadid) = foreign "C" createIOThread( MyCapability() "ptr",
1055 RtsFlags_GcFlags_initialStkSize(RtsFlags),
1058 /* start blocked if the current thread is blocked */
1059 StgTSO_flags(threadid) =
1060 StgTSO_flags(threadid) | (StgTSO_flags(CurrentTSO) &
1061 (TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32));
1063 foreign "C" scheduleThreadOn(MyCapability() "ptr", cpu, threadid "ptr") [];
1065 // switch at the earliest opportunity
1066 Capability_context_switch(MyCapability()) = 1 :: CInt;
1073 jump stg_yield_noregs;
1088 foreign "C" labelThread(R1 "ptr", R2 "ptr") [];
1090 jump %ENTRY_CODE(Sp(0));
1093 isCurrentThreadBoundzh_fast
1097 (r) = foreign "C" isThreadBound(CurrentTSO) [];
1103 /* args: R1 :: ThreadId# */
1111 if (TO_W_(StgTSO_what_next(tso)) == ThreadRelocated) {
1112 tso = StgTSO__link(tso);
1116 what_next = TO_W_(StgTSO_what_next(tso));
1117 why_blocked = TO_W_(StgTSO_why_blocked(tso));
1118 // Note: these two reads are not atomic, so they might end up
1119 // being inconsistent. It doesn't matter, since we
1120 // only return one or the other. If we wanted to return the
1121 // contents of block_info too, then we'd have to do some synchronisation.
1123 if (what_next == ThreadComplete) {
1124 ret = 16; // NB. magic, matches up with GHC.Conc.threadStatus
1126 if (what_next == ThreadKilled) {
1135 /* -----------------------------------------------------------------------------
1137 * -------------------------------------------------------------------------- */
1141 // Catch retry frame ------------------------------------------------------------
1143 INFO_TABLE_RET(stg_catch_retry_frame, CATCH_RETRY_FRAME,
1144 #if defined(PROFILING)
1145 W_ unused1, W_ unused2,
1147 W_ unused3, P_ unused4, P_ unused5)
1149 W_ r, frame, trec, outer;
1152 trec = StgTSO_trec(CurrentTSO);
1153 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1154 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1156 /* Succeeded (either first branch or second branch) */
1157 StgTSO_trec(CurrentTSO) = outer;
1158 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1159 jump %ENTRY_CODE(Sp(SP_OFF));
1161 /* Did not commit: re-execute */
1163 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1164 StgTSO_trec(CurrentTSO) = new_trec;
1165 if (StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1166 R1 = StgCatchRetryFrame_alt_code(frame);
1168 R1 = StgCatchRetryFrame_first_code(frame);
1175 // Atomically frame ------------------------------------------------------------
1177 INFO_TABLE_RET(stg_atomically_frame, ATOMICALLY_FRAME,
1178 #if defined(PROFILING)
1179 W_ unused1, W_ unused2,
1181 P_ unused3, P_ unused4)
1183 W_ frame, trec, valid, next_invariant, q, outer;
1186 trec = StgTSO_trec(CurrentTSO);
1187 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1189 if (outer == NO_TREC) {
1190 /* First time back at the atomically frame -- pick up invariants */
1191 ("ptr" q) = foreign "C" stmGetInvariantsToCheck(MyCapability() "ptr", trec "ptr") [];
1192 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1195 /* Second/subsequent time back at the atomically frame -- abort the
1196 * tx that's checking the invariant and move on to the next one */
1197 StgTSO_trec(CurrentTSO) = outer;
1198 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1199 StgInvariantCheckQueue_my_execution(q) = trec;
1200 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1201 /* Don't free trec -- it's linked from q and will be stashed in the
1202 * invariant if we eventually commit. */
1203 q = StgInvariantCheckQueue_next_queue_entry(q);
1204 StgAtomicallyFrame_next_invariant_to_check(frame) = q;
1208 q = StgAtomicallyFrame_next_invariant_to_check(frame);
1210 if (q != END_INVARIANT_CHECK_QUEUE) {
1211 /* We can't commit yet: another invariant to check */
1212 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [];
1213 StgTSO_trec(CurrentTSO) = trec;
1215 next_invariant = StgInvariantCheckQueue_invariant(q);
1216 R1 = StgAtomicInvariant_code(next_invariant);
1221 /* We've got no more invariants to check, try to commit */
1222 (valid) = foreign "C" stmCommitTransaction(MyCapability() "ptr", trec "ptr") [];
1224 /* Transaction was valid: commit succeeded */
1225 StgTSO_trec(CurrentTSO) = NO_TREC;
1226 Sp = Sp + SIZEOF_StgAtomicallyFrame;
1227 jump %ENTRY_CODE(Sp(SP_OFF));
1229 /* Transaction was not valid: try again */
1230 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1231 StgTSO_trec(CurrentTSO) = trec;
1232 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1233 R1 = StgAtomicallyFrame_code(frame);
1239 INFO_TABLE_RET(stg_atomically_waiting_frame, ATOMICALLY_FRAME,
1240 #if defined(PROFILING)
1241 W_ unused1, W_ unused2,
1243 P_ unused3, P_ unused4)
1245 W_ frame, trec, valid;
1249 /* The TSO is currently waiting: should we stop waiting? */
1250 (valid) = foreign "C" stmReWait(MyCapability() "ptr", CurrentTSO "ptr") [];
1252 /* Previous attempt is still valid: no point trying again yet */
1253 jump stg_block_noregs;
1255 /* Previous attempt is no longer valid: try again */
1256 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr") [];
1257 StgTSO_trec(CurrentTSO) = trec;
1258 StgHeader_info(frame) = stg_atomically_frame_info;
1259 R1 = StgAtomicallyFrame_code(frame);
1264 // STM catch frame --------------------------------------------------------------
1268 /* Catch frames are very similar to update frames, but when entering
1269 * one we just pop the frame off the stack and perform the correct
1270 * kind of return to the activation record underneath us on the stack.
1273 INFO_TABLE_RET(stg_catch_stm_frame, CATCH_STM_FRAME,
1274 #if defined(PROFILING)
1275 W_ unused1, W_ unused2,
1277 P_ unused3, P_ unused4)
1279 W_ r, frame, trec, outer;
1281 trec = StgTSO_trec(CurrentTSO);
1282 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1283 (r) = foreign "C" stmCommitNestedTransaction(MyCapability() "ptr", trec "ptr") [];
1285 /* Commit succeeded */
1286 StgTSO_trec(CurrentTSO) = outer;
1287 Sp = Sp + SIZEOF_StgCatchSTMFrame;
1292 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1293 StgTSO_trec(CurrentTSO) = new_trec;
1294 R1 = StgCatchSTMFrame_code(frame);
1300 // Primop definition ------------------------------------------------------------
1308 // stmStartTransaction may allocate
1309 MAYBE_GC (R1_PTR, atomicallyzh_fast);
1311 /* Args: R1 = m :: STM a */
1312 STK_CHK_GEN(SIZEOF_StgAtomicallyFrame + WDS(1), R1_PTR, atomicallyzh_fast);
1314 old_trec = StgTSO_trec(CurrentTSO);
1316 /* Nested transactions are not allowed; raise an exception */
1317 if (old_trec != NO_TREC) {
1318 R1 = base_ControlziExceptionziBase_nestedAtomically_closure;
1322 /* Set up the atomically frame */
1323 Sp = Sp - SIZEOF_StgAtomicallyFrame;
1326 SET_HDR(frame,stg_atomically_frame_info, W_[CCCS]);
1327 StgAtomicallyFrame_code(frame) = R1;
1328 StgAtomicallyFrame_next_invariant_to_check(frame) = END_INVARIANT_CHECK_QUEUE;
1330 /* Start the memory transcation */
1331 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", old_trec "ptr") [R1];
1332 StgTSO_trec(CurrentTSO) = new_trec;
1334 /* Apply R1 to the realworld token */
1343 /* Args: R1 :: STM a */
1344 /* Args: R2 :: Exception -> STM a */
1345 STK_CHK_GEN(SIZEOF_StgCatchSTMFrame + WDS(1), R1_PTR & R2_PTR, catchSTMzh_fast);
1347 /* Set up the catch frame */
1348 Sp = Sp - SIZEOF_StgCatchSTMFrame;
1351 SET_HDR(frame, stg_catch_stm_frame_info, W_[CCCS]);
1352 StgCatchSTMFrame_handler(frame) = R2;
1353 StgCatchSTMFrame_code(frame) = R1;
1355 /* Start a nested transaction to run the body of the try block in */
1358 cur_trec = StgTSO_trec(CurrentTSO);
1359 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", cur_trec "ptr");
1360 StgTSO_trec(CurrentTSO) = new_trec;
1362 /* Apply R1 to the realworld token */
1373 // stmStartTransaction may allocate
1374 MAYBE_GC (R1_PTR & R2_PTR, catchRetryzh_fast);
1376 /* Args: R1 :: STM a */
1377 /* Args: R2 :: STM a */
1378 STK_CHK_GEN(SIZEOF_StgCatchRetryFrame + WDS(1), R1_PTR & R2_PTR, catchRetryzh_fast);
1380 /* Start a nested transaction within which to run the first code */
1381 trec = StgTSO_trec(CurrentTSO);
1382 ("ptr" new_trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", trec "ptr") [R1,R2];
1383 StgTSO_trec(CurrentTSO) = new_trec;
1385 /* Set up the catch-retry frame */
1386 Sp = Sp - SIZEOF_StgCatchRetryFrame;
1389 SET_HDR(frame, stg_catch_retry_frame_info, W_[CCCS]);
1390 StgCatchRetryFrame_running_alt_code(frame) = 0 :: CInt; // false;
1391 StgCatchRetryFrame_first_code(frame) = R1;
1392 StgCatchRetryFrame_alt_code(frame) = R2;
1394 /* Apply R1 to the realworld token */
1407 MAYBE_GC (NO_PTRS, retryzh_fast); // STM operations may allocate
1409 // Find the enclosing ATOMICALLY_FRAME or CATCH_RETRY_FRAME
1411 StgTSO_sp(CurrentTSO) = Sp;
1412 (frame_type) = foreign "C" findRetryFrameHelper(CurrentTSO "ptr") [];
1413 Sp = StgTSO_sp(CurrentTSO);
1415 trec = StgTSO_trec(CurrentTSO);
1416 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1418 if (frame_type == CATCH_RETRY_FRAME) {
1419 // The retry reaches a CATCH_RETRY_FRAME before the atomic frame
1420 ASSERT(outer != NO_TREC);
1421 // Abort the transaction attempting the current branch
1422 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1423 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1424 if (!StgCatchRetryFrame_running_alt_code(frame) != 0::I32) {
1425 // Retry in the first branch: try the alternative
1426 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1427 StgTSO_trec(CurrentTSO) = trec;
1428 StgCatchRetryFrame_running_alt_code(frame) = 1 :: CInt; // true;
1429 R1 = StgCatchRetryFrame_alt_code(frame);
1432 // Retry in the alternative code: propagate the retry
1433 StgTSO_trec(CurrentTSO) = outer;
1434 Sp = Sp + SIZEOF_StgCatchRetryFrame;
1435 goto retry_pop_stack;
1439 // We've reached the ATOMICALLY_FRAME: attempt to wait
1440 ASSERT(frame_type == ATOMICALLY_FRAME);
1441 if (outer != NO_TREC) {
1442 // We called retry while checking invariants, so abort the current
1443 // invariant check (merging its TVar accesses into the parents read
1444 // set so we'll wait on them)
1445 foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
1446 foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
1448 StgTSO_trec(CurrentTSO) = trec;
1449 ("ptr" outer) = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
1451 ASSERT(outer == NO_TREC);
1453 (r) = foreign "C" stmWait(MyCapability() "ptr", CurrentTSO "ptr", trec "ptr") [];
1455 // Transaction was valid: stmWait put us on the TVars' queues, we now block
1456 StgHeader_info(frame) = stg_atomically_waiting_frame_info;
1458 // Fix up the stack in the unregisterised case: the return convention is different.
1459 R3 = trec; // passing to stmWaitUnblock()
1460 jump stg_block_stmwait;
1462 // Transaction was not valid: retry immediately
1463 ("ptr" trec) = foreign "C" stmStartTransaction(MyCapability() "ptr", outer "ptr") [];
1464 StgTSO_trec(CurrentTSO) = trec;
1465 R1 = StgAtomicallyFrame_code(frame);
1476 /* Args: R1 = invariant closure */
1477 MAYBE_GC (R1_PTR, checkzh_fast);
1479 trec = StgTSO_trec(CurrentTSO);
1481 foreign "C" stmAddInvariantToCheck(MyCapability() "ptr",
1485 jump %ENTRY_CODE(Sp(0));
1494 /* Args: R1 = initialisation value */
1496 MAYBE_GC (R1_PTR, newTVarzh_fast);
1498 ("ptr" tv) = foreign "C" stmNewTVar(MyCapability() "ptr", new_value "ptr") [];
1509 /* Args: R1 = TVar closure */
1511 MAYBE_GC (R1_PTR, readTVarzh_fast); // Call to stmReadTVar may allocate
1512 trec = StgTSO_trec(CurrentTSO);
1514 ("ptr" result) = foreign "C" stmReadTVar(MyCapability() "ptr", trec "ptr", tvar "ptr") [];
1524 result = StgTVar_current_value(R1);
1525 if (%INFO_PTR(result) == stg_TREC_HEADER_info) {
1537 /* Args: R1 = TVar closure */
1538 /* R2 = New value */
1540 MAYBE_GC (R1_PTR & R2_PTR, writeTVarzh_fast); // Call to stmWriteTVar may allocate
1541 trec = StgTSO_trec(CurrentTSO);
1544 foreign "C" stmWriteTVar(MyCapability() "ptr", trec "ptr", tvar "ptr", new_value "ptr") [];
1546 jump %ENTRY_CODE(Sp(0));
1550 /* -----------------------------------------------------------------------------
1553 * take & putMVar work as follows. Firstly, an important invariant:
1555 * If the MVar is full, then the blocking queue contains only
1556 * threads blocked on putMVar, and if the MVar is empty then the
1557 * blocking queue contains only threads blocked on takeMVar.
1560 * MVar empty : then add ourselves to the blocking queue
1561 * MVar full : remove the value from the MVar, and
1562 * blocking queue empty : return
1563 * blocking queue non-empty : perform the first blocked putMVar
1564 * from the queue, and wake up the
1565 * thread (MVar is now full again)
1567 * putMVar is just the dual of the above algorithm.
1569 * How do we "perform a putMVar"? Well, we have to fiddle around with
1570 * the stack of the thread waiting to do the putMVar. See
1571 * stg_block_putmvar and stg_block_takemvar in HeapStackCheck.c for
1572 * the stack layout, and the PerformPut and PerformTake macros below.
1574 * It is important that a blocked take or put is woken up with the
1575 * take/put already performed, because otherwise there would be a
1576 * small window of vulnerability where the thread could receive an
1577 * exception and never perform its take or put, and we'd end up with a
1580 * -------------------------------------------------------------------------- */
1584 /* args: R1 = MVar closure */
1586 if (StgMVar_value(R1) == stg_END_TSO_QUEUE_closure) {
1598 ALLOC_PRIM ( SIZEOF_StgMVar, NO_PTRS, newMVarzh_fast );
1600 mvar = Hp - SIZEOF_StgMVar + WDS(1);
1601 SET_HDR(mvar,stg_MVAR_DIRTY_info,W_[CCCS]);
1602 // MVARs start dirty: generation 0 has no mutable list
1603 StgMVar_head(mvar) = stg_END_TSO_QUEUE_closure;
1604 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1605 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1610 #define PerformTake(tso, value) \
1611 W_[StgTSO_sp(tso) + WDS(1)] = value; \
1612 W_[StgTSO_sp(tso) + WDS(0)] = stg_gc_unpt_r1_info;
1614 #define PerformPut(tso,lval) \
1615 StgTSO_sp(tso) = StgTSO_sp(tso) + WDS(3); \
1616 lval = W_[StgTSO_sp(tso) - WDS(1)];
1620 W_ mvar, val, info, tso;
1622 /* args: R1 = MVar closure */
1625 #if defined(THREADED_RTS)
1626 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1628 info = GET_INFO(mvar);
1631 if (info == stg_MVAR_CLEAN_info) {
1632 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr") [];
1635 /* If the MVar is empty, put ourselves on its blocking queue,
1636 * and wait until we're woken up.
1638 if (StgMVar_value(mvar) == stg_END_TSO_QUEUE_closure) {
1639 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1640 StgMVar_head(mvar) = CurrentTSO;
1642 foreign "C" setTSOLink(MyCapability() "ptr",
1643 StgMVar_tail(mvar) "ptr",
1646 StgTSO__link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1647 StgTSO_block_info(CurrentTSO) = mvar;
1648 // write barrier for throwTo(), which looks at block_info
1649 // if why_blocked==BlockedOnMVar.
1650 prim %write_barrier() [];
1651 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1652 StgMVar_tail(mvar) = CurrentTSO;
1655 jump stg_block_takemvar;
1658 /* we got the value... */
1659 val = StgMVar_value(mvar);
1661 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure)
1663 /* There are putMVar(s) waiting...
1664 * wake up the first thread on the queue
1666 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1668 /* actually perform the putMVar for the thread that we just woke up */
1669 tso = StgMVar_head(mvar);
1670 PerformPut(tso,StgMVar_value(mvar));
1672 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1673 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1676 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1677 StgMVar_head(mvar) "ptr", 1) [];
1678 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_MVAR_DIRTY_info);
1687 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1693 /* No further putMVars, MVar is now empty */
1694 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1696 #if defined(THREADED_RTS)
1697 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1699 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1709 W_ mvar, val, info, tso;
1711 /* args: R1 = MVar closure */
1715 #if defined(THREADED_RTS)
1716 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1718 info = GET_INFO(mvar);
1721 if (StgMVar_value(mvar) == stg_END_TSO_QUEUE_closure) {
1722 #if defined(THREADED_RTS)
1723 unlockClosure(mvar, info);
1725 /* HACK: we need a pointer to pass back,
1726 * so we abuse NO_FINALIZER_closure
1728 RET_NP(0, stg_NO_FINALIZER_closure);
1731 if (info == stg_MVAR_CLEAN_info) {
1732 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1735 /* we got the value... */
1736 val = StgMVar_value(mvar);
1738 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1740 /* There are putMVar(s) waiting...
1741 * wake up the first thread on the queue
1743 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1745 /* actually perform the putMVar for the thread that we just woke up */
1746 tso = StgMVar_head(mvar);
1747 PerformPut(tso,StgMVar_value(mvar));
1748 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1749 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1752 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1753 StgMVar_head(mvar) "ptr", 1) [];
1754 StgMVar_head(mvar) = tso;
1756 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1757 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1759 #if defined(THREADED_RTS)
1760 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1762 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1767 /* No further putMVars, MVar is now empty */
1768 StgMVar_value(mvar) = stg_END_TSO_QUEUE_closure;
1769 #if defined(THREADED_RTS)
1770 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1772 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1782 W_ mvar, val, info, tso;
1784 /* args: R1 = MVar, R2 = value */
1788 #if defined(THREADED_RTS)
1789 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [];
1791 info = GET_INFO(mvar);
1794 if (info == stg_MVAR_CLEAN_info) {
1795 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1798 if (StgMVar_value(mvar) != stg_END_TSO_QUEUE_closure) {
1799 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1800 StgMVar_head(mvar) = CurrentTSO;
1802 foreign "C" setTSOLink(MyCapability() "ptr",
1803 StgMVar_tail(mvar) "ptr",
1806 StgTSO__link(CurrentTSO) = stg_END_TSO_QUEUE_closure;
1807 StgTSO_block_info(CurrentTSO) = mvar;
1808 // write barrier for throwTo(), which looks at block_info
1809 // if why_blocked==BlockedOnMVar.
1810 prim %write_barrier() [];
1811 StgTSO_why_blocked(CurrentTSO) = BlockedOnMVar::I16;
1812 StgMVar_tail(mvar) = CurrentTSO;
1816 jump stg_block_putmvar;
1819 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1821 /* There are takeMVar(s) waiting: wake up the first one
1823 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1825 /* actually perform the takeMVar */
1826 tso = StgMVar_head(mvar);
1827 PerformTake(tso, val);
1828 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1829 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1832 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1833 StgMVar_head(mvar) "ptr", 1) [];
1834 StgMVar_head(mvar) = tso;
1836 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1837 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1840 #if defined(THREADED_RTS)
1841 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1843 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1845 jump %ENTRY_CODE(Sp(0));
1849 /* No further takes, the MVar is now full. */
1850 StgMVar_value(mvar) = val;
1852 #if defined(THREADED_RTS)
1853 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1855 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1857 jump %ENTRY_CODE(Sp(0));
1860 /* ToDo: yield afterward for better communication performance? */
1868 /* args: R1 = MVar, R2 = value */
1871 #if defined(THREADED_RTS)
1872 ("ptr" info) = foreign "C" lockClosure(mvar "ptr") [R2];
1874 info = GET_INFO(mvar);
1877 if (StgMVar_value(mvar) != stg_END_TSO_QUEUE_closure) {
1878 #if defined(THREADED_RTS)
1879 unlockClosure(mvar, info);
1884 if (info == stg_MVAR_CLEAN_info) {
1885 foreign "C" dirty_MVAR(BaseReg "ptr", mvar "ptr");
1888 if (StgMVar_head(mvar) != stg_END_TSO_QUEUE_closure) {
1890 /* There are takeMVar(s) waiting: wake up the first one
1892 ASSERT(StgTSO_why_blocked(StgMVar_head(mvar)) == BlockedOnMVar::I16);
1894 /* actually perform the takeMVar */
1895 tso = StgMVar_head(mvar);
1896 PerformTake(tso, R2);
1897 if (TO_W_(StgTSO_flags(tso)) & TSO_DIRTY == 0) {
1898 foreign "C" dirty_TSO(MyCapability() "ptr", tso "ptr") [];
1901 ("ptr" tso) = foreign "C" unblockOne_(MyCapability() "ptr",
1902 StgMVar_head(mvar) "ptr", 1) [];
1903 StgMVar_head(mvar) = tso;
1905 if (StgMVar_head(mvar) == stg_END_TSO_QUEUE_closure) {
1906 StgMVar_tail(mvar) = stg_END_TSO_QUEUE_closure;
1909 #if defined(THREADED_RTS)
1910 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1912 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1917 /* No further takes, the MVar is now full. */
1918 StgMVar_value(mvar) = R2;
1920 #if defined(THREADED_RTS)
1921 unlockClosure(mvar, stg_MVAR_DIRTY_info);
1923 SET_INFO(mvar,stg_MVAR_DIRTY_info);
1928 /* ToDo: yield afterward for better communication performance? */
1932 /* -----------------------------------------------------------------------------
1933 Stable pointer primitives
1934 ------------------------------------------------------------------------- */
1936 makeStableNamezh_fast
1940 ALLOC_PRIM( SIZEOF_StgStableName, R1_PTR, makeStableNamezh_fast );
1942 (index) = foreign "C" lookupStableName(R1 "ptr") [];
1944 /* Is there already a StableName for this heap object?
1945 * stable_ptr_table is a pointer to an array of snEntry structs.
1947 if ( snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) == NULL ) {
1948 sn_obj = Hp - SIZEOF_StgStableName + WDS(1);
1949 SET_HDR(sn_obj, stg_STABLE_NAME_info, W_[CCCS]);
1950 StgStableName_sn(sn_obj) = index;
1951 snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry) = sn_obj;
1953 sn_obj = snEntry_sn_obj(W_[stable_ptr_table] + index*SIZEOF_snEntry);
1960 makeStablePtrzh_fast
1964 MAYBE_GC(R1_PTR, makeStablePtrzh_fast);
1965 ("ptr" sp) = foreign "C" getStablePtr(R1 "ptr") [];
1969 deRefStablePtrzh_fast
1971 /* Args: R1 = the stable ptr */
1974 r = snEntry_addr(W_[stable_ptr_table] + sp*SIZEOF_snEntry);
1978 /* -----------------------------------------------------------------------------
1979 Bytecode object primitives
1980 ------------------------------------------------------------------------- */
1990 W_ bco, bitmap_arr, bytes, words;
1994 words = BYTES_TO_WDS(SIZEOF_StgBCO) + StgArrWords_words(bitmap_arr);
1997 ALLOC_PRIM( bytes, R1_PTR&R2_PTR&R3_PTR&R5_PTR, newBCOzh_fast );
1999 bco = Hp - bytes + WDS(1);
2000 SET_HDR(bco, stg_BCO_info, W_[CCCS]);
2002 StgBCO_instrs(bco) = R1;
2003 StgBCO_literals(bco) = R2;
2004 StgBCO_ptrs(bco) = R3;
2005 StgBCO_arity(bco) = HALF_W_(R4);
2006 StgBCO_size(bco) = HALF_W_(words);
2008 // Copy the arity/bitmap info into the BCO
2012 if (i < StgArrWords_words(bitmap_arr)) {
2013 StgBCO_bitmap(bco,i) = StgArrWords_payload(bitmap_arr,i);
2024 // R1 = the BCO# for the AP
2028 // This function is *only* used to wrap zero-arity BCOs in an
2029 // updatable wrapper (see ByteCodeLink.lhs). An AP thunk is always
2030 // saturated and always points directly to a FUN or BCO.
2031 ASSERT(%INFO_TYPE(%GET_STD_INFO(R1)) == HALF_W_(BCO) &&
2032 StgBCO_arity(R1) == HALF_W_(0));
2034 HP_CHK_GEN_TICKY(SIZEOF_StgAP, R1_PTR, mkApUpd0zh_fast);
2035 TICK_ALLOC_UP_THK(0, 0);
2036 CCCS_ALLOC(SIZEOF_StgAP);
2038 ap = Hp - SIZEOF_StgAP + WDS(1);
2039 SET_HDR(ap, stg_AP_info, W_[CCCS]);
2041 StgAP_n_args(ap) = HALF_W_(0);
2047 unpackClosurezh_fast
2049 /* args: R1 = closure to analyze */
2050 // TODO: Consider the absence of ptrs or nonptrs as a special case ?
2052 W_ info, ptrs, nptrs, p, ptrs_arr, nptrs_arr;
2053 info = %GET_STD_INFO(UNTAG(R1));
2055 // Some closures have non-standard layout, so we omit those here.
2057 type = TO_W_(%INFO_TYPE(info));
2058 switch [0 .. N_CLOSURE_TYPES] type {
2059 case THUNK_SELECTOR : {
2064 case THUNK, THUNK_1_0, THUNK_0_1, THUNK_2_0, THUNK_1_1,
2065 THUNK_0_2, THUNK_STATIC, AP, PAP, AP_STACK, BCO : {
2071 ptrs = TO_W_(%INFO_PTRS(info));
2072 nptrs = TO_W_(%INFO_NPTRS(info));
2077 W_ ptrs_arr_sz, nptrs_arr_sz;
2078 nptrs_arr_sz = SIZEOF_StgArrWords + WDS(nptrs);
2079 ptrs_arr_sz = SIZEOF_StgMutArrPtrs + WDS(ptrs);
2081 ALLOC_PRIM (ptrs_arr_sz + nptrs_arr_sz, R1_PTR, unpackClosurezh_fast);
2086 ptrs_arr = Hp - nptrs_arr_sz - ptrs_arr_sz + WDS(1);
2087 nptrs_arr = Hp - nptrs_arr_sz + WDS(1);
2089 SET_HDR(ptrs_arr, stg_MUT_ARR_PTRS_FROZEN_info, W_[CCCS]);
2090 StgMutArrPtrs_ptrs(ptrs_arr) = ptrs;
2094 W_[ptrs_arr + SIZEOF_StgMutArrPtrs + WDS(p)] = StgClosure_payload(clos,p);
2099 SET_HDR(nptrs_arr, stg_ARR_WORDS_info, W_[CCCS]);
2100 StgArrWords_words(nptrs_arr) = nptrs;
2104 W_[BYTE_ARR_CTS(nptrs_arr) + WDS(p)] = StgClosure_payload(clos, p+ptrs);
2108 RET_NPP(info, ptrs_arr, nptrs_arr);
2111 /* -----------------------------------------------------------------------------
2112 Thread I/O blocking primitives
2113 -------------------------------------------------------------------------- */
2115 /* Add a thread to the end of the blocked queue. (C-- version of the C
2116 * macro in Schedule.h).
2118 #define APPEND_TO_BLOCKED_QUEUE(tso) \
2119 ASSERT(StgTSO__link(tso) == END_TSO_QUEUE); \
2120 if (W_[blocked_queue_hd] == END_TSO_QUEUE) { \
2121 W_[blocked_queue_hd] = tso; \
2123 foreign "C" setTSOLink(MyCapability() "ptr", W_[blocked_queue_tl] "ptr", tso) []; \
2125 W_[blocked_queue_tl] = tso;
2131 foreign "C" barf("waitRead# on threaded RTS") never returns;
2134 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2135 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2136 StgTSO_block_info(CurrentTSO) = R1;
2137 // No locking - we're not going to use this interface in the
2138 // threaded RTS anyway.
2139 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2140 jump stg_block_noregs;
2148 foreign "C" barf("waitWrite# on threaded RTS") never returns;
2151 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2152 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2153 StgTSO_block_info(CurrentTSO) = R1;
2154 // No locking - we're not going to use this interface in the
2155 // threaded RTS anyway.
2156 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2157 jump stg_block_noregs;
2162 STRING(stg_delayzh_malloc_str, "delayzh_fast")
2165 #ifdef mingw32_HOST_OS
2173 foreign "C" barf("delay# on threaded RTS") never returns;
2176 /* args: R1 (microsecond delay amount) */
2177 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2178 StgTSO_why_blocked(CurrentTSO) = BlockedOnDelay::I16;
2180 #ifdef mingw32_HOST_OS
2182 /* could probably allocate this on the heap instead */
2183 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2184 stg_delayzh_malloc_str);
2185 (reqID) = foreign "C" addDelayRequest(R1);
2186 StgAsyncIOResult_reqID(ares) = reqID;
2187 StgAsyncIOResult_len(ares) = 0;
2188 StgAsyncIOResult_errCode(ares) = 0;
2189 StgTSO_block_info(CurrentTSO) = ares;
2191 /* Having all async-blocked threads reside on the blocked_queue
2192 * simplifies matters, so change the status to OnDoProc put the
2193 * delayed thread on the blocked_queue.
2195 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2196 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2197 jump stg_block_async_void;
2203 (time) = foreign "C" getourtimeofday() [R1];
2204 divisor = TO_W_(RtsFlags_MiscFlags_tickInterval(RtsFlags));
2208 divisor = divisor * 1000;
2209 target = ((R1 + divisor - 1) / divisor) /* divide rounding up */
2210 + time + 1; /* Add 1 as getourtimeofday rounds down */
2211 StgTSO_block_info(CurrentTSO) = target;
2213 /* Insert the new thread in the sleeping queue. */
2215 t = W_[sleeping_queue];
2217 if (t != END_TSO_QUEUE && StgTSO_block_info(t) < target) {
2219 t = StgTSO__link(t);
2223 StgTSO__link(CurrentTSO) = t;
2225 W_[sleeping_queue] = CurrentTSO;
2227 foreign "C" setTSOLink(MyCapability() "ptr", prev "ptr", CurrentTSO) [];
2229 jump stg_block_noregs;
2231 #endif /* !THREADED_RTS */
2235 #ifdef mingw32_HOST_OS
2236 STRING(stg_asyncReadzh_malloc_str, "asyncReadzh_fast")
2243 foreign "C" barf("asyncRead# on threaded RTS") never returns;
2246 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2247 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2248 StgTSO_why_blocked(CurrentTSO) = BlockedOnRead::I16;
2250 /* could probably allocate this on the heap instead */
2251 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2252 stg_asyncReadzh_malloc_str)
2254 (reqID) = foreign "C" addIORequest(R1, 0/*FALSE*/,R2,R3,R4 "ptr") [];
2255 StgAsyncIOResult_reqID(ares) = reqID;
2256 StgAsyncIOResult_len(ares) = 0;
2257 StgAsyncIOResult_errCode(ares) = 0;
2258 StgTSO_block_info(CurrentTSO) = ares;
2259 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2260 jump stg_block_async;
2264 STRING(stg_asyncWritezh_malloc_str, "asyncWritezh_fast")
2271 foreign "C" barf("asyncWrite# on threaded RTS") never returns;
2274 /* args: R1 = fd, R2 = isSock, R3 = len, R4 = buf */
2275 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2276 StgTSO_why_blocked(CurrentTSO) = BlockedOnWrite::I16;
2278 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2279 stg_asyncWritezh_malloc_str)
2281 (reqID) = foreign "C" addIORequest(R1, 1/*TRUE*/,R2,R3,R4 "ptr") [];
2283 StgAsyncIOResult_reqID(ares) = reqID;
2284 StgAsyncIOResult_len(ares) = 0;
2285 StgAsyncIOResult_errCode(ares) = 0;
2286 StgTSO_block_info(CurrentTSO) = ares;
2287 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2288 jump stg_block_async;
2292 STRING(stg_asyncDoProczh_malloc_str, "asyncDoProczh_fast")
2299 foreign "C" barf("asyncDoProc# on threaded RTS") never returns;
2302 /* args: R1 = proc, R2 = param */
2303 ASSERT(StgTSO_why_blocked(CurrentTSO) == NotBlocked::I16);
2304 StgTSO_why_blocked(CurrentTSO) = BlockedOnDoProc::I16;
2306 /* could probably allocate this on the heap instead */
2307 ("ptr" ares) = foreign "C" stgMallocBytes(SIZEOF_StgAsyncIOResult,
2308 stg_asyncDoProczh_malloc_str)
2310 (reqID) = foreign "C" addDoProcRequest(R1 "ptr",R2 "ptr") [];
2311 StgAsyncIOResult_reqID(ares) = reqID;
2312 StgAsyncIOResult_len(ares) = 0;
2313 StgAsyncIOResult_errCode(ares) = 0;
2314 StgTSO_block_info(CurrentTSO) = ares;
2315 APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
2316 jump stg_block_async;
2321 // noDuplicate# tries to ensure that none of the thunks under
2322 // evaluation by the current thread are also under evaluation by
2323 // another thread. It relies on *both* threads doing noDuplicate#;
2324 // the second one will get blocked if they are duplicating some work.
2327 SAVE_THREAD_STATE();
2328 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2329 foreign "C" threadPaused (MyCapability() "ptr", CurrentTSO "ptr") [];
2331 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
2332 jump stg_threadFinished;
2334 LOAD_THREAD_STATE();
2335 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
2336 jump %ENTRY_CODE(Sp(0));
2340 getApStackValzh_fast
2342 W_ ap_stack, offset, val, ok;
2344 /* args: R1 = AP_STACK, R2 = offset */
2348 if (%INFO_PTR(ap_stack) == stg_AP_STACK_info) {
2350 val = StgAP_STACK_payload(ap_stack,offset);
2358 /* -----------------------------------------------------------------------------
2360 -------------------------------------------------------------------------- */
2362 // Write the cost center stack of the first argument on stderr; return
2363 // the second. Possibly only makes sense for already evaluated
2370 ccs = StgHeader_ccs(UNTAG(R1));
2371 foreign "C" fprintCCS_stderr(ccs "ptr") [R2];
2382 #ifndef THREADED_RTS
2383 RET_NP(0,ghczmprim_GHCziBool_False_closure);
2385 (spark) = foreign "C" findSpark(MyCapability());
2389 RET_NP(0,ghczmprim_GHCziBool_False_closure);