[project @ 2002-12-18 11:17:15 by simonmar]
[ghc-hetmet.git] / ghc / rts / Interpreter.c
1 /* -----------------------------------------------------------------------------
2  * Bytecode interpreter
3  *
4  * Copyright (c) The GHC Team, 1994-2002.
5  * ---------------------------------------------------------------------------*/
6
7 #if !defined(SMP)
8 #include "PosixSource.h"
9 #else
10 /* Hack and slash.. */
11 #include "Stg.h"
12 #endif
13 #include "Rts.h"
14 #include "RtsAPI.h"
15 #include "RtsUtils.h"
16 #include "Closures.h"
17 #include "TSO.h"
18 #include "Schedule.h"
19 #include "RtsFlags.h"
20 #include "Storage.h"
21 #include "Updates.h"
22 #include "Sanity.h"
23
24 #include "Bytecodes.h"
25 #include "Printer.h"
26 #include "Disassembler.h"
27 #include "Interpreter.h"
28
29
30 /* --------------------------------------------------------------------------
31  * The bytecode interpreter
32  * ------------------------------------------------------------------------*/
33
34 /* Gather stats about entry, opcode, opcode-pair frequencies.  For
35    tuning the interpreter. */
36
37 /* #define INTERP_STATS */
38
39
40 /* Sp points to the lowest live word on the stack. */
41
42 #define BCO_NEXT      instrs[bciPtr++]
43 #define BCO_PTR(n)    (W_)ptrs[n]
44 #define BCO_LIT(n)    (W_)literals[n]
45 #define BCO_ITBL(n)   itbls[n]
46
47 #define LOAD_STACK_POINTERS                                     \
48     Sp = cap->r.rCurrentTSO->sp;                                \
49     /* We don't change this ... */                              \
50     SpLim = cap->r.rCurrentTSO->stack + RESERVED_STACK_WORDS;
51
52 #define SAVE_STACK_POINTERS                     \
53     cap->r.rCurrentTSO->sp = Sp
54
55 #define RETURN_TO_SCHEDULER(todo,retcode)       \
56    SAVE_STACK_POINTERS;                         \
57    cap->r.rCurrentTSO->what_next = (todo);      \
58    return (retcode);
59
60
61 static inline StgPtr
62 allocate_UPD (int n_words)
63 {
64    return allocate(stg_max(sizeofW(StgHeader)+MIN_UPD_SIZE, n_words));
65 }
66
67 static inline StgPtr
68 allocate_NONUPD (int n_words)
69 {
70     return allocate(stg_max(sizeofW(StgHeader)+MIN_NONUPD_SIZE, n_words));
71 }
72
73
74 #ifdef INTERP_STATS
75
76 /* Hacky stats, for tuning the interpreter ... */
77 int it_unknown_entries[N_CLOSURE_TYPES];
78 int it_total_unknown_entries;
79 int it_total_entries;
80
81 int it_retto_BCO;
82 int it_retto_UPDATE;
83 int it_retto_other;
84
85 int it_slides;
86 int it_insns;
87 int it_BCO_entries;
88
89 int it_ofreq[27];
90 int it_oofreq[27][27];
91 int it_lastopc;
92
93 #define INTERP_TICK(n) (n)++
94
95 void interp_startup ( void )
96 {
97    int i, j;
98    it_retto_BCO = it_retto_UPDATE = it_retto_other = 0;
99    it_total_entries = it_total_unknown_entries = 0;
100    for (i = 0; i < N_CLOSURE_TYPES; i++)
101       it_unknown_entries[i] = 0;
102    it_slides = it_insns = it_BCO_entries = 0;
103    for (i = 0; i < 27; i++) it_ofreq[i] = 0;
104    for (i = 0; i < 27; i++) 
105      for (j = 0; j < 27; j++)
106         it_oofreq[i][j] = 0;
107    it_lastopc = 0;
108 }
109
110 void interp_shutdown ( void )
111 {
112    int i, j, k, o_max, i_max, j_max;
113    fprintf(stderr, "%d constrs entered -> (%d BCO, %d UPD, %d ??? )\n",
114                    it_retto_BCO + it_retto_UPDATE + it_retto_other,
115                    it_retto_BCO, it_retto_UPDATE, it_retto_other );
116    fprintf(stderr, "%d total entries, %d unknown entries \n", 
117                    it_total_entries, it_total_unknown_entries);
118    for (i = 0; i < N_CLOSURE_TYPES; i++) {
119      if (it_unknown_entries[i] == 0) continue;
120      fprintf(stderr, "   type %2d: unknown entries (%4.1f%%) == %d\n",
121              i, 100.0 * ((double)it_unknown_entries[i]) / 
122                         ((double)it_total_unknown_entries),
123              it_unknown_entries[i]);
124    }
125    fprintf(stderr, "%d insns, %d slides, %d BCO_entries\n", 
126                    it_insns, it_slides, it_BCO_entries);
127    for (i = 0; i < 27; i++) 
128       fprintf(stderr, "opcode %2d got %d\n", i, it_ofreq[i] );
129
130    for (k = 1; k < 20; k++) {
131       o_max = 0;
132       i_max = j_max = 0;
133       for (i = 0; i < 27; i++) {
134          for (j = 0; j < 27; j++) {
135             if (it_oofreq[i][j] > o_max) {
136                o_max = it_oofreq[i][j];
137                i_max = i; j_max = j;
138             }
139          }
140       }
141       
142       fprintf ( stderr, "%d:  count (%4.1f%%) %6d   is %d then %d\n",
143                 k, ((double)o_max) * 100.0 / ((double)it_insns), o_max,
144                    i_max, j_max );
145       it_oofreq[i_max][j_max] = 0;
146
147    }
148 }
149
150 #else // !INTERP_STATS
151
152 #define INTERP_TICK(n) /* nothing */
153
154 #endif
155
156 static StgWord app_ptrs_itbl[] = {
157     (W_)&stg_ap_p_info,
158     (W_)&stg_ap_pp_info,
159     (W_)&stg_ap_ppp_info,
160     (W_)&stg_ap_pppp_info,
161     (W_)&stg_ap_ppppp_info,
162     (W_)&stg_ap_pppppp_info,
163     (W_)&stg_ap_ppppppp_info
164 };
165
166 StgThreadReturnCode
167 interpretBCO (Capability* cap)
168 {
169     // Use of register here is primarily to make it clear to compilers
170     // that these entities are non-aliasable.
171     register StgPtr       Sp;    // local state -- stack pointer
172     register StgPtr       SpLim; // local state -- stack lim pointer
173     register StgClosure*  obj;
174     nat n, m;
175
176     LOAD_STACK_POINTERS;
177
178     // ------------------------------------------------------------------------
179     // Case 1:
180     // 
181     //       We have a closure to evaluate.  Stack looks like:
182     //       
183     //          |   XXXX_info   |
184     //          +---------------+
185     //       Sp |      -------------------> closure
186     //          +---------------+
187     //       
188     if (Sp[0] == (W_)&stg_enter_info) {
189         Sp++;
190         goto eval;
191     }
192
193     // ------------------------------------------------------------------------
194     // Case 2:
195     // 
196     //       We have a BCO application to perform.  Stack looks like:
197     //
198     //          |     ....      |
199     //          +---------------+
200     //          |     arg1      |
201     //          +---------------+
202     //          |     BCO       |
203     //          +---------------+
204     //       Sp |   RET_BCO     |
205     //          +---------------+
206     //       
207     else if (Sp[0] == (W_)&stg_apply_interp_info) {
208         obj = (StgClosure *)Sp[1];
209         Sp += 2;
210         goto run_BCO_fun;
211     }
212
213     // ------------------------------------------------------------------------
214     // Case 3:
215     //
216     //       We have an unboxed value to return.  See comment before
217     //       do_return_unboxed, below.
218     //
219     else {
220         goto do_return_unboxed;
221     }
222
223     // Evaluate the object on top of the stack.
224 eval:
225     obj = (StgClosure*)Sp[0]; Sp++;
226
227 eval_obj:
228     INTERP_TICK(it_total_evals);
229
230     IF_DEBUG(interpreter,
231              fprintf(stderr, 
232              "\n---------------------------------------------------------------\n");
233              fprintf(stderr,"Evaluating: "); printObj(obj);
234              fprintf(stderr,"Sp = %p\n", Sp);
235              fprintf(stderr, "\n" );
236
237              printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
238              fprintf(stderr, "\n\n");
239             );
240
241     IF_DEBUG(sanity,checkStackChunk(Sp, cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size));
242
243     switch ( get_itbl(obj)->type ) {
244
245     case IND:
246     case IND_OLDGEN:
247     case IND_PERM:
248     case IND_OLDGEN_PERM:
249     case IND_STATIC:
250     { 
251         obj = ((StgInd*)obj)->indirectee;
252         goto eval_obj;
253     }
254     
255     case CONSTR:
256     case CONSTR_1_0:
257     case CONSTR_0_1:
258     case CONSTR_2_0:
259     case CONSTR_1_1:
260     case CONSTR_0_2:
261     case CONSTR_INTLIKE:
262     case CONSTR_CHARLIKE:
263     case CONSTR_STATIC:
264     case CONSTR_NOCAF_STATIC:
265     case FUN:
266     case FUN_1_0:
267     case FUN_0_1:
268     case FUN_2_0:
269     case FUN_1_1:
270     case FUN_0_2:
271     case FUN_STATIC:
272     case PAP:
273         // already in WHNF
274         break;
275         
276     case BCO:
277         ASSERT(BCO_ARITY(obj) > 0);
278         break;
279
280     case AP:    /* Copied from stg_AP_entry. */
281     {
282         nat i, words;
283         StgAP *ap;
284         
285         ap = (StgAP*)obj;
286         words = ap->n_args;
287         
288         // Stack check
289         if (Sp - (words+sizeofW(StgUpdateFrame)) < SpLim) {
290             Sp -= 2;
291             Sp[1] = (W_)obj;
292             Sp[0] = (W_)&stg_enter_info;
293             RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
294         }
295         
296         /* Ok; we're safe.  Party on.  Push an update frame. */
297         Sp -= sizeofW(StgUpdateFrame);
298         {
299             StgUpdateFrame *__frame;
300             __frame = (StgUpdateFrame *)Sp;
301             SET_INFO(__frame, (StgInfoTable *)&stg_upd_frame_info);
302             __frame->updatee = (StgClosure *)(ap);
303         }
304         
305         /* Reload the stack */
306         Sp -= words;
307         for (i=0; i < words; i++) {
308             Sp[i] = (W_)ap->payload[i];
309         }
310
311         obj = (StgClosure*)ap->fun;
312         ASSERT(get_itbl(obj)->type == BCO);
313         goto run_BCO_fun;
314     }
315
316     default:
317 #ifdef INTERP_STATS
318     { 
319         int j;
320         
321         j = get_itbl(obj)->type;
322         ASSERT(j >= 0 && j < N_CLOSURE_TYPES);
323         it_unknown_entries[j]++;
324         it_total_unknown_entries++;
325     }
326 #endif
327     {
328         // Can't handle this object; yield to scheduler
329         IF_DEBUG(interpreter,
330                  fprintf(stderr, "evaluating unknown closure -- yielding to sched\n"); 
331                  printObj(obj);
332             );
333         Sp -= 2;
334         Sp[1] = (W_)obj;
335         Sp[0] = (W_)&stg_enter_info;
336         RETURN_TO_SCHEDULER(ThreadRunGHC, ThreadYielding);
337     }
338     }
339
340     // ------------------------------------------------------------------------
341     // We now have an evaluated object (obj).  The next thing to
342     // do is return it to the stack frame on top of the stack.
343 do_return:
344     ASSERT(closure_HNF(obj));
345
346     IF_DEBUG(interpreter,
347              fprintf(stderr, 
348              "\n---------------------------------------------------------------\n");
349              fprintf(stderr,"Returning: "); printObj(obj);
350              fprintf(stderr,"Sp = %p\n", Sp);
351              fprintf(stderr, "\n" );
352              printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
353              fprintf(stderr, "\n\n");
354             );
355
356     IF_DEBUG(sanity,checkStackChunk(Sp, cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size));
357
358     switch (get_itbl((StgClosure *)Sp)->type) {
359
360     case RET_SMALL: {
361         const StgInfoTable *info;
362
363         // NOTE: not using get_itbl().
364         info = ((StgClosure *)Sp)->header.info;
365         if (info == (StgInfoTable *)&stg_ap_v_info) {
366             n = 1; m = 0; goto do_apply;
367         }
368         if (info == (StgInfoTable *)&stg_ap_f_info) {
369             n = 1; m = 1; goto do_apply;
370         }
371         if (info == (StgInfoTable *)&stg_ap_d_info) {
372             n = 1; m = sizeofW(StgDouble); goto do_apply;
373         }
374         if (info == (StgInfoTable *)&stg_ap_l_info) {
375             n = 1; m = sizeofW(StgInt64); goto do_apply;
376         }
377         if (info == (StgInfoTable *)&stg_ap_n_info) {
378             n = 1; m = 1; goto do_apply;
379         }
380         if (info == (StgInfoTable *)&stg_ap_p_info) {
381             n = 1; m = 1; goto do_apply;
382         }
383         if (info == (StgInfoTable *)&stg_ap_pp_info) {
384             n = 2; m = 2; goto do_apply;
385         }
386         if (info == (StgInfoTable *)&stg_ap_ppp_info) {
387             n = 3; m = 3; goto do_apply;
388         }
389         if (info == (StgInfoTable *)&stg_ap_pppp_info) {
390             n = 4; m = 4; goto do_apply;
391         }
392         if (info == (StgInfoTable *)&stg_ap_ppppp_info) {
393             n = 5; m = 5; goto do_apply;
394         }
395         if (info == (StgInfoTable *)&stg_ap_pppppp_info) {
396             n = 6; m = 6; goto do_apply;
397         }
398         if (info == (StgInfoTable *)&stg_ap_ppppppp_info) {
399             n = 7; m = 7; goto do_apply;
400         }
401         goto do_return_unrecognised;
402     }
403
404     case UPDATE_FRAME:
405         // Returning to an update frame: do the update, pop the update
406         // frame, and continue with the next stack frame.
407         INTERP_TICK(it_retto_UPDATE);
408         UPD_IND(((StgUpdateFrame *)Sp)->updatee, obj); 
409         Sp += sizeofW(StgUpdateFrame);
410         goto do_return;
411
412     case RET_BCO:
413         // Returning to an interpreted continuation: put the object on
414         // the stack, and start executing the BCO.
415         INTERP_TICK(it_retto_BCO);
416         Sp--;
417         Sp[0] = (W_)obj;
418         obj = (StgClosure*)Sp[2];
419         ASSERT(get_itbl(obj)->type == BCO);
420         goto run_BCO_return;
421
422     default:
423     do_return_unrecognised:
424     {
425         // Can't handle this return address; yield to scheduler
426         INTERP_TICK(it_retto_other);
427         IF_DEBUG(interpreter,
428                  fprintf(stderr, "returning to unknown frame -- yielding to sched\n"); 
429                  printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
430             );
431         Sp -= 2;
432         Sp[1] = (W_)obj;
433         Sp[0] = (W_)&stg_enter_info;
434         RETURN_TO_SCHEDULER(ThreadRunGHC, ThreadYielding);
435     }
436     }
437
438     // -------------------------------------------------------------------------
439     // Returning an unboxed value.  The stack looks like this:
440     //
441     //    |     ....      |
442     //    +---------------+
443     //    |     fv2       |
444     //    +---------------+
445     //    |     fv1       |
446     //    +---------------+
447     //    |     BCO       |
448     //    +---------------+
449     //    | stg_ctoi_ret_ |
450     //    +---------------+
451     //    |    retval     |
452     //    +---------------+
453     //    |   XXXX_info   |
454     //    +---------------+
455     //
456     // where XXXX_info is one of the stg_gc_unbx_r1_info family.
457     //
458     // We're only interested in the case when the real return address
459     // is a BCO; otherwise we'll return to the scheduler.
460
461 do_return_unboxed:
462     { 
463         int offset;
464         
465         ASSERT( Sp[0] == (W_)&stg_gc_unbx_r1_info
466                 || Sp[0] == (W_)&stg_gc_unpt_r1_info
467                 || Sp[0] == (W_)&stg_gc_f1_info
468                 || Sp[0] == (W_)&stg_gc_d1_info
469                 || Sp[0] == (W_)&stg_gc_l1_info
470                 || Sp[0] == (W_)&stg_gc_void_info // VoidRep
471             );
472
473         // get the offset of the stg_ctoi_ret_XXX itbl
474         offset = stack_frame_sizeW((StgClosure *)Sp);
475
476         switch (get_itbl((StgClosure *)Sp+offset)->type) {
477
478         case RET_BCO:
479             // Returning to an interpreted continuation: put the object on
480             // the stack, and start executing the BCO.
481             INTERP_TICK(it_retto_BCO);
482             obj = (StgClosure*)Sp[offset+1];
483             ASSERT(get_itbl(obj)->type == BCO);
484             goto run_BCO_return_unboxed;
485
486         default:
487         {
488             // Can't handle this return address; yield to scheduler
489             INTERP_TICK(it_retto_other);
490             IF_DEBUG(interpreter,
491                      fprintf(stderr, "returning to unknown frame -- yielding to sched\n"); 
492                      printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
493                 );
494             RETURN_TO_SCHEDULER(ThreadRunGHC, ThreadYielding);
495         }
496         }
497     }
498     // not reached.
499
500
501     // -------------------------------------------------------------------------
502     // Application...
503
504 do_apply:
505     // we have a function to apply (obj), and n arguments taking up m
506     // words on the stack.  The info table (stg_ap_pp_info or whatever)
507     // is on top of the arguments on the stack.
508     {
509         switch (get_itbl(obj)->type) {
510
511         case PAP: {
512             StgPAP *pap;
513             nat arity, i;
514
515             pap = (StgPAP *)obj;
516
517             // we only cope with PAPs whose function is a BCO
518             if (get_itbl(pap->fun)->type != BCO) {
519                 goto defer_apply_to_sched;
520             }
521
522             Sp++;
523             arity = pap->arity;
524             ASSERT(arity > 0);
525             if (arity < n) {
526                 // n must be greater than 1, and the only kinds of
527                 // application we support with more than one argument
528                 // are all pointers...
529                 //
530                 // Shuffle the args for this function down, and put
531                 // the appropriate info table in the gap.
532                 for (i = 0; i < arity; i++) {
533                     Sp[i-1] = Sp[i];
534                 }
535                 Sp[arity-1] = app_ptrs_itbl[n-arity-1];
536                 Sp--;
537                 // unpack the PAP's arguments onto the stack
538                 Sp -= pap->n_args;
539                 for (i = 0; i < pap->n_args; i++) {
540                     Sp[i] = (W_)pap->payload[i];
541                 }
542                 obj = pap->fun;
543                 goto run_BCO_fun;
544             } 
545             else if (arity == n) {
546                 Sp -= pap->n_args;
547                 for (i = 0; i < pap->n_args; i++) {
548                     Sp[i] = (W_)pap->payload[i];
549                 }
550                 obj = pap->fun;
551                 goto run_BCO_fun;
552             } 
553             else /* arity > n */ {
554                 // build a new PAP and return it.
555                 StgPAP *new_pap;
556                 nat size;
557                 size = PAP_sizeW(pap->n_args + m);
558                 new_pap = (StgPAP *)allocate(size);
559                 SET_HDR(new_pap,&stg_PAP_info,CCCS);
560                 new_pap->arity = pap->arity - n;
561                 new_pap->n_args = pap->n_args + m;
562                 new_pap->fun = pap->fun;
563                 for (i = 0; i < pap->n_args; i++) {
564                     new_pap->payload[i] = pap->payload[i];
565                 }
566                 for (i = 0; i < m; i++) {
567                     new_pap->payload[pap->n_args + i] = (StgClosure *)Sp[i];
568                 }
569                 obj = (StgClosure *)new_pap;
570                 Sp += m;
571                 goto do_return;
572             }
573         }           
574
575         case BCO: {
576             nat arity, i;
577
578             Sp++;
579             arity = BCO_ARITY(obj);
580             ASSERT(arity > 0);
581             if (arity < n) {
582                 // n must be greater than 1, and the only kinds of
583                 // application we support with more than one argument
584                 // are all pointers...
585                 //
586                 // Shuffle the args for this function down, and put
587                 // the appropriate info table in the gap.
588                 for (i = 0; i < arity; i++) {
589                     Sp[i-1] = Sp[i];
590                 }
591                 Sp[arity-1] = app_ptrs_itbl[n-arity-1];
592                 Sp--;
593                 goto run_BCO_fun;
594             } 
595             else if (arity == n) {
596                 goto run_BCO_fun;
597             }
598             else /* arity > n */ {
599                 // build a PAP and return it.
600                 StgPAP *pap;
601                 nat size, i;
602                 size = PAP_sizeW(m);
603                 pap = (StgPAP *)allocate(size);
604                 SET_HDR(pap, &stg_PAP_info,CCCS);
605                 pap->arity = arity - n;
606                 pap->fun = obj;
607                 pap->n_args = m;
608                 for (i = 0; i < m; i++) {
609                     pap->payload[i] = (StgClosure *)Sp[i];
610                 }
611                 obj = (StgClosure *)pap;
612                 Sp += m;
613                 goto do_return;
614             }
615         }
616
617         // No point in us applying machine-code functions
618         default:
619         defer_apply_to_sched:
620             Sp -= 2;
621             Sp[1] = (W_)obj;
622             Sp[0] = (W_)&stg_enter_info;
623             RETURN_TO_SCHEDULER(ThreadRunGHC, ThreadYielding);
624     }
625
626     // ------------------------------------------------------------------------
627     // Ok, we now have a bco (obj), and its arguments are all on the
628     // stack.  We can start executing the byte codes.
629     //
630     // The stack is in one of two states.  First, if this BCO is a
631     // function:
632     //
633     //    |     ....      |
634     //    +---------------+
635     //    |     arg2      |
636     //    +---------------+
637     //    |     arg1      |
638     //    +---------------+
639     //
640     // Second, if this BCO is a continuation:
641     //
642     //    |     ....      |
643     //    +---------------+
644     //    |     fv2       |
645     //    +---------------+
646     //    |     fv1       |
647     //    +---------------+
648     //    |     BCO       |
649     //    +---------------+
650     //    | stg_ctoi_ret_ |
651     //    +---------------+
652     //    |    retval     |
653     //    +---------------+
654     // 
655     // where retval is the value being returned to this continuation.
656     // In the event of a stack check, heap check, or context switch,
657     // we need to leave the stack in a sane state so the garbage
658     // collector can find all the pointers.
659     //
660     //  (1) BCO is a function:  the BCO's bitmap describes the
661     //      pointerhood of the arguments.
662     //
663     //  (2) BCO is a continuation: BCO's bitmap describes the
664     //      pointerhood of the free variables.
665     //
666     // Sadly we have three different kinds of stack/heap/cswitch check
667     // to do:
668
669 run_BCO_return:
670     // Heap check
671     if (doYouWantToGC()) {
672         Sp--; Sp[0] = (W_)&stg_enter_info;
673         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
674     }
675     
676     // "Standard" stack check
677     if (Sp - (INTERP_STACK_CHECK_THRESH+1) < SpLim) {
678         Sp--; Sp[0] = (W_)&stg_enter_info;
679         RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
680     }
681     goto run_BCO;
682     
683 run_BCO_return_unboxed:
684     // Heap check
685     if (doYouWantToGC()) {
686         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
687     }
688     
689     // "Standard" stack check
690     if (Sp - (INTERP_STACK_CHECK_THRESH+1) < SpLim) {
691         RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
692     }
693     goto run_BCO;
694     
695 run_BCO_fun:
696     IF_DEBUG(sanity,
697              Sp -= 2; 
698              Sp[1] = (W_)obj; 
699              Sp[0] = (W_)&stg_apply_interp_info;
700              checkStackChunk(Sp,SpLim);
701              Sp += 2;
702         );
703
704     // Heap check
705     if (doYouWantToGC()) {
706         Sp -= 2; 
707         Sp[1] = (W_)obj; 
708         Sp[0] = (W_)&stg_apply_interp_info; // placeholder, really
709         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
710     }
711     
712     // "Standard" stack check
713     if (Sp - (INTERP_STACK_CHECK_THRESH+1) < SpLim) {
714         Sp -= 2; 
715         Sp[1] = (W_)obj; 
716         Sp[0] = (W_)&stg_apply_interp_info; // placeholder, really
717         RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
718     }
719     goto run_BCO;
720     
721     // Now, actually interpret the BCO... (no returning to the
722     // scheduler again until the stack is in an orderly state).
723 run_BCO:
724     INTERP_TICK(it_BCO_entries);
725     {
726         register int       bciPtr     = 1; /* instruction pointer */
727         register StgBCO*   bco        = (StgBCO*)obj;
728         register StgWord16* instrs    = (StgWord16*)(BCO_INSTRS(bco));
729         register StgWord*  literals   = (StgWord*)(&bco->literals->payload[0]);
730         register StgPtr*   ptrs       = (StgPtr*)(&bco->ptrs->payload[0]);
731         register StgInfoTable** itbls = (StgInfoTable**)
732             (&bco->itbls->payload[0]);
733
734 #ifdef INTERP_STATS
735         it_lastopc = 0; /* no opcode */
736 #endif
737
738     nextInsn:
739         ASSERT(bciPtr <= instrs[0]);
740         IF_DEBUG(interpreter,
741                  //if (do_print_stack) {
742                  //fprintf(stderr, "\n-- BEGIN stack\n");
743                  //printStack(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size,iSu);
744                  //fprintf(stderr, "-- END stack\n\n");
745                  //}
746                  fprintf(stderr,"Sp = %p   pc = %d      ", Sp, bciPtr);
747                  disInstr(bco,bciPtr);
748                  if (0) { int i;
749                  fprintf(stderr,"\n");
750                  for (i = 8; i >= 0; i--) {
751                      fprintf(stderr, "%d  %p\n", i, (StgPtr)(*(Sp+i)));
752                  }
753                  fprintf(stderr,"\n");
754                  }
755                  //if (do_print_stack) checkStack(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size,iSu);
756             );
757
758         INTERP_TICK(it_insns);
759
760 #ifdef INTERP_STATS
761         ASSERT( (int)instrs[bciPtr] >= 0 && (int)instrs[bciPtr] < 27 );
762         it_ofreq[ (int)instrs[bciPtr] ] ++;
763         it_oofreq[ it_lastopc ][ (int)instrs[bciPtr] ] ++;
764         it_lastopc = (int)instrs[bciPtr];
765 #endif
766
767         switch (BCO_NEXT) {
768
769         case bci_STKCHECK: 
770         {
771             // An explicit stack check; we hope these will be rare.
772             int stk_words_reqd = BCO_NEXT + 1;
773             if (Sp - stk_words_reqd < SpLim) {
774                 Sp--; Sp[0] = (W_)obj;
775                 RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
776             }
777             goto nextInsn;
778         }
779
780         case bci_PUSH_L: {
781             int o1 = BCO_NEXT;
782             Sp[-1] = Sp[o1];
783             Sp--;
784             goto nextInsn;
785         }
786
787         case bci_PUSH_LL: {
788             int o1 = BCO_NEXT;
789             int o2 = BCO_NEXT;
790             Sp[-1] = Sp[o1];
791             Sp[-2] = Sp[o2];
792             Sp -= 2;
793             goto nextInsn;
794         }
795
796         case bci_PUSH_LLL: {
797             int o1 = BCO_NEXT;
798             int o2 = BCO_NEXT;
799             int o3 = BCO_NEXT;
800             Sp[-1] = Sp[o1];
801             Sp[-2] = Sp[o2];
802             Sp[-3] = Sp[o3];
803             Sp -= 3;
804             goto nextInsn;
805         }
806
807         case bci_PUSH_G: {
808             int o1 = BCO_NEXT;
809             Sp[-1] = BCO_PTR(o1);
810             Sp -= 1;
811             goto nextInsn;
812         }
813
814         case bci_PUSH_ALTS: {
815             int o_bco  = BCO_NEXT;
816             Sp[-2] = (W_)&stg_ctoi_ret_R1p_info;
817             Sp[-1] = BCO_PTR(o_bco);
818             Sp -= 2;
819             goto nextInsn;
820         }
821
822         case bci_PUSH_ALTS_P: {
823             int o_bco  = BCO_NEXT;
824             Sp[-2] = (W_)&stg_ctoi_ret_R1unpt_info;
825             Sp[-1] = BCO_PTR(o_bco);
826             Sp -= 2;
827             goto nextInsn;
828         }
829
830         case bci_PUSH_ALTS_N: {
831             int o_bco  = BCO_NEXT;
832             Sp[-2] = (W_)&stg_ctoi_ret_R1n_info;
833             Sp[-1] = BCO_PTR(o_bco);
834             Sp -= 2;
835             goto nextInsn;
836         }
837
838         case bci_PUSH_ALTS_F: {
839             int o_bco  = BCO_NEXT;
840             Sp[-2] = (W_)&stg_ctoi_ret_F1_info;
841             Sp[-1] = BCO_PTR(o_bco);
842             Sp -= 2;
843             goto nextInsn;
844         }
845
846         case bci_PUSH_ALTS_D: {
847             int o_bco  = BCO_NEXT;
848             Sp[-2] = (W_)&stg_ctoi_ret_D1_info;
849             Sp[-1] = BCO_PTR(o_bco);
850             Sp -= 2;
851             goto nextInsn;
852         }
853
854         case bci_PUSH_ALTS_L: {
855             int o_bco  = BCO_NEXT;
856             Sp[-2] = (W_)&stg_ctoi_ret_L1_info;
857             Sp[-1] = BCO_PTR(o_bco);
858             Sp -= 2;
859             goto nextInsn;
860         }
861
862         case bci_PUSH_ALTS_V: {
863             int o_bco  = BCO_NEXT;
864             Sp[-2] = (W_)&stg_ctoi_ret_V_info;
865             Sp[-1] = BCO_PTR(o_bco);
866             Sp -= 2;
867             goto nextInsn;
868         }
869
870         case bci_PUSH_APPLY_N:
871             Sp--; Sp[0] = (W_)&stg_ap_n_info;
872             goto nextInsn;
873         case bci_PUSH_APPLY_V:
874             Sp--; Sp[0] = (W_)&stg_ap_v_info;
875             goto nextInsn;
876         case bci_PUSH_APPLY_F:
877             Sp--; Sp[0] = (W_)&stg_ap_f_info;
878             goto nextInsn;
879         case bci_PUSH_APPLY_D:
880             Sp--; Sp[0] = (W_)&stg_ap_d_info;
881             goto nextInsn;
882         case bci_PUSH_APPLY_L:
883             Sp--; Sp[0] = (W_)&stg_ap_l_info;
884             goto nextInsn;
885         case bci_PUSH_APPLY_P:
886             Sp--; Sp[0] = (W_)&stg_ap_p_info;
887             goto nextInsn;
888         case bci_PUSH_APPLY_PP:
889             Sp--; Sp[0] = (W_)&stg_ap_pp_info;
890             goto nextInsn;
891         case bci_PUSH_APPLY_PPP:
892             Sp--; Sp[0] = (W_)&stg_ap_ppp_info;
893             goto nextInsn;
894         case bci_PUSH_APPLY_PPPP:
895             Sp--; Sp[0] = (W_)&stg_ap_pppp_info;
896             goto nextInsn;
897         case bci_PUSH_APPLY_PPPPP:
898             Sp--; Sp[0] = (W_)&stg_ap_ppppp_info;
899             goto nextInsn;
900         case bci_PUSH_APPLY_PPPPPP:
901             Sp--; Sp[0] = (W_)&stg_ap_pppppp_info;
902             goto nextInsn;
903         case bci_PUSH_APPLY_PPPPPPP:
904             Sp--; Sp[0] = (W_)&stg_ap_ppppppp_info;
905             goto nextInsn;
906             
907         case bci_PUSH_UBX: {
908             int i;
909             int o_lits = BCO_NEXT;
910             int n_words = BCO_NEXT;
911             Sp -= n_words;
912             for (i = 0; i < n_words; i++) {
913                 Sp[i] = BCO_LIT(o_lits+i);
914             }
915             goto nextInsn;
916         }
917
918         case bci_SLIDE: {
919             int n  = BCO_NEXT;
920             int by = BCO_NEXT;
921             /* a_1, .. a_n, b_1, .. b_by, s => a_1, .. a_n, s */
922             while(--n >= 0) {
923                 Sp[n+by] = Sp[n];
924             }
925             Sp += by;
926             INTERP_TICK(it_slides);
927             goto nextInsn;
928         }
929
930         case bci_ALLOC_AP: {
931             StgAP* ap; 
932             int n_payload = BCO_NEXT - 1;
933             int request   = PAP_sizeW(n_payload);
934             ap = (StgAP*)allocate_UPD(request);
935             Sp[-1] = (W_)ap;
936             ap->n_args = n_payload;
937             SET_HDR(ap, &stg_AP_info, CCS_SYSTEM/*ToDo*/)
938             Sp --;
939             goto nextInsn;
940         }
941
942         case bci_ALLOC_PAP: {
943             StgPAP* pap; 
944             int arity = BCO_NEXT;
945             int n_payload = BCO_NEXT - 1;
946             int request   = PAP_sizeW(n_payload);
947             pap = (StgPAP*)allocate_NONUPD(request);
948             Sp[-1] = (W_)pap;
949             pap->n_args = n_payload;
950             pap->arity = arity;
951             SET_HDR(pap, &stg_PAP_info, CCS_SYSTEM/*ToDo*/)
952             Sp --;
953             goto nextInsn;
954         }
955
956         case bci_MKAP: {
957             int i;
958             int stkoff = BCO_NEXT;
959             int n_payload = BCO_NEXT - 1;
960             StgAP* ap = (StgAP*)Sp[stkoff];
961             ASSERT((int)ap->n_args == n_payload);
962             ap->fun = (StgClosure*)Sp[0];
963
964             // The function should be a BCO, and its bitmap should
965             // cover the payload of the AP correctly.
966             ASSERT(get_itbl(ap->fun)->type == BCO
967                    && (get_itbl(ap)->type == PAP || 
968                        BCO_BITMAP_SIZE(ap->fun) == ap->n_args));
969
970             for (i = 0; i < n_payload; i++)
971                 ap->payload[i] = (StgClosure*)Sp[i+1];
972             Sp += n_payload+1;
973             IF_DEBUG(interpreter,
974                      fprintf(stderr,"\tBuilt "); 
975                      printObj((StgClosure*)ap);
976                 );
977             goto nextInsn;
978         }
979
980         case bci_UNPACK: {
981             /* Unpack N ptr words from t.o.s constructor */
982             int i;
983             int n_words = BCO_NEXT;
984             StgClosure* con = (StgClosure*)Sp[0];
985             Sp -= n_words;
986             for (i = 0; i < n_words; i++) {
987                 Sp[i] = (W_)con->payload[i];
988             }
989             goto nextInsn;
990         }
991
992         case bci_PACK: {
993             int i;
994             int o_itbl         = BCO_NEXT;
995             int n_words        = BCO_NEXT;
996             StgInfoTable* itbl = INFO_PTR_TO_STRUCT(BCO_ITBL(o_itbl));
997             int request        = CONSTR_sizeW( itbl->layout.payload.ptrs, 
998                                                itbl->layout.payload.nptrs );
999             StgClosure* con = (StgClosure*)allocate_NONUPD(request);
1000             ASSERT( itbl->layout.payload.ptrs + itbl->layout.payload.nptrs > 0);
1001             SET_HDR(con, BCO_ITBL(o_itbl), CCS_SYSTEM/*ToDo*/);
1002             for (i = 0; i < n_words; i++) {
1003                 con->payload[i] = (StgClosure*)Sp[i];
1004             }
1005             Sp += n_words;
1006             Sp --;
1007             Sp[0] = (W_)con;
1008             IF_DEBUG(interpreter,
1009                      fprintf(stderr,"\tBuilt "); 
1010                      printObj((StgClosure*)con);
1011                 );
1012             goto nextInsn;
1013         }
1014
1015         case bci_TESTLT_P: {
1016             int discr  = BCO_NEXT;
1017             int failto = BCO_NEXT;
1018             StgClosure* con = (StgClosure*)Sp[0];
1019             if (constrTag(con) >= discr) {
1020                 bciPtr = failto;
1021             }
1022             goto nextInsn;
1023         }
1024
1025         case bci_TESTEQ_P: {
1026             int discr  = BCO_NEXT;
1027             int failto = BCO_NEXT;
1028             StgClosure* con = (StgClosure*)Sp[0];
1029             if (constrTag(con) != discr) {
1030                 bciPtr = failto;
1031             }
1032             goto nextInsn;
1033         }
1034
1035         case bci_TESTLT_I: {
1036             // There should be an Int at Sp[1], and an info table at Sp[0].
1037             int discr   = BCO_NEXT;
1038             int failto  = BCO_NEXT;
1039             I_ stackInt = (I_)Sp[1];
1040             if (stackInt >= (I_)BCO_LIT(discr))
1041                 bciPtr = failto;
1042             goto nextInsn;
1043         }
1044
1045         case bci_TESTEQ_I: {
1046             // There should be an Int at Sp[1], and an info table at Sp[0].
1047             int discr   = BCO_NEXT;
1048             int failto  = BCO_NEXT;
1049             I_ stackInt = (I_)Sp[1];
1050             if (stackInt != (I_)BCO_LIT(discr)) {
1051                 bciPtr = failto;
1052             }
1053             goto nextInsn;
1054         }
1055
1056         case bci_TESTLT_D: {
1057             // There should be a Double at Sp[1], and an info table at Sp[0].
1058             int discr   = BCO_NEXT;
1059             int failto  = BCO_NEXT;
1060             StgDouble stackDbl, discrDbl;
1061             stackDbl = PK_DBL( & Sp[1] );
1062             discrDbl = PK_DBL( & BCO_LIT(discr) );
1063             if (stackDbl >= discrDbl) {
1064                 bciPtr = failto;
1065             }
1066             goto nextInsn;
1067         }
1068
1069         case bci_TESTEQ_D: {
1070             // There should be a Double at Sp[1], and an info table at Sp[0].
1071             int discr   = BCO_NEXT;
1072             int failto  = BCO_NEXT;
1073             StgDouble stackDbl, discrDbl;
1074             stackDbl = PK_DBL( & Sp[1] );
1075             discrDbl = PK_DBL( & BCO_LIT(discr) );
1076             if (stackDbl != discrDbl) {
1077                 bciPtr = failto;
1078             }
1079             goto nextInsn;
1080         }
1081
1082         case bci_TESTLT_F: {
1083             // There should be a Float at Sp[1], and an info table at Sp[0].
1084             int discr   = BCO_NEXT;
1085             int failto  = BCO_NEXT;
1086             StgFloat stackFlt, discrFlt;
1087             stackFlt = PK_FLT( & Sp[1] );
1088             discrFlt = PK_FLT( & BCO_LIT(discr) );
1089             if (stackFlt >= discrFlt) {
1090                 bciPtr = failto;
1091             }
1092             goto nextInsn;
1093         }
1094
1095         case bci_TESTEQ_F: {
1096             // There should be a Float at Sp[1], and an info table at Sp[0].
1097             int discr   = BCO_NEXT;
1098             int failto  = BCO_NEXT;
1099             StgFloat stackFlt, discrFlt;
1100             stackFlt = PK_FLT( & Sp[1] );
1101             discrFlt = PK_FLT( & BCO_LIT(discr) );
1102             if (stackFlt != discrFlt) {
1103                 bciPtr = failto;
1104             }
1105             goto nextInsn;
1106         }
1107
1108         // Control-flow ish things
1109         case bci_ENTER:
1110             // Context-switch check.  We put it here to ensure that
1111             // the interpreter has done at least *some* work before
1112             // context switching: sometimes the scheduler can invoke
1113             // the interpreter with context_switch == 1, particularly
1114             // if the -C0 flag has been given on the cmd line.
1115             if (context_switch) {
1116                 Sp--; Sp[0] = (W_)&stg_enter_info;
1117                 RETURN_TO_SCHEDULER(ThreadInterpret, ThreadYielding);
1118             }
1119             goto eval;
1120
1121         case bci_RETURN:
1122             obj = (StgClosure *)Sp[0];
1123             Sp++;
1124             goto do_return;
1125
1126         case bci_RETURN_P:
1127             Sp--;
1128             Sp[0] = (W_)&stg_gc_unpt_r1_info;
1129             goto do_return_unboxed;
1130         case bci_RETURN_N:
1131             Sp--;
1132             Sp[0] = (W_)&stg_gc_unbx_r1_info;
1133             goto do_return_unboxed;
1134         case bci_RETURN_F:
1135             Sp--;
1136             Sp[0] = (W_)&stg_gc_f1_info;
1137             goto do_return_unboxed;
1138         case bci_RETURN_D:
1139             Sp--;
1140             Sp[0] = (W_)&stg_gc_d1_info;
1141             goto do_return_unboxed;
1142         case bci_RETURN_L:
1143             Sp--;
1144             Sp[0] = (W_)&stg_gc_l1_info;
1145             goto do_return_unboxed;
1146         case bci_RETURN_V:
1147             Sp--;
1148             Sp[0] = (W_)&stg_gc_void_info;
1149             goto do_return_unboxed;
1150
1151         case bci_SWIZZLE: {
1152             int stkoff = BCO_NEXT;
1153             signed short n = (signed short)(BCO_NEXT);
1154             Sp[stkoff] += (W_)n;
1155             goto nextInsn;
1156         }
1157
1158         case bci_CCALL: {
1159             StgInt tok;
1160             int stk_offset            = BCO_NEXT;
1161             int o_itbl                = BCO_NEXT;
1162             void(*marshall_fn)(void*) = (void (*)(void*))BCO_LIT(o_itbl);
1163
1164             // There are a bunch of non-ptr words on the stack (the
1165             // ccall args, the ccall fun address and space for the
1166             // result), which we need to cover with an info table
1167             // since we might GC during this call.
1168             //
1169             // We know how many (non-ptr) words there are before the
1170             // next valid stack frame: it is the stk_offset arg to the
1171             // CCALL instruction.   So we build a RET_DYN stack frame
1172             // on the stack frame to describe this chunk of stack.
1173             //
1174             Sp -= RET_DYN_SIZE + sizeofW(StgRetDyn);
1175             ((StgRetDyn *)Sp)->liveness = ALL_NON_PTRS | N_NONPTRS(stk_offset);
1176             ((StgRetDyn *)Sp)->info = (StgInfoTable *)&stg_gc_gen_info;
1177
1178             SAVE_STACK_POINTERS;
1179             tok = suspendThread(&cap->r,rtsFalse);
1180
1181             // Careful: suspendThread might have shifted the stack
1182             // around (stack squeezing), so we have to grab the real
1183             // Sp out of the TSO to find the ccall args again:
1184             marshall_fn ( (void*)(cap->r.rCurrentTSO->sp + RET_DYN_SIZE
1185                 + sizeofW(StgRetDyn)) );
1186
1187             // And restart the thread again, popping the RET_DYN frame.
1188             cap = (Capability *)((void *)resumeThread(tok,rtsFalse) - sizeof(StgFunTable));
1189             LOAD_STACK_POINTERS;
1190             Sp += RET_DYN_SIZE + sizeofW(StgRetDyn);
1191             goto nextInsn;
1192         }
1193
1194         case bci_JMP: {
1195             /* BCO_NEXT modifies bciPtr, so be conservative. */
1196             int nextpc = BCO_NEXT;
1197             bciPtr     = nextpc;
1198             goto nextInsn;
1199         }
1200
1201         case bci_CASEFAIL:
1202             barf("interpretBCO: hit a CASEFAIL");
1203             
1204             // Errors
1205         default: 
1206             barf("interpretBCO: unknown or unimplemented opcode");
1207
1208         } /* switch on opcode */
1209     }
1210     }
1211
1212     barf("interpretBCO: fell off end of the interpreter");
1213 }