[project @ 2002-04-10 11:43:43 by stolz]
[ghc-hetmet.git] / ghc / rts / PrimOps.hc
index 015e34a..d31e842 100644 (file)
@@ -1,5 +1,5 @@
 /* -----------------------------------------------------------------------------
- * $Id: PrimOps.hc,v 1.53 2000/08/07 23:37:23 qrczak Exp $
+ * $Id: PrimOps.hc,v 1.95 2002/04/10 11:43:45 stolz Exp $
  *
  * (c) The GHC Team, 1998-2000
  *
@@ -7,6 +7,7 @@
  *
  * ---------------------------------------------------------------------------*/
 
+#include "Stg.h"
 #include "Rts.h"
 
 #include "RtsFlags.h"
@@ -17,7 +18,6 @@
 #include "Storage.h"
 #include "BlockAlloc.h" /* tmp */
 #include "StablePriv.h"
-#include "HeapStackCheck.h"
 #include "StgRun.h"
 #include "Itimer.h"
 #include "Prelude.h"
    classes CCallable and CReturnable don't really exist, but the
    compiler insists on generating dictionaries containing references
    to GHC_ZcCCallable_static_info etc., so we provide dummy symbols
-   for these.
+   for these.  Some C compilers can't cope with zero-length static arrays,
+   so we have to make these one element long.
 */
 
-W_ GHC_ZCCCallable_static_info[0];
-W_ GHC_ZCCReturnable_static_info[0];
-
-
+StgWord GHC_ZCCCallable_static_info[1];
+StgWord GHC_ZCCReturnable_static_info[1];
+  
 /* -----------------------------------------------------------------------------
    Macros for Hand-written primitives.
    -------------------------------------------------------------------------- */
@@ -244,33 +244,41 @@ W_ GHC_ZCCReturnable_static_info[0];
 
 #define BYTES_TO_STGWORDS(n) ((n) + sizeof(W_) - 1)/sizeof(W_)
 
