004bb6f256c6a212da2cc451cd473e46d684eeb4
[ghc-hetmet.git] / ghc / rts / Interpreter.c
1 /* -----------------------------------------------------------------------------
2  * Bytecode interpreter
3  *
4  * Copyright (c) The GHC Team, 1994-2002.
5  * ---------------------------------------------------------------------------*/
6
7 #include "PosixSource.h"
8 #include "Rts.h"
9 #include "RtsAPI.h"
10 #include "RtsUtils.h"
11 #include "Closures.h"
12 #include "TSO.h"
13 #include "Schedule.h"
14 #include "RtsFlags.h"
15 #include "Storage.h"
16 #include "LdvProfile.h"
17 #include "Updates.h"
18 #include "Sanity.h"
19 #include "Liveness.h"
20
21 #include "Bytecodes.h"
22 #include "Printer.h"
23 #include "Disassembler.h"
24 #include "Interpreter.h"
25
26 #include <string.h>     /* for memcpy */
27 #ifdef HAVE_ERRNO_H
28 #include <errno.h>
29 #endif
30
31
32 /* --------------------------------------------------------------------------
33  * The bytecode interpreter
34  * ------------------------------------------------------------------------*/
35
36 /* Gather stats about entry, opcode, opcode-pair frequencies.  For
37    tuning the interpreter. */
38
39 /* #define INTERP_STATS */
40
41
42 /* Sp points to the lowest live word on the stack. */
43
44 #define BCO_NEXT      instrs[bciPtr++]
45 #define BCO_PTR(n)    (W_)ptrs[n]
46 #define BCO_LIT(n)    literals[n]
47 #define BCO_ITBL(n)   itbls[n]
48
49 #define LOAD_STACK_POINTERS                                     \
50     Sp = cap->r.rCurrentTSO->sp;                                \
51     /* We don't change this ... */                              \
52     SpLim = cap->r.rCurrentTSO->stack + RESERVED_STACK_WORDS;
53
54 #define SAVE_STACK_POINTERS                     \
55     cap->r.rCurrentTSO->sp = Sp
56
57 #define RETURN_TO_SCHEDULER(todo,retcode)       \
58    SAVE_STACK_POINTERS;                         \
59    cap->r.rCurrentTSO->what_next = (todo);      \
60    threadPaused(cap->r.rCurrentTSO);            \
61    return (retcode);
62
63 #define RETURN_TO_SCHEDULER_NO_PAUSE(todo,retcode)      \
64    SAVE_STACK_POINTERS;                         \
65    cap->r.rCurrentTSO->what_next = (todo);      \
66    return (retcode);
67
68
69 STATIC_INLINE StgPtr
70 allocate_UPD (int n_words)
71 {
72    return allocate(stg_max(sizeofW(StgHeader)+MIN_UPD_SIZE, n_words));
73 }
74
75 STATIC_INLINE StgPtr
76 allocate_NONUPD (int n_words)
77 {
78     return allocate(stg_max(sizeofW(StgHeader)+MIN_NONUPD_SIZE, n_words));
79 }
80
81
82 #ifdef INTERP_STATS
83
84 /* Hacky stats, for tuning the interpreter ... */
85 int it_unknown_entries[N_CLOSURE_TYPES];
86 int it_total_unknown_entries;
87 int it_total_entries;
88
89 int it_retto_BCO;
90 int it_retto_UPDATE;
91 int it_retto_other;
92
93 int it_slides;
94 int it_insns;
95 int it_BCO_entries;
96
97 int it_ofreq[27];
98 int it_oofreq[27][27];
99 int it_lastopc;
100
101 #define INTERP_TICK(n) (n)++
102
103 void interp_startup ( void )
104 {
105    int i, j;
106    it_retto_BCO = it_retto_UPDATE = it_retto_other = 0;
107    it_total_entries = it_total_unknown_entries = 0;
108    for (i = 0; i < N_CLOSURE_TYPES; i++)
109       it_unknown_entries[i] = 0;
110    it_slides = it_insns = it_BCO_entries = 0;
111    for (i = 0; i < 27; i++) it_ofreq[i] = 0;
112    for (i = 0; i < 27; i++) 
113      for (j = 0; j < 27; j++)
114         it_oofreq[i][j] = 0;
115    it_lastopc = 0;
116 }
117
118 void interp_shutdown ( void )
119 {
120    int i, j, k, o_max, i_max, j_max;
121    debugBelch("%d constrs entered -> (%d BCO, %d UPD, %d ??? )\n",
122                    it_retto_BCO + it_retto_UPDATE + it_retto_other,
123                    it_retto_BCO, it_retto_UPDATE, it_retto_other );
124    debugBelch("%d total entries, %d unknown entries \n", 
125                    it_total_entries, it_total_unknown_entries);
126    for (i = 0; i < N_CLOSURE_TYPES; i++) {
127      if (it_unknown_entries[i] == 0) continue;
128      debugBelch("   type %2d: unknown entries (%4.1f%%) == %d\n",
129              i, 100.0 * ((double)it_unknown_entries[i]) / 
130                         ((double)it_total_unknown_entries),
131              it_unknown_entries[i]);
132    }
133    debugBelch("%d insns, %d slides, %d BCO_entries\n", 
134                    it_insns, it_slides, it_BCO_entries);
135    for (i = 0; i < 27; i++) 
136       debugBelch("opcode %2d got %d\n", i, it_ofreq[i] );
137
138    for (k = 1; k < 20; k++) {
139       o_max = 0;
140       i_max = j_max = 0;
141       for (i = 0; i < 27; i++) {
142          for (j = 0; j < 27; j++) {
143             if (it_oofreq[i][j] > o_max) {
144                o_max = it_oofreq[i][j];
145                i_max = i; j_max = j;
146             }
147          }
148       }
149       
150       debugBelch("%d:  count (%4.1f%%) %6d   is %d then %d\n",
151                 k, ((double)o_max) * 100.0 / ((double)it_insns), o_max,
152                    i_max, j_max );
153       it_oofreq[i_max][j_max] = 0;
154
155    }
156 }
157
158 #else // !INTERP_STATS
159
160 #define INTERP_TICK(n) /* nothing */
161
162 #endif
163
164 static StgWord app_ptrs_itbl[] = {
165     (W_)&stg_ap_p_info,
166     (W_)&stg_ap_pp_info,
167     (W_)&stg_ap_ppp_info,
168     (W_)&stg_ap_pppp_info,
169     (W_)&stg_ap_ppppp_info,
170     (W_)&stg_ap_pppppp_info,
171 };
172
173 StgThreadReturnCode
174 interpretBCO (Capability* cap)
175 {
176     // Use of register here is primarily to make it clear to compilers
177     // that these entities are non-aliasable.
178     register StgPtr       Sp;    // local state -- stack pointer
179     register StgPtr       SpLim; // local state -- stack lim pointer
180     register StgClosure*  obj;
181     nat n, m;
182
183     LOAD_STACK_POINTERS;
184
185     // ------------------------------------------------------------------------
186     // Case 1:
187     // 
188     //       We have a closure to evaluate.  Stack looks like:
189     //       
190     //          |   XXXX_info   |
191     //          +---------------+
192     //       Sp |      -------------------> closure
193     //          +---------------+
194     //       
195     if (Sp[0] == (W_)&stg_enter_info) {
196         Sp++;
197         goto eval;
198     }
199
200     // ------------------------------------------------------------------------
201     // Case 2:
202     // 
203     //       We have a BCO application to perform.  Stack looks like:
204     //
205     //          |     ....      |
206     //          +---------------+
207     //          |     arg1      |
208     //          +---------------+
209     //          |     BCO       |
210     //          +---------------+
211     //       Sp |   RET_BCO     |
212     //          +---------------+
213     //       
214     else if (Sp[0] == (W_)&stg_apply_interp_info) {
215         obj = (StgClosure *)Sp[1];
216         Sp += 2;
217         goto run_BCO_fun;
218     }
219
220     // ------------------------------------------------------------------------
221     // Case 3:
222     //
223     //       We have an unboxed value to return.  See comment before
224     //       do_return_unboxed, below.
225     //
226     else {
227         goto do_return_unboxed;
228     }
229
230     // Evaluate the object on top of the stack.
231 eval:
232     obj = (StgClosure*)Sp[0]; Sp++;
233
234 eval_obj:
235     INTERP_TICK(it_total_evals);
236
237     IF_DEBUG(interpreter,
238              debugBelch(
239              "\n---------------------------------------------------------------\n");
240              debugBelch("Evaluating: "); printObj(obj);
241              debugBelch("Sp = %p\n", Sp);
242              debugBelch("\n" );
243
244              printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
245              debugBelch("\n\n");
246             );
247
248     IF_DEBUG(sanity,checkStackChunk(Sp, cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size));
249
250     switch ( get_itbl(obj)->type ) {
251
252     case IND:
253     case IND_OLDGEN:
254     case IND_PERM:
255     case IND_OLDGEN_PERM:
256     case IND_STATIC:
257     { 
258         obj = ((StgInd*)obj)->indirectee;
259         goto eval_obj;
260     }
261     
262     case CONSTR:
263     case CONSTR_1_0:
264     case CONSTR_0_1:
265     case CONSTR_2_0:
266     case CONSTR_1_1:
267     case CONSTR_0_2:
268     case CONSTR_INTLIKE:
269     case CONSTR_CHARLIKE:
270     case CONSTR_STATIC:
271     case CONSTR_NOCAF_STATIC:
272     case FUN:
273     case FUN_1_0:
274     case FUN_0_1:
275     case FUN_2_0:
276     case FUN_1_1:
277     case FUN_0_2:
278     case FUN_STATIC:
279     case PAP:
280         // already in WHNF
281         break;
282         
283     case BCO:
284         ASSERT(((StgBCO *)obj)->arity > 0);
285         break;
286
287     case AP:    /* Copied from stg_AP_entry. */
288     {
289         nat i, words;
290         StgAP *ap;
291         
292         ap = (StgAP*)obj;
293         words = ap->n_args;
294         
295         // Stack check
296         if (Sp - (words+sizeofW(StgUpdateFrame)) < SpLim) {
297             Sp -= 2;
298             Sp[1] = (W_)obj;
299             Sp[0] = (W_)&stg_enter_info;
300             RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
301         }
302         
303         /* Ok; we're safe.  Party on.  Push an update frame. */
304         Sp -= sizeofW(StgUpdateFrame);
305         {
306             StgUpdateFrame *__frame;
307             __frame = (StgUpdateFrame *)Sp;
308             SET_INFO(__frame, (StgInfoTable *)&stg_upd_frame_info);
309             __frame->updatee = (StgClosure *)(ap);
310         }
311         
312         /* Reload the stack */
313         Sp -= words;
314         for (i=0; i < words; i++) {
315             Sp[i] = (W_)ap->payload[i];
316         }
317
318         obj = (StgClosure*)ap->fun;
319         ASSERT(get_itbl(obj)->type == BCO);
320         goto run_BCO_fun;
321     }
322
323     default:
324 #ifdef INTERP_STATS
325     { 
326         int j;
327         
328         j = get_itbl(obj)->type;
329         ASSERT(j >= 0 && j < N_CLOSURE_TYPES);
330         it_unknown_entries[j]++;
331         it_total_unknown_entries++;
332     }
333 #endif
334     {
335         // Can't handle this object; yield to scheduler
336         IF_DEBUG(interpreter,
337                  debugBelch("evaluating unknown closure -- yielding to sched\n"); 
338                  printObj(obj);
339             );
340         Sp -= 2;
341         Sp[1] = (W_)obj;
342         Sp[0] = (W_)&stg_enter_info;
343         RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
344     }
345     }
346
347     // ------------------------------------------------------------------------
348     // We now have an evaluated object (obj).  The next thing to
349     // do is return it to the stack frame on top of the stack.
350 do_return:
351     ASSERT(closure_HNF(obj));
352
353     IF_DEBUG(interpreter,
354              debugBelch(
355              "\n---------------------------------------------------------------\n");
356              debugBelch("Returning: "); printObj(obj);
357              debugBelch("Sp = %p\n", Sp);
358              debugBelch("\n" );
359              printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
360              debugBelch("\n\n");
361             );
362
363     IF_DEBUG(sanity,checkStackChunk(Sp, cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size));
364
365     switch (get_itbl((StgClosure *)Sp)->type) {
366
367     case RET_SMALL: {
368         const StgInfoTable *info;
369
370         // NOTE: not using get_itbl().
371         info = ((StgClosure *)Sp)->header.info;
372         if (info == (StgInfoTable *)&stg_ap_v_info) {
373             n = 1; m = 0; goto do_apply;
374         }
375         if (info == (StgInfoTable *)&stg_ap_f_info) {
376             n = 1; m = 1; goto do_apply;
377         }
378         if (info == (StgInfoTable *)&stg_ap_d_info) {
379             n = 1; m = sizeofW(StgDouble); goto do_apply;
380         }
381         if (info == (StgInfoTable *)&stg_ap_l_info) {
382             n = 1; m = sizeofW(StgInt64); goto do_apply;
383         }
384         if (info == (StgInfoTable *)&stg_ap_n_info) {
385             n = 1; m = 1; goto do_apply;
386         }
387         if (info == (StgInfoTable *)&stg_ap_p_info) {
388             n = 1; m = 1; goto do_apply;
389         }
390         if (info == (StgInfoTable *)&stg_ap_pp_info) {
391             n = 2; m = 2; goto do_apply;
392         }
393         if (info == (StgInfoTable *)&stg_ap_ppp_info) {
394             n = 3; m = 3; goto do_apply;
395         }
396         if (info == (StgInfoTable *)&stg_ap_pppp_info) {
397             n = 4; m = 4; goto do_apply;
398         }
399         if (info == (StgInfoTable *)&stg_ap_ppppp_info) {
400             n = 5; m = 5; goto do_apply;
401         }
402         if (info == (StgInfoTable *)&stg_ap_pppppp_info) {
403             n = 6; m = 6; goto do_apply;
404         }
405         goto do_return_unrecognised;
406     }
407
408     case UPDATE_FRAME:
409         // Returning to an update frame: do the update, pop the update
410         // frame, and continue with the next stack frame.
411         INTERP_TICK(it_retto_UPDATE);
412         UPD_IND(((StgUpdateFrame *)Sp)->updatee, obj); 
413         Sp += sizeofW(StgUpdateFrame);
414         goto do_return;
415
416     case RET_BCO:
417         // Returning to an interpreted continuation: put the object on
418         // the stack, and start executing the BCO.
419         INTERP_TICK(it_retto_BCO);
420         Sp--;
421         Sp[0] = (W_)obj;
422         obj = (StgClosure*)Sp[2];
423         ASSERT(get_itbl(obj)->type == BCO);
424         goto run_BCO_return;
425
426     default:
427     do_return_unrecognised:
428     {
429         // Can't handle this return address; yield to scheduler
430         INTERP_TICK(it_retto_other);
431         IF_DEBUG(interpreter,
432                  debugBelch("returning to unknown frame -- yielding to sched\n"); 
433                  printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
434             );
435         Sp -= 2;
436         Sp[1] = (W_)obj;
437         Sp[0] = (W_)&stg_enter_info;
438         RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
439     }
440     }
441
442     // -------------------------------------------------------------------------
443     // Returning an unboxed value.  The stack looks like this:
444     //
445     //    |     ....      |
446     //    +---------------+
447     //    |     fv2       |
448     //    +---------------+
449     //    |     fv1       |
450     //    +---------------+
451     //    |     BCO       |
452     //    +---------------+
453     //    | stg_ctoi_ret_ |
454     //    +---------------+
455     //    |    retval     |
456     //    +---------------+
457     //    |   XXXX_info   |
458     //    +---------------+
459     //
460     // where XXXX_info is one of the stg_gc_unbx_r1_info family.
461     //
462     // We're only interested in the case when the real return address
463     // is a BCO; otherwise we'll return to the scheduler.
464
465 do_return_unboxed:
466     { 
467         int offset;
468         
469         ASSERT( Sp[0] == (W_)&stg_gc_unbx_r1_info
470                 || Sp[0] == (W_)&stg_gc_unpt_r1_info
471                 || Sp[0] == (W_)&stg_gc_f1_info
472                 || Sp[0] == (W_)&stg_gc_d1_info
473                 || Sp[0] == (W_)&stg_gc_l1_info
474                 || Sp[0] == (W_)&stg_gc_void_info // VoidRep
475             );
476
477         // get the offset of the stg_ctoi_ret_XXX itbl
478         offset = stack_frame_sizeW((StgClosure *)Sp);
479
480         switch (get_itbl((StgClosure *)Sp+offset)->type) {
481
482         case RET_BCO:
483             // Returning to an interpreted continuation: put the object on
484             // the stack, and start executing the BCO.
485             INTERP_TICK(it_retto_BCO);
486             obj = (StgClosure*)Sp[offset+1];
487             ASSERT(get_itbl(obj)->type == BCO);
488             goto run_BCO_return_unboxed;
489
490         default:
491         {
492             // Can't handle this return address; yield to scheduler
493             INTERP_TICK(it_retto_other);
494             IF_DEBUG(interpreter,
495                      debugBelch("returning to unknown frame -- yielding to sched\n"); 
496                      printStackChunk(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size);
497                 );
498             RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
499         }
500         }
501     }
502     // not reached.
503
504
505     // -------------------------------------------------------------------------
506     // Application...
507
508 do_apply:
509     // we have a function to apply (obj), and n arguments taking up m
510     // words on the stack.  The info table (stg_ap_pp_info or whatever)
511     // is on top of the arguments on the stack.
512     {
513         switch (get_itbl(obj)->type) {
514
515         case PAP: {
516             StgPAP *pap;
517             nat i, arity;
518
519             pap = (StgPAP *)obj;
520
521             // we only cope with PAPs whose function is a BCO
522             if (get_itbl(pap->fun)->type != BCO) {
523                 goto defer_apply_to_sched;
524             }
525
526             Sp++;
527             arity = pap->arity;
528             ASSERT(arity > 0);
529             if (arity < n) {
530                 // n must be greater than 1, and the only kinds of
531                 // application we support with more than one argument
532                 // are all pointers...
533                 //
534                 // Shuffle the args for this function down, and put
535                 // the appropriate info table in the gap.
536                 for (i = 0; i < arity; i++) {
537                     Sp[(int)i-1] = Sp[i];
538                     // ^^^^^ careful, i-1 might be negative, but i in unsigned
539                 }
540                 Sp[arity-1] = app_ptrs_itbl[n-arity-1];
541                 Sp--;
542                 // unpack the PAP's arguments onto the stack
543                 Sp -= pap->n_args;
544                 for (i = 0; i < pap->n_args; i++) {
545                     Sp[i] = (W_)pap->payload[i];
546                 }
547                 obj = pap->fun;
548                 goto run_BCO_fun;
549             } 
550             else if (arity == n) {
551                 Sp -= pap->n_args;
552                 for (i = 0; i < pap->n_args; i++) {
553                     Sp[i] = (W_)pap->payload[i];
554                 }
555                 obj = pap->fun;
556                 goto run_BCO_fun;
557             } 
558             else /* arity > n */ {
559                 // build a new PAP and return it.
560                 StgPAP *new_pap;
561                 nat size;
562                 size = PAP_sizeW(pap->n_args + m);
563                 new_pap = (StgPAP *)allocate(size);
564                 SET_HDR(new_pap,&stg_PAP_info,CCCS);
565                 new_pap->arity = pap->arity - n;
566                 new_pap->n_args = pap->n_args + m;
567                 new_pap->fun = pap->fun;
568                 for (i = 0; i < pap->n_args; i++) {
569                     new_pap->payload[i] = pap->payload[i];
570                 }
571                 for (i = 0; i < m; i++) {
572                     new_pap->payload[pap->n_args + i] = (StgClosure *)Sp[i];
573                 }
574                 obj = (StgClosure *)new_pap;
575                 Sp += m;
576                 goto do_return;
577             }
578         }           
579
580         case BCO: {
581             nat arity, i;
582
583             Sp++;
584             arity = ((StgBCO *)obj)->arity;
585             ASSERT(arity > 0);
586             if (arity < n) {
587                 // n must be greater than 1, and the only kinds of
588                 // application we support with more than one argument
589                 // are all pointers...
590                 //
591                 // Shuffle the args for this function down, and put
592                 // the appropriate info table in the gap.
593                 for (i = 0; i < arity; i++) {
594                     Sp[(int)i-1] = Sp[i];
595                     // ^^^^^ careful, i-1 might be negative, but i in unsigned
596                 }
597                 Sp[arity-1] = app_ptrs_itbl[n-arity-1];
598                 Sp--;
599                 goto run_BCO_fun;
600             } 
601             else if (arity == n) {
602                 goto run_BCO_fun;
603             }
604             else /* arity > n */ {
605                 // build a PAP and return it.
606                 StgPAP *pap;
607                 nat size, i;
608                 size = PAP_sizeW(m);
609                 pap = (StgPAP *)allocate(size);
610                 SET_HDR(pap, &stg_PAP_info,CCCS);
611                 pap->arity = arity - n;
612                 pap->fun = obj;
613                 pap->n_args = m;
614                 for (i = 0; i < m; i++) {
615                     pap->payload[i] = (StgClosure *)Sp[i];
616                 }
617                 obj = (StgClosure *)pap;
618                 Sp += m;
619                 goto do_return;
620             }
621         }
622
623         // No point in us applying machine-code functions
624         default:
625         defer_apply_to_sched:
626             Sp -= 2;
627             Sp[1] = (W_)obj;
628             Sp[0] = (W_)&stg_enter_info;
629             RETURN_TO_SCHEDULER_NO_PAUSE(ThreadRunGHC, ThreadYielding);
630     }
631
632     // ------------------------------------------------------------------------
633     // Ok, we now have a bco (obj), and its arguments are all on the
634     // stack.  We can start executing the byte codes.
635     //
636     // The stack is in one of two states.  First, if this BCO is a
637     // function:
638     //
639     //    |     ....      |
640     //    +---------------+
641     //    |     arg2      |
642     //    +---------------+
643     //    |     arg1      |
644     //    +---------------+
645     //
646     // Second, if this BCO is a continuation:
647     //
648     //    |     ....      |
649     //    +---------------+
650     //    |     fv2       |
651     //    +---------------+
652     //    |     fv1       |
653     //    +---------------+
654     //    |     BCO       |
655     //    +---------------+
656     //    | stg_ctoi_ret_ |
657     //    +---------------+
658     //    |    retval     |
659     //    +---------------+
660     // 
661     // where retval is the value being returned to this continuation.
662     // In the event of a stack check, heap check, or context switch,
663     // we need to leave the stack in a sane state so the garbage
664     // collector can find all the pointers.
665     //
666     //  (1) BCO is a function:  the BCO's bitmap describes the
667     //      pointerhood of the arguments.
668     //
669     //  (2) BCO is a continuation: BCO's bitmap describes the
670     //      pointerhood of the free variables.
671     //
672     // Sadly we have three different kinds of stack/heap/cswitch check
673     // to do:
674
675 run_BCO_return:
676     // Heap check
677     if (doYouWantToGC()) {
678         Sp--; Sp[0] = (W_)&stg_enter_info;
679         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
680     }
681     // Stack checks aren't necessary at return points, the stack use
682     // is aggregated into the enclosing function entry point.
683     goto run_BCO;
684     
685 run_BCO_return_unboxed:
686     // Heap check
687     if (doYouWantToGC()) {
688         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
689     }
690     // Stack checks aren't necessary at return points, the stack use
691     // is aggregated into the enclosing function entry point.
692     goto run_BCO;
693     
694 run_BCO_fun:
695     IF_DEBUG(sanity,
696              Sp -= 2; 
697              Sp[1] = (W_)obj; 
698              Sp[0] = (W_)&stg_apply_interp_info;
699              checkStackChunk(Sp,SpLim);
700              Sp += 2;
701         );
702
703     // Heap check
704     if (doYouWantToGC()) {
705         Sp -= 2; 
706         Sp[1] = (W_)obj; 
707         Sp[0] = (W_)&stg_apply_interp_info; // placeholder, really
708         RETURN_TO_SCHEDULER(ThreadInterpret, HeapOverflow);
709     }
710     
711     // Stack check
712     if (Sp - INTERP_STACK_CHECK_THRESH < SpLim) {
713         Sp -= 2; 
714         Sp[1] = (W_)obj; 
715         Sp[0] = (W_)&stg_apply_interp_info; // placeholder, really
716         RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
717     }
718     goto run_BCO;
719     
720     // Now, actually interpret the BCO... (no returning to the
721     // scheduler again until the stack is in an orderly state).
722 run_BCO:
723     INTERP_TICK(it_BCO_entries);
724     {
725         register int       bciPtr     = 1; /* instruction pointer */
726         register StgBCO*   bco        = (StgBCO*)obj;
727         register StgWord16* instrs    = (StgWord16*)(bco->instrs->payload);
728         register StgWord*  literals   = (StgWord*)(&bco->literals->payload[0]);
729         register StgPtr*   ptrs       = (StgPtr*)(&bco->ptrs->payload[0]);
730         register StgInfoTable** itbls = (StgInfoTable**)
731             (&bco->itbls->payload[0]);
732
733 #ifdef INTERP_STATS
734         it_lastopc = 0; /* no opcode */
735 #endif
736
737     nextInsn:
738         ASSERT(bciPtr <= instrs[0]);
739         IF_DEBUG(interpreter,
740                  //if (do_print_stack) {
741                  //debugBelch("\n-- BEGIN stack\n");
742                  //printStack(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size,iSu);
743                  //debugBelch("-- END stack\n\n");
744                  //}
745                  debugBelch("Sp = %p   pc = %d      ", Sp, bciPtr);
746                  disInstr(bco,bciPtr);
747                  if (0) { int i;
748                  debugBelch("\n");
749                  for (i = 8; i >= 0; i--) {
750                      debugBelch("%d  %p\n", i, (StgPtr)(*(Sp+i)));
751                  }
752                  debugBelch("\n");
753                  }
754                  //if (do_print_stack) checkStack(Sp,cap->r.rCurrentTSO->stack+cap->r.rCurrentTSO->stack_size,iSu);
755             );
756
757         INTERP_TICK(it_insns);
758
759 #ifdef INTERP_STATS
760         ASSERT( (int)instrs[bciPtr] >= 0 && (int)instrs[bciPtr] < 27 );
761         it_ofreq[ (int)instrs[bciPtr] ] ++;
762         it_oofreq[ it_lastopc ][ (int)instrs[bciPtr] ] ++;
763         it_lastopc = (int)instrs[bciPtr];
764 #endif
765
766         switch (BCO_NEXT) {
767
768         case bci_STKCHECK: {
769             // Explicit stack check at the beginning of a function
770             // *only* (stack checks in case alternatives are
771             // propagated to the enclosing function).
772             int stk_words_reqd = BCO_NEXT + 1;
773             if (Sp - stk_words_reqd < SpLim) {
774                 Sp -= 2; 
775                 Sp[1] = (W_)obj; 
776                 Sp[0] = (W_)&stg_apply_interp_info;
777                 RETURN_TO_SCHEDULER(ThreadInterpret, StackOverflow);
778             } else {
779                 goto nextInsn;
780             }
781         }
782
783         case bci_PUSH_L: {
784             int o1 = BCO_NEXT;
785             Sp[-1] = Sp[o1];
786             Sp--;
787             goto nextInsn;
788         }
789
790         case bci_PUSH_LL: {
791             int o1 = BCO_NEXT;
792             int o2 = BCO_NEXT;
793             Sp[-1] = Sp[o1];
794             Sp[-2] = Sp[o2];
795             Sp -= 2;
796             goto nextInsn;
797         }
798
799         case bci_PUSH_LLL: {
800             int o1 = BCO_NEXT;
801             int o2 = BCO_NEXT;
802             int o3 = BCO_NEXT;
803             Sp[-1] = Sp[o1];
804             Sp[-2] = Sp[o2];
805             Sp[-3] = Sp[o3];
806             Sp -= 3;
807             goto nextInsn;
808         }
809
810         case bci_PUSH_G: {
811             int o1 = BCO_NEXT;
812             Sp[-1] = BCO_PTR(o1);
813             Sp -= 1;
814             goto nextInsn;
815         }
816
817         case bci_PUSH_ALTS: {
818             int o_bco  = BCO_NEXT;
819             Sp[-2] = (W_)&stg_ctoi_R1p_info;
820             Sp[-1] = BCO_PTR(o_bco);
821             Sp -= 2;
822             goto nextInsn;
823         }
824
825         case bci_PUSH_ALTS_P: {
826             int o_bco  = BCO_NEXT;
827             Sp[-2] = (W_)&stg_ctoi_R1unpt_info;
828             Sp[-1] = BCO_PTR(o_bco);
829             Sp -= 2;
830             goto nextInsn;
831         }
832
833         case bci_PUSH_ALTS_N: {
834             int o_bco  = BCO_NEXT;
835             Sp[-2] = (W_)&stg_ctoi_R1n_info;
836             Sp[-1] = BCO_PTR(o_bco);
837             Sp -= 2;
838             goto nextInsn;
839         }
840
841         case bci_PUSH_ALTS_F: {
842             int o_bco  = BCO_NEXT;
843             Sp[-2] = (W_)&stg_ctoi_F1_info;
844             Sp[-1] = BCO_PTR(o_bco);
845             Sp -= 2;
846             goto nextInsn;
847         }
848
849         case bci_PUSH_ALTS_D: {
850             int o_bco  = BCO_NEXT;
851             Sp[-2] = (W_)&stg_ctoi_D1_info;
852             Sp[-1] = BCO_PTR(o_bco);
853             Sp -= 2;
854             goto nextInsn;
855         }
856
857         case bci_PUSH_ALTS_L: {
858             int o_bco  = BCO_NEXT;
859             Sp[-2] = (W_)&stg_ctoi_L1_info;
860             Sp[-1] = BCO_PTR(o_bco);
861             Sp -= 2;
862             goto nextInsn;
863         }
864
865         case bci_PUSH_ALTS_V: {
866             int o_bco  = BCO_NEXT;
867             Sp[-2] = (W_)&stg_ctoi_V_info;
868             Sp[-1] = BCO_PTR(o_bco);
869             Sp -= 2;
870             goto nextInsn;
871         }
872
873         case bci_PUSH_APPLY_N:
874             Sp--; Sp[0] = (W_)&stg_ap_n_info;
875             goto nextInsn;
876         case bci_PUSH_APPLY_V:
877             Sp--; Sp[0] = (W_)&stg_ap_v_info;
878             goto nextInsn;
879         case bci_PUSH_APPLY_F:
880             Sp--; Sp[0] = (W_)&stg_ap_f_info;
881             goto nextInsn;
882         case bci_PUSH_APPLY_D:
883             Sp--; Sp[0] = (W_)&stg_ap_d_info;
884             goto nextInsn;
885         case bci_PUSH_APPLY_L:
886             Sp--; Sp[0] = (W_)&stg_ap_l_info;
887             goto nextInsn;
888         case bci_PUSH_APPLY_P:
889             Sp--; Sp[0] = (W_)&stg_ap_p_info;
890             goto nextInsn;
891         case bci_PUSH_APPLY_PP:
892             Sp--; Sp[0] = (W_)&stg_ap_pp_info;
893             goto nextInsn;
894         case bci_PUSH_APPLY_PPP:
895             Sp--; Sp[0] = (W_)&stg_ap_ppp_info;
896             goto nextInsn;
897         case bci_PUSH_APPLY_PPPP:
898             Sp--; Sp[0] = (W_)&stg_ap_pppp_info;
899             goto nextInsn;
900         case bci_PUSH_APPLY_PPPPP:
901             Sp--; Sp[0] = (W_)&stg_ap_ppppp_info;
902             goto nextInsn;
903         case bci_PUSH_APPLY_PPPPPP:
904             Sp--; Sp[0] = (W_)&stg_ap_pppppp_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] = (W_)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;
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;
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;
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                      debugBelch("\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                      debugBelch("\tBuilt "); 
1010                      printObj((StgClosure*)con);
1011                 );
1012             goto nextInsn;
1013         }
1014
1015         case bci_TESTLT_P: {
1016             unsigned int discr  = BCO_NEXT;
1017             int failto = BCO_NEXT;
1018             StgClosure* con = (StgClosure*)Sp[0];
1019             if (GET_TAG(con) >= discr) {
1020                 bciPtr = failto;
1021             }
1022             goto nextInsn;
1023         }
1024
1025         case bci_TESTEQ_P: {
1026             unsigned int discr  = BCO_NEXT;
1027             int failto = BCO_NEXT;
1028             StgClosure* con = (StgClosure*)Sp[0];
1029             if (GET_TAG(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             int ret_dyn_size = 
1164                 RET_DYN_BITMAP_SIZE + RET_DYN_NONPTR_REGS_SIZE
1165                 + sizeofW(StgRetDyn);
1166
1167 #ifdef RTS_SUPPORTS_THREADS
1168             // Threaded RTS:
1169             // Arguments on the TSO stack are not good, because garbage
1170             // collection might move the TSO as soon as we call
1171             // suspendThread below.
1172
1173             W_ arguments[stk_offset];
1174             
1175             memcpy(arguments, Sp, sizeof(W_) * stk_offset);
1176 #endif
1177
1178             // Restore the Haskell thread's current value of errno
1179             errno = cap->r.rCurrentTSO->saved_errno;
1180
1181             // There are a bunch of non-ptr words on the stack (the
1182             // ccall args, the ccall fun address and space for the
1183             // result), which we need to cover with an info table
1184             // since we might GC during this call.
1185             //
1186             // We know how many (non-ptr) words there are before the
1187             // next valid stack frame: it is the stk_offset arg to the
1188             // CCALL instruction.   So we build a RET_DYN stack frame
1189             // on the stack frame to describe this chunk of stack.
1190             //
1191             Sp -= ret_dyn_size;
1192             ((StgRetDyn *)Sp)->liveness = NO_PTRS | N_NONPTRS(stk_offset);
1193             ((StgRetDyn *)Sp)->info = (StgInfoTable *)&stg_gc_gen_info;
1194
1195             SAVE_STACK_POINTERS;
1196             tok = suspendThread(&cap->r);
1197
1198 #ifndef RTS_SUPPORTS_THREADS
1199             // Careful:
1200             // suspendThread might have shifted the stack
1201             // around (stack squeezing), so we have to grab the real
1202             // Sp out of the TSO to find the ccall args again.
1203
1204             marshall_fn ( (void*)(cap->r.rCurrentTSO->sp + ret_dyn_size) );
1205 #else
1206             // Threaded RTS:
1207             // We already made a copy of the arguments above.
1208
1209             marshall_fn ( arguments );
1210 #endif
1211
1212             // And restart the thread again, popping the RET_DYN frame.
1213             cap = (Capability *)((void *)((unsigned char*)resumeThread(tok) - sizeof(StgFunTable)));
1214             LOAD_STACK_POINTERS;
1215             Sp += ret_dyn_size;
1216             
1217             // Save the Haskell thread's current value of errno
1218             cap->r.rCurrentTSO->saved_errno = errno;
1219                 
1220 #ifdef RTS_SUPPORTS_THREADS
1221             // Threaded RTS:
1222             // Copy the "arguments", which might include a return value,
1223             // back to the TSO stack. It would of course be enough to
1224             // just copy the return value, but we don't know the offset.
1225             memcpy(Sp, arguments, sizeof(W_) * stk_offset);
1226 #endif
1227
1228             goto nextInsn;
1229         }
1230
1231         case bci_JMP: {
1232             /* BCO_NEXT modifies bciPtr, so be conservative. */
1233             int nextpc = BCO_NEXT;
1234             bciPtr     = nextpc;
1235             goto nextInsn;
1236         }
1237
1238         case bci_CASEFAIL:
1239             barf("interpretBCO: hit a CASEFAIL");
1240             
1241             // Errors
1242         default: 
1243             barf("interpretBCO: unknown or unimplemented opcode");
1244
1245         } /* switch on opcode */
1246     }
1247     }
1248
1249     barf("interpretBCO: fell off end of the interpreter");
1250 }