-#define newByteArray(ty,scale)                         \
- FN_(new##ty##Arrayzh_fast)                            \
+FN_(newByteArrayzh_fast)                               \
  {                                                     \
-   W_ stuff_size, size, n;                             \
+   W_ size, stuff_size, n;                             \
    StgArrWords* p;                                     \
    FB_                                                 \
-     MAYBE_GC(NO_PTRS,new##ty##Arrayzh_fast);          \
+     MAYBE_GC(NO_PTRS,newByteArrayzh_fast);            \
      n = R1.w;                                         \
-     stuff_size = BYTES_TO_STGWORDS(n*scale);          \
+     stuff_size = BYTES_TO_STGWORDS(n);                        \
      size = sizeofW(StgArrWords)+ stuff_size;          \
      p = (StgArrWords *)RET_STGCALL1(P_,allocate,size);        \
      TICK_ALLOC_PRIM(sizeofW(StgArrWords),stuff_size,0); \
-     SET_HDR(p, &ARR_WORDS_info, CCCS);                \
+     SET_HDR(p, &stg_ARR_WORDS_info, CCCS);            \
      p->words = stuff_size;                            \
      TICK_RET_UNBOXED_TUP(1)                           \
      RET_P(p);                                         \
    FE_                                                 \
  }
 
-newByteArray(Char,   1)
-/* Char arrays really contain only 8-bit bytes for compatibility. */
-newByteArray(Int,    sizeof(I_))
-newByteArray(Word,   sizeof(W_))
-newByteArray(Addr,   sizeof(P_))
-newByteArray(Float,  sizeof(StgFloat))
-newByteArray(Double, sizeof(StgDouble))
-newByteArray(StablePtr, sizeof(StgStablePtr))
+FN_(newPinnedByteArrayzh_fast)                                 \
+ {                                                             \
+   W_ size, stuff_size, n;                                     \
+   StgArrWords* p;                                             \
+   FB_                                                         \
+     MAYBE_GC(NO_PTRS,newPinnedByteArrayzh_fast);              \
+     n = R1.w;                                                 \
+     stuff_size = BYTES_TO_STGWORDS(n);                                \
+     size = sizeofW(StgArrWords)+ stuff_size;                  \
+     p = (StgArrWords *)RET_STGCALL1(P_,allocatePinned,size);  \
+     TICK_ALLOC_PRIM(sizeofW(StgArrWords),stuff_size,0);       \
+     SET_HDR(p, &stg_ARR_WORDS_info, CCCS);                    \
+     p->words = stuff_size;                                    \
+     TICK_RET_UNBOXED_TUP(1)                                   \
+     RET_P(p);                                                 \
+   FE_                                                         \
+ }
 
 FN_(newArrayzh_fast)
 {
@@ -286,7 +294,7 @@ FN_(newArrayzh_fast)
     arr = (StgMutArrPtrs *)RET_STGCALL1(P_, allocate, size);
     TICK_ALLOC_PRIM(sizeofW(StgMutArrPtrs), n, 0);
 
-    SET_HDR(arr,&MUT_ARR_PTRS_info,CCCS);
+    SET_HDR(arr,&stg_MUT_ARR_PTRS_info,CCCS);
     arr->ptrs = n;
 
     init = R2.w;
@@ -311,7 +319,7 @@ FN_(newMutVarzh_fast)
   CCS_ALLOC(CCCS,sizeofW(StgMutVar));
 
   mv = (StgMutVar *)(Hp-sizeofW(StgMutVar)+1);
-  SET_HDR(mv,&MUT_VAR_info,CCCS);
+  SET_HDR(mv,&stg_MUT_VAR_info,CCCS);
   mv->var = R1.cl;
 
   TICK_RET_UNBOXED_TUP(1);
@@ -321,10 +329,8 @@ FN_(newMutVarzh_fast)
 
 /* -----------------------------------------------------------------------------
    Foreign Object Primitives
-
    -------------------------------------------------------------------------- */
 
-#ifndef PAR
 FN_(mkForeignObjzh_fast)
 {
   /* R1.p = ptr to foreign object,
@@ -338,7 +344,7 @@ FN_(mkForeignObjzh_fast)
   CCS_ALLOC(CCCS,sizeofW(StgForeignObj)); /* ccs prof */
 
   result = (StgForeignObj *) (Hp + 1 - sizeofW(StgForeignObj));
-  SET_HDR(result,&FOREIGN_info,CCCS);
+  SET_HDR(result,&stg_FOREIGN_info,CCCS);
   result->data = R1.p;
 
   /* returns (# s#, ForeignObj# #) */
@@ -346,13 +352,12 @@ FN_(mkForeignObjzh_fast)
   RET_P(result);
   FE_
 }
-#endif
 
 /* These two are out-of-line for the benefit of the NCG */
 FN_(unsafeThawArrayzh_fast)
 {
   FB_
-  SET_INFO((StgClosure *)R1.cl,&MUT_ARR_PTRS_info);
+  SET_INFO((StgClosure *)R1.cl,&stg_MUT_ARR_PTRS_info);
   recordMutable((StgMutClosure*)R1.cl);
 
   TICK_RET_UNBOXED_TUP(1);
@@ -364,8 +369,6 @@ FN_(unsafeThawArrayzh_fast)
    Weak Pointer Primitives
    -------------------------------------------------------------------------- */
 
-#ifndef PAR
-
 FN_(mkWeakzh_fast)
 {
   /* R1.p = key
@@ -376,7 +379,7 @@ FN_(mkWeakzh_fast)
   FB_
 
   if (R3.cl == NULL) {
-    R3.cl = &NO_FINALIZER_closure;
+    R3.cl = &stg_NO_FINALIZER_closure;
   }
 
   HP_CHK_GEN_TICKY(sizeofW(StgWeak),R1_PTR|R2_PTR|R3_PTR, mkWeakzh_fast,);
@@ -385,7 +388,7 @@ FN_(mkWeakzh_fast)
   CCS_ALLOC(CCCS,sizeofW(StgWeak)); /* ccs prof */
 
   w = (StgWeak *) (Hp + 1 - sizeofW(StgWeak));
-  SET_HDR(w, &WEAK_info, CCCS);
+  SET_HDR(w, &stg_WEAK_info, CCCS);
 
   w->key        = R1.cl;
   w->value      = R2.cl;
@@ -411,25 +414,60 @@ FN_(finalizzeWeakzh_fast)
   w = (StgDeadWeak *)R1.p;
 
   /* already dead? */
-  if (w->header.info == &DEAD_WEAK_info) {
-      RET_NP(0,&NO_FINALIZER_closure);
+  if (w->header.info == &stg_DEAD_WEAK_info) {
+      RET_NP(0,&stg_NO_FINALIZER_closure);
   }
 
   /* kill it */
-  w->header.info = &DEAD_WEAK_info;
+#ifdef PROFILING
+  // @LDV profiling
+  // A weak pointer is inherently used, so we do not need to call
+  // LDV_recordDead_FILL_SLOP_DYNAMIC():
+  //    LDV_recordDead_FILL_SLOP_DYNAMIC((StgClosure *)w);
+  // or, LDV_recordDead():
+  //    LDV_recordDead((StgClosure *)w, sizeofW(StgWeak) - sizeofW(StgProfHeader));
+  // Furthermore, when PROFILING is turned on, dead weak pointers are exactly as 
+  // large as weak pointers, so there is no need to fill the slop, either.
+  // See stg_DEAD_WEAK_info in StgMiscClosures.hc.
+#endif
+  //
+  // Todo: maybe use SET_HDR() and remove LDV_recordCreate()?
+  //
+  w->header.info = &stg_DEAD_WEAK_info;
+#ifdef PROFILING
+  // @LDV profiling
+  LDV_recordCreate((StgClosure *)w);
+#endif
   f = ((StgWeak *)w)->finalizer;
   w->link = ((StgWeak *)w)->link;
 
   /* return the finalizer */
-  if (f == &NO_FINALIZER_closure) {
-      RET_NP(0,&NO_FINALIZER_closure);
+  if (f == &stg_NO_FINALIZER_closure) {
+      RET_NP(0,&stg_NO_FINALIZER_closure);
   } else {
       RET_NP(1,f);
   }
   FE_
 }
 
-#endif /* !PAR */
+FN_(deRefWeakzh_fast)
+{
+  /* R1.p = weak ptr */
+  StgWeak* w;
+  I_       code;
+  P_       val;
+  FB_
+  w = (StgWeak*)R1.p;
+  if (w->header.info == &stg_WEAK_info) {
+    code = 1;
+    val = (P_)((StgWeak *)w)->value;
+  } else {
+    code = 0;
+    val = (P_)w;
+  }
+  RET_NP(code,val);
+  FE_
+}
 
 /* -----------------------------------------------------------------------------
    Arbitrary-precision Integer operations.
@@ -449,7 +487,7 @@ FN_(int2Integerzh_fast)
    CCS_ALLOC(CCCS,sizeofW(StgArrWords)+1); /* ccs prof */
 
    p = (StgArrWords *)Hp - 1;
-   SET_ARR_HDR(p, &ARR_WORDS_info, CCCS, 1);
+   SET_ARR_HDR(p, &stg_ARR_WORDS_info, CCCS, 1);
 
    /* mpz_set_si is inlined here, makes things simpler */
    if (val < 0) { 
@@ -486,7 +524,7 @@ FN_(word2Integerzh_fast)
    CCS_ALLOC(CCCS,sizeofW(StgArrWords)+1); /* ccs prof */
 
    p = (StgArrWords *)Hp - 1;
-   SET_ARR_HDR(p, &ARR_WORDS_info, CCCS, 1);
+   SET_ARR_HDR(p, &stg_ARR_WORDS_info, CCCS, 1);
 
    if (val != 0) {
        s = 1;
@@ -504,30 +542,6 @@ FN_(word2Integerzh_fast)
    FE_
 }
 
-FN_(addr2Integerzh_fast)
-{
-  MP_INT result;
-  char *str;
-  FB_
-
-  MAYBE_GC(NO_PTRS,addr2Integerzh_fast);
-
-  /* args:   R1 :: Addr# */
-  str = R1.a;
-
-  /* Perform the operation */
-  if (RET_STGCALL3(int, mpz_init_set_str,&result,(str),/*base*/10))
-      abort();
-
-   /* returns (# size  :: Int#, 
-                data  :: ByteArray# 
-              #)
-   */
-  TICK_RET_UNBOXED_TUP(2);
-  RET_NP(result._mp_size, 
-         result._mp_d - sizeofW(StgArrWords));
-  FE_
-}
 
 /*
  * 'long long' primops for converting to/from Integers.
@@ -559,17 +573,17 @@ FN_(int64ToIntegerzh_fast)
    CCS_ALLOC(CCCS,sizeofW(StgArrWords)+words_needed); /* ccs prof */
 
    p = (StgArrWords *)(Hp-words_needed+1) - 1;
-   SET_ARR_HDR(p, &ARR_WORDS_info, CCCS, words_needed);
+   SET_ARR_HDR(p, &stg_ARR_WORDS_info, CCCS, words_needed);
 
    if ( val < 0LL ) {
      neg = 1;
      val = -val;
-   } 
+   }
 
    hi = (W_)((LW_)val / 0x100000000ULL);
 
    if ( words_needed == 2 )  { 
-      s = 2; 
+      s = 2;
       Hp[-1] = (W_)val;
       Hp[0] = hi;
    } else if ( val != 0 ) {
@@ -610,7 +624,7 @@ FN_(word64ToIntegerzh_fast)
    CCS_ALLOC(CCCS,sizeofW(StgArrWords)+words_needed); /* ccs prof */
 
    p = (StgArrWords *)(Hp-words_needed+1) - 1;
-   SET_ARR_HDR(p, &ARR_WORDS_info, CCCS, words_needed);
+   SET_ARR_HDR(p, &stg_ARR_WORDS_info, CCCS, words_needed);
 
    hi = (W_)((LW_)val / 0x100000000ULL);
    if ( val >= 0x100000000ULL ) { 
@@ -634,7 +648,7 @@ FN_(word64ToIntegerzh_fast)
 }
 
 
-#endif /* HAVE_LONG_LONG */
+#endif /* SUPPORT_LONG_LONGS */
 
 /* ToDo: this is shockingly inefficient */
 
@@ -673,6 +687,35 @@ FN_(name)                                                          \
   FE_                                                                  \
 }
 
+#define GMP_TAKE1_RET1(name,mp_fun)                                    \
+FN_(name)                                                              \
+{                                                                      \
+  MP_INT arg1, result;                                                 \
+  I_ s1;                                                               \
+  StgArrWords* d1;                                                     \
+  FB_                                                                  \
+                                                                       \
+  /* call doYouWantToGC() */                                           \
+  MAYBE_GC(R2_PTR, name);                                              \
+                                                                       \
+  d1 = (StgArrWords *)R2.p;                                            \
+  s1 = R1.i;                                                           \
+                                                                       \
+  arg1._mp_alloc       = d1->words;                                    \
+  arg1._mp_size                = (s1);                                         \
+  arg1._mp_d           = (unsigned long int *) (BYTE_ARR_CTS(d1));     \
+                                                                       \
+  STGCALL1(mpz_init,&result);                                          \
+                                                                       \
+  /* Perform the operation */                                          \
+  STGCALL2(mp_fun,&result,&arg1);                                      \
+                                                                       \
+  TICK_RET_UNBOXED_TUP(2);                                             \
+  RET_NP(result._mp_size,                                              \
+         result._mp_d-sizeofW(StgArrWords));                           \
+  FE_                                                                  \
+}
+
 #define GMP_TAKE2_RET2(name,mp_fun)                                    \
 FN_(name)                                                              \
 {                                                                      \
@@ -718,11 +761,169 @@ GMP_TAKE2_RET1(gcdIntegerzh_fast,      mpz_gcd);
 GMP_TAKE2_RET1(quotIntegerzh_fast,     mpz_tdiv_q);
 GMP_TAKE2_RET1(remIntegerzh_fast,      mpz_tdiv_r);
 GMP_TAKE2_RET1(divExactIntegerzh_fast, mpz_divexact);
+GMP_TAKE2_RET1(andIntegerzh_fast,      mpz_and);
+GMP_TAKE2_RET1(orIntegerzh_fast,       mpz_ior);
+GMP_TAKE2_RET1(xorIntegerzh_fast,      mpz_xor);
+GMP_TAKE1_RET1(complementIntegerzh_fast, mpz_com);
 
 GMP_TAKE2_RET2(quotRemIntegerzh_fast, mpz_tdiv_qr);
 GMP_TAKE2_RET2(divModIntegerzh_fast,  mpz_fdiv_qr);
 
-#ifndef FLOATS_AS_DOUBLES
+
+FN_(gcdIntzh_fast)
+{
+  /* R1 = the first Int#; R2 = the second Int# */
+  mp_limb_t aa;
+  I_ r;
+  FB_
+  aa = (mp_limb_t)(R1.i);
+  r = RET_STGCALL3(StgInt, mpn_gcd_1, (mp_limb_t *)(&aa), 1, (mp_limb_t)(R2.i));
+
+  R1.i = r;
+  /* Result parked in R1, return via info-pointer at TOS */
+  JMP_(ENTRY_CODE(Sp[0]));
+  FE_
+}
+
+FN_(gcdIntegerIntzh_fast)
+{
+  /* R1 = s1; R2 = d1; R3 = the int */
+  I_ r;
+  FB_
+  r = RET_STGCALL3(StgInt,mpn_gcd_1,(mp_limb_t *)(BYTE_ARR_CTS(R2.p)), R1.i, R3.i);
+
+  R1.i = r;
+  /* Result parked in R1, return via info-pointer at TOS */
+  JMP_(ENTRY_CODE(Sp[0]));
+  FE_
+}
+
+FN_(cmpIntegerIntzh_fast)
+{
+  /* R1 = s1; R2 = d1; R3 = the int */
+  I_ usize;
+  I_ vsize;
+  I_ v_digit;
+  mp_limb_t u_digit;
+  FB_
+
+  usize = R1.i;
+  vsize = 0;
+  v_digit = R3.i;
+
+  // paraphrased from mpz_cmp_si() in the GMP sources
+  if (v_digit > 0) {
+      vsize = 1;
+  } else if (v_digit < 0) {
+      vsize = -1;
+      v_digit = -v_digit;
+  }
+
+  if (usize != vsize) {
+    R1.i = usize - vsize; JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  if (usize == 0) {
+    R1.i = 0; JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  u_digit = *(mp_limb_t *)(BYTE_ARR_CTS(R2.p));
+
+  if (u_digit == (mp_limb_t) (unsigned long) v_digit) {
+    R1.i = 0; JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  if (u_digit > (mp_limb_t) (unsigned long) v_digit) {
+    R1.i = usize; 
+  } else {
+    R1.i = -usize; 
+  }
+
+  JMP_(ENTRY_CODE(Sp[0]));
+  FE_
+}
+
+FN_(cmpIntegerzh_fast)
+{
+  /* R1 = s1; R2 = d1; R3 = s2; R4 = d2 */
+  I_ usize;
+  I_ vsize;
+  I_ size;
+  StgPtr up, vp;
+  int cmp;
+  FB_
+
+  // paraphrased from mpz_cmp() in the GMP sources
+  usize = R1.i;
+  vsize = R3.i;
+
+  if (usize != vsize) {
+    R1.i = usize - vsize; JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  if (usize == 0) {
+    R1.i = 0; JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  size = abs(usize);
+
+  up = BYTE_ARR_CTS(R2.p);
+  vp = BYTE_ARR_CTS(R4.p);
+
+  cmp = RET_STGCALL3(I_, mpn_cmp, (mp_limb_t *)up, (mp_limb_t *)vp, size);
+
+  if (cmp == 0) {
+    R1.i = 0; JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  if ((cmp < 0) == (usize < 0)) {
+    R1.i = 1;
+  } else {
+    R1.i = (-1); 
+  }
+  /* Result parked in R1, return via info-pointer at TOS */
+  JMP_(ENTRY_CODE(Sp[0]));
+  FE_
+}
+
+FN_(integer2Intzh_fast)
+{
+  /* R1 = s; R2 = d */
+  I_ r, s;
+  FB_
+  s = R1.i;
+  if (s == 0)
+    r = 0;
+  else {
+    r = ((mp_limb_t *) (BYTE_ARR_CTS(R2.p)))[0];
+    if (s < 0) r = -r;
+  }
+  /* Result parked in R1, return via info-pointer at TOS */
+  R1.i = r;
+  JMP_(ENTRY_CODE(Sp[0]));
+  FE_
+}
+
+FN_(integer2Wordzh_fast)
+{
+  /* R1 = s; R2 = d */
+  I_ s;
+  W_ r;
+  FB_
+  s = R1.i;
+  if (s == 0)
+    r = 0;
+  else {
+    r = ((mp_limb_t *) (BYTE_ARR_CTS(R2.p)))[0];
+    if (s < 0) r = -r;
+  }
+  /* Result parked in R1, return via info-pointer at TOS */
+  R1.w = r;
+  JMP_(ENTRY_CODE(Sp[0]));
+  FE_
+}
+
+
 FN_(decodeFloatzh_fast)
 { 
   MP_INT mantissa;
@@ -741,7 +942,7 @@ FN_(decodeFloatzh_fast)
   /* Be prepared to tell Lennart-coded __decodeFloat   */
   /* where mantissa._mp_d can be put (it does not care about the rest) */
   p = (StgArrWords *)Hp - 1;
-  SET_ARR_HDR(p,&ARR_WORDS_info,CCCS,1)
+  SET_ARR_HDR(p,&stg_ARR_WORDS_info,CCCS,1)
   mantissa._mp_d = (void *)BYTE_ARR_CTS(p);
 
   /* Perform the operation */
@@ -752,7 +953,6 @@ FN_(decodeFloatzh_fast)
   RET_NNP(exponent,mantissa._mp_size,p);
   FE_
 }
-#endif /* !FLOATS_AS_DOUBLES */
 
 #define DOUBLE_MANTISSA_SIZE (sizeofW(StgDouble))
 #define ARR_SIZE (sizeofW(StgArrWords) + DOUBLE_MANTISSA_SIZE)
@@ -774,7 +974,7 @@ FN_(decodeDoublezh_fast)
   /* Be prepared to tell Lennart-coded __decodeDouble  */
   /* where mantissa.d can be put (it does not care about the rest) */
   p = (StgArrWords *)(Hp-ARR_SIZE+1);
-  SET_ARR_HDR(p, &ARR_WORDS_info, CCCS, DOUBLE_MANTISSA_SIZE);
+  SET_ARR_HDR(p, &stg_ARR_WORDS_info, CCCS, DOUBLE_MANTISSA_SIZE);
   mantissa._mp_d = (void *)BYTE_ARR_CTS(p);
 
   /* Perform the operation */
@@ -799,13 +999,28 @@ FN_(forkzh_fast)
 
   /* create it right now, return ThreadID in R1 */
   R1.t = RET_STGCALL2(StgTSO *, createIOThread, 
-                     RtsFlags.GcFlags.initialStkSize, R1.cl);
+                    RtsFlags.GcFlags.initialStkSize, R1.cl);
   STGCALL1(scheduleThread, R1.t);
       
   /* switch at the earliest opportunity */ 
   context_switch = 1;
   
+  RET_P(R1.t);
+  FE_
+}
+
+FN_(forkProcesszh_fast)
+{
+  pid_t pid;
+
+  FB_
+  /* args: none */
+  /* result: Pid */
+
+  R1.i = RET_STGCALL1(StgInt, forkProcess, CurrentTSO);
+
   JMP_(ENTRY_CODE(Sp[0]));
+
   FE_
 }
 
@@ -816,6 +1031,68 @@ FN_(yieldzh_fast)
   FE_
 }
 
+FN_(myThreadIdzh_fast)
+{
+  /* no args. */
+  FB_
+  RET_P((P_)CurrentTSO);
+  FE_
+}
+
+FN_(labelThreadzh_fast)
+{
+  FB_
+  /* args: R1.p = Addr# */
+#ifdef DEBUG
+  STGCALL2(labelThread,CurrentTSO,(char *)R1.p);
+#endif
+  FE_
+}
+
+
+/* -----------------------------------------------------------------------------
+ * MVar primitives
+ *
+ * take & putMVar work as follows.  Firstly, an important invariant:
+ *
+ *    If the MVar is full, then the blocking queue contains only
+ *    threads blocked on putMVar, and if the MVar is empty then the
+ *    blocking queue contains only threads blocked on takeMVar.
+ *
+ * takeMvar:
+ *    MVar empty : then add ourselves to the blocking queue
+ *    MVar full  : remove the value from the MVar, and
+ *                 blocking queue empty     : return
+ *                 blocking queue non-empty : perform the first blocked putMVar
+ *                                            from the queue, and wake up the
+ *                                            thread (MVar is now full again)
+ *
+ * putMVar is just the dual of the above algorithm.
+ *
+ * How do we "perform a putMVar"?  Well, we have to fiddle around with
+ * the stack of the thread waiting to do the putMVar.  See
+ * stg_block_putmvar and stg_block_takemvar in HeapStackCheck.c for
+ * the stack layout, and the PerformPut and PerformTake macros below.
+ *
+ * It is important that a blocked take or put is woken up with the
+ * take/put already performed, because otherwise there would be a
+ * small window of vulnerability where the thread could receive an
+ * exception and never perform its take or put, and we'd end up with a
+ * deadlock.
+ *
+ * -------------------------------------------------------------------------- */
+
+FN_(isEmptyMVarzh_fast)
+{
+  /* args: R1 = MVar closure */
+  I_ r;
+  FB_
+  r = (I_)((GET_INFO((StgMVar*)(R1.p))) == &stg_EMPTY_MVAR_info);
+  RET_N(r);
+  FE_
+}
+
+
 FN_(newMVarzh_fast)
 {
   StgMVar *mvar;
@@ -829,15 +1106,36 @@ FN_(newMVarzh_fast)
   CCS_ALLOC(CCCS,sizeofW(StgMVar)); /* ccs prof */
   
   mvar = (StgMVar *) (Hp - sizeofW(StgMVar) + 1);
-  SET_HDR(mvar,&EMPTY_MVAR_info,CCCS);
-  mvar->head = mvar->tail = (StgTSO *)&END_TSO_QUEUE_closure;
-  mvar->value = (StgClosure *)&END_TSO_QUEUE_closure;
+  SET_HDR(mvar,&stg_EMPTY_MVAR_info,CCCS);
+  mvar->head = mvar->tail = (StgTSO *)&stg_END_TSO_QUEUE_closure;
+  mvar->value = (StgClosure *)&stg_END_TSO_QUEUE_closure;
 
   TICK_RET_UNBOXED_TUP(1);
   RET_P(mvar);
   FE_
 }
 
+/* If R1 isn't available, pass it on the stack */
+#ifdef REG_R1
+#define PerformTake(tso, value) ({             \
+    (tso)->sp[1] = (W_)value;                  \
+    (tso)->sp[0] = (W_)&stg_gc_unpt_r1_info;   \
+  })
+#else
+#define PerformTake(tso, value) ({             \
+    (tso)->sp[1] = (W_)value;                  \
+    (tso)->sp[0] = (W_)&stg_ut_1_0_unreg_info; \
+  })
+#endif
+
+
+#define PerformPut(tso) ({                             \
+    StgClosure *val = (StgClosure *)(tso)->sp[2];      \
+    (tso)->sp[2] = (W_)&stg_gc_noregs_info;            \
+    (tso)->sp += 2;                                    \
+    val;                                               \
+  })
+
 FN_(takeMVarzh_fast)
 {
   StgMVar *mvar;
@@ -858,34 +1156,62 @@ FN_(takeMVarzh_fast)
   /* If the MVar is empty, put ourselves on its blocking queue,
    * and wait until we're woken up.
    */
-  if (info == &EMPTY_MVAR_info) {
-    if (mvar->head == (StgTSO *)&END_TSO_QUEUE_closure) {
+  if (info == &stg_EMPTY_MVAR_info) {
+    if (mvar->head == (StgTSO *)&stg_END_TSO_QUEUE_closure) {
       mvar->head = CurrentTSO;
     } else {
       mvar->tail->link = CurrentTSO;
     }
-    CurrentTSO->link = (StgTSO *)&END_TSO_QUEUE_closure;
+    CurrentTSO->link = (StgTSO *)&stg_END_TSO_QUEUE_closure;
     CurrentTSO->why_blocked = BlockedOnMVar;
     CurrentTSO->block_info.closure = (StgClosure *)mvar;
     mvar->tail = CurrentTSO;
 
 #ifdef SMP
     /* unlock the MVar */
-    mvar->header.info = &EMPTY_MVAR_info;
+    mvar->header.info = &stg_EMPTY_MVAR_info;
 #endif
-    BLOCK(R1_PTR, takeMVarzh_fast);
+    JMP_(stg_block_takemvar);
   }
 
+  /* we got the value... */
   val = mvar->value;
-  mvar->value = (StgClosure *)&END_TSO_QUEUE_closure;
 
-  /* do this last... we might have locked the MVar in the SMP case,
-   * and writing the info pointer will unlock it.
-   */
-  SET_INFO(mvar,&EMPTY_MVAR_info);
+  if (mvar->head != (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+      /* There are putMVar(s) waiting... 
+       * wake up the first thread on the queue
+       */
+      ASSERT(mvar->head->why_blocked == BlockedOnMVar);
 
-  TICK_RET_UNBOXED_TUP(1);
-  RET_P(val);
+      /* actually perform the putMVar for the thread that we just woke up */
+      mvar->value = PerformPut(mvar->head);
+
+#if defined(GRAN) || defined(PAR)
+      /* ToDo: check 2nd arg (mvar) is right */
+      mvar->head = RET_STGCALL2(StgTSO *,unblockOne,mvar->head,mvar);
+#else
+      mvar->head = RET_STGCALL1(StgTSO *,unblockOne,mvar->head);
+#endif
+      if (mvar->head == (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+         mvar->tail = (StgTSO *)&stg_END_TSO_QUEUE_closure;
+      }
+#ifdef SMP
+      /* unlock in the SMP case */
+      SET_INFO(mvar,&stg_FULL_MVAR_info);
+#endif
+      TICK_RET_UNBOXED_TUP(1);
+      RET_P(val);
+  } else {
+      /* No further putMVars, MVar is now empty */
+
+      /* do this last... we might have locked the MVar in the SMP case,
+       * and writing the info pointer will unlock it.
+       */
+      SET_INFO(mvar,&stg_EMPTY_MVAR_info);
+      mvar->value = (StgClosure *)&stg_END_TSO_QUEUE_closure;
+      TICK_RET_UNBOXED_TUP(1);
+      RET_P(val);
+  }
   FE_
 }
 
@@ -906,27 +1232,56 @@ FN_(tryTakeMVarzh_fast)
   info = GET_INFO(mvar);
 #endif
 
-  if (info == &EMPTY_MVAR_info) {
+  if (info == &stg_EMPTY_MVAR_info) {
 
 #ifdef SMP
-    /* unlock the MVar */
-    mvar->header.info = &EMPTY_MVAR_info;
+      /* unlock the MVar */
+      SET_INFO(mvar,&stg_EMPTY_MVAR_info);
 #endif
 
-    /* HACK: we need a pointer to pass back, so we abuse NO_FINALIZER_closure */
-    RET_NP(0, &NO_FINALIZER_closure);
+      /* HACK: we need a pointer to pass back, 
+       * so we abuse NO_FINALIZER_closure
+       */
+      RET_NP(0, &stg_NO_FINALIZER_closure);
   }
 
+  /* we got the value... */
   val = mvar->value;
-  mvar->value = (StgClosure *)&END_TSO_QUEUE_closure;
 
-  /* do this last... we might have locked the MVar in the SMP case,
-   * and writing the info pointer will unlock it.
-   */
-  SET_INFO(mvar,&EMPTY_MVAR_info);
+  if (mvar->head != (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+      /* There are putMVar(s) waiting... 
+       * wake up the first thread on the queue
+       */
+      ASSERT(mvar->head->why_blocked == BlockedOnMVar);
+
+      /* actually perform the putMVar for the thread that we just woke up */
+      mvar->value = PerformPut(mvar->head);
+
+#if defined(GRAN) || defined(PAR)
+      /* ToDo: check 2nd arg (mvar) is right */
+      mvar->head = RET_STGCALL2(StgTSO *,unblockOne,mvar->head,mvar);
+#else
+      mvar->head = RET_STGCALL1(StgTSO *,unblockOne,mvar->head);
+#endif
+      if (mvar->head == (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+         mvar->tail = (StgTSO *)&stg_END_TSO_QUEUE_closure;
+      }
+#ifdef SMP
+      /* unlock in the SMP case */
+      SET_INFO(mvar,&stg_FULL_MVAR_info);
+#endif
+  } else {
+      /* No further putMVars, MVar is now empty */
+      mvar->value = (StgClosure *)&stg_END_TSO_QUEUE_closure;
+
+      /* do this last... we might have locked the MVar in the SMP case,
+       * and writing the info pointer will unlock it.
+       */
+      SET_INFO(mvar,&stg_EMPTY_MVAR_info);
+  }
 
   TICK_RET_UNBOXED_TUP(1);
-  RET_NP(1,val);
+  RET_NP((I_)1, val);
   FE_
 }
 
@@ -946,41 +1301,115 @@ FN_(putMVarzh_fast)
   info = GET_INFO(mvar);
 #endif
 
-  if (info == &FULL_MVAR_info) {
-#ifdef INTERPRETER
-    fprintf(stderr, "fatal: put on a full MVar in Hugs; aborting\n" );
-    exit(1);
-#else
-    R1.cl = (StgClosure *)PutFullMVar_closure;
-    JMP_(raisezh_fast);
+  if (info == &stg_FULL_MVAR_info) {
+    if (mvar->head == (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+      mvar->head = CurrentTSO;
+    } else {
+      mvar->tail->link = CurrentTSO;
+    }
+    CurrentTSO->link = (StgTSO *)&stg_END_TSO_QUEUE_closure;
+    CurrentTSO->why_blocked = BlockedOnMVar;
+    CurrentTSO->block_info.closure = (StgClosure *)mvar;
+    mvar->tail = CurrentTSO;
+
+#ifdef SMP
+    /* unlock the MVar */
+    SET_INFO(mvar,&stg_FULL_MVAR_info);
 #endif
+    JMP_(stg_block_putmvar);
   }
   
-  mvar->value = R2.cl;
+  if (mvar->head != (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+      /* There are takeMVar(s) waiting: wake up the first one
+       */
+      ASSERT(mvar->head->why_blocked == BlockedOnMVar);
 
-  /* wake up the first thread on the queue, it will continue with the
-   * takeMVar operation and mark the MVar empty again.
-   */
-  if (mvar->head != (StgTSO *)&END_TSO_QUEUE_closure) {
-    ASSERT(mvar->head->why_blocked == BlockedOnMVar);
-#if defined(GRAN)
-    mvar->head = RET_STGCALL2(StgTSO *,unblockOne,mvar->head,mvar);
-#elif defined(PAR)
-    // ToDo: check 2nd arg (mvar) is right
-    mvar->head = RET_STGCALL2(StgTSO *,unblockOne,mvar->head,mvar);
+      /* actually perform the takeMVar */
+      PerformTake(mvar->head, R2.cl);
+      
+#if defined(GRAN) || defined(PAR)
+      /* ToDo: check 2nd arg (mvar) is right */
+      mvar->head = RET_STGCALL2(StgTSO *,unblockOne,mvar->head,mvar);
 #else
-    mvar->head = RET_STGCALL1(StgTSO *,unblockOne,mvar->head);
+      mvar->head = RET_STGCALL1(StgTSO *,unblockOne,mvar->head);
 #endif
-    if (mvar->head == (StgTSO *)&END_TSO_QUEUE_closure) {
-      mvar->tail = (StgTSO *)&END_TSO_QUEUE_closure;
-    }
+      if (mvar->head == (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+         mvar->tail = (StgTSO *)&stg_END_TSO_QUEUE_closure;
+      }
+#ifdef SMP
+      /* unlocks the MVar in the SMP case */
+      SET_INFO(mvar,&stg_EMPTY_MVAR_info);
+#endif
+      JMP_(ENTRY_CODE(Sp[0]));
+  } else {
+      /* No further takes, the MVar is now full. */
+      mvar->value = R2.cl;
+      /* unlocks the MVar in the SMP case */
+      SET_INFO(mvar,&stg_FULL_MVAR_info);
+      JMP_(ENTRY_CODE(Sp[0]));
   }
 
-  /* unlocks the MVar in the SMP case */
-  SET_INFO(mvar,&FULL_MVAR_info);
+  /* ToDo: yield afterward for better communication performance? */
+  FE_
+}
 
-  /* ToDo: yield here for better communication performance? */
-  JMP_(ENTRY_CODE(Sp[0]));
+FN_(tryPutMVarzh_fast)
+{
+  StgMVar *mvar;
+  const StgInfoTable *info;
+
+  FB_
+  /* args: R1 = MVar, R2 = value */
+
+  mvar = (StgMVar *)R1.p;
+
+#ifdef SMP
+  info = LOCK_CLOSURE(mvar);
+#else
+  info = GET_INFO(mvar);
+#endif
+
+  if (info == &stg_FULL_MVAR_info) {
+
+#ifdef SMP
+    /* unlock the MVar */
+    mvar->header.info = &stg_FULL_MVAR_info;
+#endif
+
+    RET_N(0);
+  }
+  
+  if (mvar->head != (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+      /* There are takeMVar(s) waiting: wake up the first one
+       */
+      ASSERT(mvar->head->why_blocked == BlockedOnMVar);
+
+      /* actually perform the takeMVar */
+      PerformTake(mvar->head, R2.cl);
+      
+#if defined(GRAN) || defined(PAR)
+      /* ToDo: check 2nd arg (mvar) is right */
+      mvar->head = RET_STGCALL2(StgTSO *,unblockOne,mvar->head,mvar);
+#else
+      mvar->head = RET_STGCALL1(StgTSO *,unblockOne,mvar->head);
+#endif
+      if (mvar->head == (StgTSO *)&stg_END_TSO_QUEUE_closure) {
+         mvar->tail = (StgTSO *)&stg_END_TSO_QUEUE_closure;
+      }
+#ifdef SMP
+      /* unlocks the MVar in the SMP case */
+      SET_INFO(mvar,&stg_EMPTY_MVAR_info);
+#endif
+      JMP_(ENTRY_CODE(Sp[0]));
+  } else {
+      /* No further takes, the MVar is now full. */
+      mvar->value = R2.cl;
+      /* unlocks the MVar in the SMP case */
+      SET_INFO(mvar,&stg_FULL_MVAR_info);
+      JMP_(ENTRY_CODE(Sp[0]));
+  }
+
+  /* ToDo: yield afterward for better communication performance? */
   FE_
 }
 
@@ -1004,7 +1433,7 @@ FN_(makeStableNamezh_fast)
   /* Is there already a StableName for this heap object? */
   if (stable_ptr_table[index].sn_obj == NULL) {
     sn_obj = (StgStableName *) (Hp - sizeofW(StgStableName) + 1);
-    sn_obj->header.info = &STABLE_NAME_info;
+    SET_HDR(sn_obj,&stg_STABLE_NAME_info,CCCS);
     sn_obj->sn = index;
     stable_ptr_table[index].sn_obj = (StgClosure *)sn_obj;
   } else {
@@ -1015,6 +1444,80 @@ FN_(makeStableNamezh_fast)
   RET_P(sn_obj);
 }
 
+
+FN_(makeStablePtrzh_fast)
+{
+  /* Args: R1 = a */
+  StgStablePtr sp;
+  FB_
+  MAYBE_GC(R1_PTR, makeStablePtrzh_fast);
+  sp = RET_STGCALL1(StgStablePtr,getStablePtr,R1.p);
+  RET_N(sp);
+  FE_
+}
+
+FN_(deRefStablePtrzh_fast)
+{
+  /* Args: R1 = the stable ptr */
+  P_ r;
+  StgStablePtr sp;
+  FB_
+  sp = (StgStablePtr)R1.w;
+  r = stable_ptr_table[(StgWord)sp].addr;
+  RET_P(r);
+  FE_
+}
+
+/* -----------------------------------------------------------------------------
+   Bytecode object primitives
+   -------------------------------------------------------------------------  */
+
+FN_(newBCOzh_fast)
+{
+  /* R1.p = instrs
+     R2.p = literals
+     R3.p = ptrs
+     R4.p = itbls
+  */
+  StgBCO *bco;
+  FB_
+
+  HP_CHK_GEN_TICKY(sizeofW(StgBCO),R1_PTR|R2_PTR|R3_PTR|R4_PTR, newBCOzh_fast,);
+  TICK_ALLOC_PRIM(sizeofW(StgHeader), sizeofW(StgBCO)-sizeofW(StgHeader), 0);
+  CCS_ALLOC(CCCS,sizeofW(StgBCO)); /* ccs prof */
+  bco = (StgBCO *) (Hp + 1 - sizeofW(StgBCO));
+  SET_HDR(bco, &stg_BCO_info, CCCS);
+
+  bco->instrs     = (StgArrWords*)R1.cl;
+  bco->literals   = (StgArrWords*)R2.cl;
+  bco->ptrs       = (StgMutArrPtrs*)R3.cl;
+  bco->itbls      = (StgArrWords*)R4.cl;
+
+  TICK_RET_UNBOXED_TUP(1);
+  RET_P(bco);
+  FE_
+}
+
+FN_(mkApUpd0zh_fast)
+{
+  /* R1.p = the fn for the AP_UPD
+  */
+  StgAP_UPD* ap;
+  FB_
+  HP_CHK_GEN_TICKY(AP_sizeW(0), R1_PTR, mkApUpd0zh_fast,);
+  TICK_ALLOC_PRIM(sizeofW(StgHeader), AP_sizeW(0)-sizeofW(StgHeader), 0);
+  CCS_ALLOC(CCCS,AP_sizeW(0)); /* ccs prof */
+  ap = (StgAP_UPD *) (Hp + 1 - AP_sizeW(0));
+  SET_HDR(ap, &stg_AP_UPD_info, CCCS);
+
+  ap->n_args = 0;
+  ap->fun = R1.cl;
+
+  TICK_RET_UNBOXED_TUP(1);
+  RET_P(ap);
+  FE_
+}
+
 /* -----------------------------------------------------------------------------
    Thread I/O blocking primitives
    -------------------------------------------------------------------------- */
@@ -1049,6 +1552,8 @@ FN_(waitWritezh_fast)
 
 FN_(delayzh_fast)
 {
+  StgTSO *t, *prev;
+  nat target;
   FB_
     /* args: R1.i */
     ASSERT(CurrentTSO->why_blocked == NotBlocked);
@@ -1056,20 +1561,26 @@ FN_(delayzh_fast)
 
     ACQUIRE_LOCK(&sched_mutex);
 
-    /* Add on ticks_since_select, since these will be subtracted at
-     * the next awaitEvent call.
-     */
-#if defined(HAVE_SETITIMER) || defined(mingw32_TARGET_OS)
-    CurrentTSO->block_info.delay = R1.i + ticks_since_select;
-#else
-    CurrentTSO->block_info.target = R1.i + getourtimeofday();
-#endif
+    target = (R1.i / (TICK_MILLISECS*1000)) + getourtimeofday();
+    CurrentTSO->block_info.target = target;
 
-    APPEND_TO_BLOCKED_QUEUE(CurrentTSO);
+    /* Insert the new thread in the sleeping queue. */
+    prev = NULL;
+    t = sleeping_queue;
+    while (t != END_TSO_QUEUE && t->block_info.target < target) {
+       prev = t;
+       t = t->link;
+    }
+
+    CurrentTSO->link = t;
+    if (prev == NULL) {
+       sleeping_queue = CurrentTSO;
+    } else {
+       prev->link = CurrentTSO;
+    }
 
     RELEASE_LOCK(&sched_mutex);
     JMP_(stg_block_noregs);
   FE_
 }
 
-