MERGE: Fix a few uses of the wrong return convention for the scheduler
[ghc-hetmet.git] / rts / Exception.cmm
1 /* -----------------------------------------------------------------------------
2  *
3  * (c) The GHC Team, 1998-2004
4  *
5  * Exception support
6  *
7  * This file is written in a subset of C--, extended with various
8  * features specific to GHC.  It is compiled by GHC directly.  For the
9  * syntax of .cmm files, see the parser in ghc/compiler/cmm/CmmParse.y.
10  *
11  * ---------------------------------------------------------------------------*/
12
13 #include "Cmm.h"
14 #include "RaiseAsync.h"
15
16 /* -----------------------------------------------------------------------------
17    Exception Primitives
18
19    A thread can request that asynchronous exceptions not be delivered
20    ("blocked") for the duration of an I/O computation.  The primitive
21    
22         blockAsyncExceptions# :: IO a -> IO a
23
24    is used for this purpose.  During a blocked section, asynchronous
25    exceptions may be unblocked again temporarily:
26
27         unblockAsyncExceptions# :: IO a -> IO a
28
29    Furthermore, asynchronous exceptions are blocked automatically during
30    the execution of an exception handler.  Both of these primitives
31    leave a continuation on the stack which reverts to the previous
32    state (blocked or unblocked) on exit.
33
34    A thread which wants to raise an exception in another thread (using
35    killThread#) must block until the target thread is ready to receive
36    it.  The action of unblocking exceptions in a thread will release all
37    the threads waiting to deliver exceptions to that thread.
38
39    NB. there's a bug in here.  If a thread is inside an
40    unsafePerformIO, and inside blockAsyncExceptions# (there is an
41    unblockAsyncExceptions_ret on the stack), and it is blocked in an
42    interruptible operation, and it receives an exception, then the
43    unsafePerformIO thunk will be updated with a stack object
44    containing the unblockAsyncExceptions_ret frame.  Later, when
45    someone else evaluates this thunk, the blocked exception state is
46    not restored, and the result is that unblockAsyncExceptions_ret
47    will attempt to unblock exceptions in the current thread, but it'll
48    find that the CurrentTSO->blocked_exceptions is NULL.  Hence, we
49    work around this by checking for NULL in awakenBlockedQueue().
50
51    -------------------------------------------------------------------------- */
52
53 INFO_TABLE_RET( stg_unblockAsyncExceptionszh_ret,
54                 0/*framesize*/, 0/*bitmap*/, RET_SMALL )
55 {
56     CInt r;
57
58     // Not true: see comments above
59     // ASSERT(StgTSO_blocked_exceptions(CurrentTSO) != NULL);
60
61     StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
62         ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
63
64     /* Eagerly raise a blocked exception, if there is one */
65     if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
66         /* 
67          * We have to be very careful here, as in killThread#, since
68          * we are about to raise an async exception in the current
69          * thread, which might result in the thread being killed.
70          */
71
72 #ifndef REG_R1
73         /*
74          * raiseAsync assumes that the stack is in ThreadRunGHC state,
75          * i.e. with a return address on the top.  In unreg mode, the
76          * return value for IO is on top of the return address, so we
77          * need to make a small adjustment here.
78          */
79         Sp_adj(1);
80 #endif
81         SAVE_THREAD_STATE();
82         r = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
83                                                       CurrentTSO "ptr") [R1];
84
85         if (r != 0::CInt) {
86             if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
87                 jump stg_threadFinished;
88             } else {
89                 LOAD_THREAD_STATE();
90                 ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
91                 jump %ENTRY_CODE(Sp(0));
92             }
93         }
94 #ifndef REG_R1
95         /* 
96          * Readjust stack in unregisterised mode if we didn't raise an
97          * exception, see above
98          */
99         else {
100             Sp_adj(-1);
101         }
102 #endif
103     }
104
105 #ifdef REG_R1
106     Sp_adj(1);
107     jump %ENTRY_CODE(Sp(0));
108 #else
109     Sp(1) = Sp(0);
110     Sp_adj(1);
111     jump %ENTRY_CODE(Sp(1));
112 #endif
113 }
114
115 INFO_TABLE_RET( stg_blockAsyncExceptionszh_ret,
116                 0/*framesize*/, 0/*bitmap*/, RET_SMALL )
117 {
118     // Not true: see comments above
119     // ASSERT(StgTSO_blocked_exceptions(CurrentTSO) == NULL);
120
121     StgTSO_flags(CurrentTSO) = 
122         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
123
124 #ifdef REG_R1
125     Sp_adj(1);
126     jump %ENTRY_CODE(Sp(0));
127 #else
128     Sp(1) = Sp(0);
129     Sp_adj(1);
130     jump %ENTRY_CODE(Sp(1));
131 #endif
132 }
133
134 blockAsyncExceptionszh_fast
135 {
136     /* Args: R1 :: IO a */
137     STK_CHK_GEN( WDS(2)/* worst case */, R1_PTR, blockAsyncExceptionszh_fast);
138
139     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) == 0) {
140         
141         StgTSO_flags(CurrentTSO) = 
142            StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
143
144         /* avoid growing the stack unnecessarily */
145         if (Sp(0) == stg_blockAsyncExceptionszh_ret_info) {
146             Sp_adj(1);
147         } else {
148             Sp_adj(-1);
149             Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
150         }
151     }
152     TICK_UNKNOWN_CALL();
153     TICK_SLOW_CALL_v();
154     jump stg_ap_v_fast;
155 }
156
157 unblockAsyncExceptionszh_fast
158 {
159     CInt r;
160
161     /* Args: R1 :: IO a */
162     STK_CHK_GEN( WDS(2), R1_PTR, unblockAsyncExceptionszh_fast);
163
164     if ((TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX) != 0) {
165
166         StgTSO_flags(CurrentTSO) = StgTSO_flags(CurrentTSO) & 
167            ~(TSO_BLOCKEX::I32|TSO_INTERRUPTIBLE::I32);
168
169         /* Eagerly raise a blocked exception, if there is one */
170         if (StgTSO_blocked_exceptions(CurrentTSO) != END_TSO_QUEUE) {
171             /* 
172              * We have to be very careful here, as in killThread#, since
173              * we are about to raise an async exception in the current
174              * thread, which might result in the thread being killed.
175              */
176             SAVE_THREAD_STATE();
177             r = foreign "C" maybePerformBlockedException (MyCapability() "ptr", 
178                                                       CurrentTSO "ptr") [R1];
179
180             if (r != 0::CInt) {
181                 if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
182                     jump stg_threadFinished;
183                 } else {
184                     LOAD_THREAD_STATE();
185                     ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
186                     jump %ENTRY_CODE(Sp(0));
187                 }
188             }
189         }
190
191         /* avoid growing the stack unnecessarily */
192         if (Sp(0) == stg_unblockAsyncExceptionszh_ret_info) {
193             Sp_adj(1);
194         } else {
195             Sp_adj(-1);
196             Sp(0) = stg_blockAsyncExceptionszh_ret_info;
197         }
198     }
199     TICK_UNKNOWN_CALL();
200     TICK_SLOW_CALL_v();
201     jump stg_ap_v_fast;
202 }
203
204
205 killThreadzh_fast
206 {
207     /* args: R1 = TSO to kill, R2 = Exception */
208
209     W_ why_blocked;
210     W_ target;
211     W_ exception;
212     
213     target = R1;
214     exception = R2;
215     
216     STK_CHK_GEN( WDS(3), R1_PTR & R2_PTR, killThreadzh_fast);
217
218     /* 
219      * We might have killed ourselves.  In which case, better be *very*
220      * careful.  If the exception killed us, then return to the scheduler.
221      * If the exception went to a catch frame, we'll just continue from
222      * the handler.
223      */
224     if (target == CurrentTSO) {
225         SAVE_THREAD_STATE();
226         /* ToDo: what if the current thread is blocking exceptions? */
227         foreign "C" throwToSingleThreaded(MyCapability() "ptr", 
228                                           target "ptr", exception "ptr")[R1,R2];
229         if (StgTSO_what_next(CurrentTSO) == ThreadKilled::I16) {
230             jump stg_threadFinished;
231         } else {
232             LOAD_THREAD_STATE();
233             ASSERT(StgTSO_what_next(CurrentTSO) == ThreadRunGHC::I16);
234             jump %ENTRY_CODE(Sp(0));
235         }
236     } else {
237         W_ out;
238         W_ retcode;
239         out = BaseReg + OFFSET_StgRegTable_rmp_tmp_w;
240         
241         retcode = foreign "C" throwTo(MyCapability() "ptr",
242                                       CurrentTSO "ptr",
243                                       target "ptr",
244                                       exception "ptr",
245                                       out "ptr") [R1,R2];
246         
247         switch [THROWTO_SUCCESS .. THROWTO_BLOCKED] (retcode) {
248
249         case THROWTO_SUCCESS: {
250             jump %ENTRY_CODE(Sp(0));
251         }
252
253         case THROWTO_BLOCKED: {
254             R3 = W_[out];
255             // we must block, and call throwToReleaseTarget() before returning
256             jump stg_block_throwto;
257         }
258         }
259     }
260 }
261
262 /* -----------------------------------------------------------------------------
263    Catch frames
264    -------------------------------------------------------------------------- */
265
266 #ifdef REG_R1
267 #define SP_OFF 0
268 #else
269 #define SP_OFF 1
270 #endif
271
272 #if defined(PROFILING)
273 #define CATCH_FRAME_BITMAP 7
274 #define CATCH_FRAME_WORDS  4
275 #else
276 #define CATCH_FRAME_BITMAP 1
277 #define CATCH_FRAME_WORDS  2
278 #endif
279
280 /* Catch frames are very similar to update frames, but when entering
281  * one we just pop the frame off the stack and perform the correct
282  * kind of return to the activation record underneath us on the stack.
283  */
284
285 INFO_TABLE_RET(stg_catch_frame,
286                CATCH_FRAME_WORDS, CATCH_FRAME_BITMAP,
287                CATCH_FRAME)
288 #ifdef REG_R1
289    {
290       Sp = Sp + SIZEOF_StgCatchFrame;
291       jump %ENTRY_CODE(Sp(SP_OFF));
292    }
293 #else
294    {
295       W_ rval;
296       rval = Sp(0);
297       Sp = Sp + SIZEOF_StgCatchFrame;
298       Sp(0) = rval;
299       jump %ENTRY_CODE(Sp(SP_OFF));
300    }
301 #endif
302
303 /* -----------------------------------------------------------------------------
304  * The catch infotable
305  *
306  * This should be exactly the same as would be generated by this STG code
307  *
308  * catch = {x,h} \n {} -> catch#{x,h}
309  *
310  * It is used in deleteThread when reverting blackholes.
311  * -------------------------------------------------------------------------- */
312
313 INFO_TABLE(stg_catch,2,0,FUN,"catch","catch")
314 {
315   R2 = StgClosure_payload(R1,1); /* h */
316   R1 = StgClosure_payload(R1,0); /* x */
317   jump catchzh_fast;
318 }
319
320 catchzh_fast
321 {
322     /* args: R1 = m :: IO a, R2 = handler :: Exception -> IO a */
323     STK_CHK_GEN(SIZEOF_StgCatchFrame + WDS(1), R1_PTR & R2_PTR, catchzh_fast);
324   
325     /* Set up the catch frame */
326     Sp = Sp - SIZEOF_StgCatchFrame;
327     SET_HDR(Sp,stg_catch_frame_info,W_[CCCS]);
328     
329     StgCatchFrame_handler(Sp) = R2;
330     StgCatchFrame_exceptions_blocked(Sp) = TO_W_(StgTSO_flags(CurrentTSO)) & TSO_BLOCKEX;
331     TICK_CATCHF_PUSHED();
332
333     /* Apply R1 to the realworld token */
334     TICK_UNKNOWN_CALL();
335     TICK_SLOW_CALL_v();
336     jump stg_ap_v_fast;
337 }
338
339 /* -----------------------------------------------------------------------------
340  * The raise infotable
341  * 
342  * This should be exactly the same as would be generated by this STG code
343  *
344  *   raise = {err} \n {} -> raise#{err}
345  *
346  * It is used in raisezh_fast to update thunks on the update list
347  * -------------------------------------------------------------------------- */
348
349 INFO_TABLE(stg_raise,1,0,THUNK_1_0,"raise","raise")
350 {
351   R1 = StgThunk_payload(R1,0);
352   jump raisezh_fast;
353 }
354
355 raisezh_fast
356 {
357     W_ handler;
358     W_ raise_closure;
359     W_ frame_type;
360     /* args : R1 :: Exception */
361
362
363 #if defined(PROFILING)
364     /* Debugging tool: on raising an  exception, show where we are. */
365
366     /* ToDo: currently this is a hack.  Would be much better if
367      * the info was only displayed for an *uncaught* exception.
368      */
369     if (RtsFlags_ProfFlags_showCCSOnException(RtsFlags) != 0::I32) {
370       foreign "C" fprintCCS_stderr(W_[CCCS] "ptr");
371     }
372 #endif
373     
374     /* Inform the Hpc that an exception has been thrown */
375     foreign "C" hs_hpc_raise_event(CurrentTSO "ptr");
376
377 retry_pop_stack:
378     StgTSO_sp(CurrentTSO) = Sp;
379     frame_type = foreign "C" raiseExceptionHelper(BaseReg "ptr", CurrentTSO "ptr", R1 "ptr");
380     Sp = StgTSO_sp(CurrentTSO);
381     if (frame_type == ATOMICALLY_FRAME) {
382       /* The exception has reached the edge of a memory transaction.  Check that 
383        * the transaction is valid.  If not then perhaps the exception should
384        * not have been thrown: re-run the transaction.  "trec" will either be
385        * a top-level transaction running the atomic block, or a nested 
386        * transaction running an invariant check.  In the latter case we
387        * abort and de-allocate the top-level transaction that encloses it
388        * as well (we could just abandon its transaction record, but this makes
389        * sure it's marked as aborted and available for re-use). */
390       W_ trec, outer;
391       W_ r;
392       trec = StgTSO_trec(CurrentTSO);
393       r = foreign "C" stmValidateNestOfTransactions(trec "ptr");
394       "ptr" outer = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
395       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr");
396       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr");
397
398       if (outer != NO_TREC) {
399         foreign "C" stmAbortTransaction(MyCapability() "ptr", outer "ptr");
400         foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", outer "ptr");
401       }
402
403       StgTSO_trec(CurrentTSO) = NO_TREC;
404       if (r != 0) {
405         // Transaction was valid: continue searching for a catch frame
406         Sp = Sp + SIZEOF_StgAtomicallyFrame;
407         goto retry_pop_stack;
408       } else {
409         // Transaction was not valid: we retry the exception (otherwise continue
410         // with a further call to raiseExceptionHelper)
411         "ptr" trec = foreign "C" stmStartTransaction(MyCapability() "ptr", NO_TREC "ptr");
412         StgTSO_trec(CurrentTSO) = trec;
413         R1 = StgAtomicallyFrame_code(Sp);
414         jump stg_ap_v_fast;
415       }          
416     }
417
418     if (frame_type == STOP_FRAME) {
419         /*
420          * We've stripped the entire stack, the thread is now dead.
421          * We will leave the stack in a GC'able state, see the stg_stop_thread
422          * entry code in StgStartup.cmm.
423          */
424         Sp = CurrentTSO + TSO_OFFSET_StgTSO_stack 
425                 + WDS(TO_W_(StgTSO_stack_size(CurrentTSO))) - WDS(2);
426         Sp(1) = R1;             /* save the exception */
427         Sp(0) = stg_enter_info; /* so that GC can traverse this stack */
428         StgTSO_what_next(CurrentTSO) = ThreadKilled::I16;
429         SAVE_THREAD_STATE();    /* inline! */
430
431         jump stg_threadFinished;
432     }
433
434     /* Ok, Sp points to the enclosing CATCH_FRAME or CATCH_STM_FRAME.  Pop everything
435      * down to and including this frame, update Su, push R1, and enter the handler.
436      */
437     if (frame_type == CATCH_FRAME) {
438       handler = StgCatchFrame_handler(Sp);
439     } else {
440       handler = StgCatchSTMFrame_handler(Sp);
441     }
442
443     /* Restore the blocked/unblocked state for asynchronous exceptions
444      * at the CATCH_FRAME.  
445      *
446      * If exceptions were unblocked, arrange that they are unblocked
447      * again after executing the handler by pushing an
448      * unblockAsyncExceptions_ret stack frame.
449      *
450      * If we've reached an STM catch frame then roll back the nested
451      * transaction we were using.
452      */
453     W_ frame;
454     frame = Sp;
455     if (frame_type == CATCH_FRAME) {
456       Sp = Sp + SIZEOF_StgCatchFrame;
457       if (StgCatchFrame_exceptions_blocked(frame) == 0) {
458         Sp_adj(-1);
459         Sp(0) = stg_unblockAsyncExceptionszh_ret_info;
460       }
461     } else {
462       W_ trec, outer;
463       trec = StgTSO_trec(CurrentTSO);
464       "ptr" outer = foreign "C" stmGetEnclosingTRec(trec "ptr") [];
465       foreign "C" stmAbortTransaction(MyCapability() "ptr", trec "ptr") [];
466       foreign "C" stmFreeAbortedTRec(MyCapability() "ptr", trec "ptr") [];
467       StgTSO_trec(CurrentTSO) = outer;
468       Sp = Sp + SIZEOF_StgCatchSTMFrame;
469     }
470
471     /* Ensure that async excpetions are blocked when running the handler.
472     */
473     StgTSO_flags(CurrentTSO) = 
474         StgTSO_flags(CurrentTSO) | TSO_BLOCKEX::I32 | TSO_INTERRUPTIBLE::I32;
475
476     /* Call the handler, passing the exception value and a realworld
477      * token as arguments.
478      */
479     Sp_adj(-1);
480     Sp(0) = R1;
481     R1 = handler;
482     Sp_adj(-1);
483     TICK_UNKNOWN_CALL();
484     TICK_SLOW_CALL_pv();
485     jump RET_LBL(stg_ap_pv);
486 }
487
488 raiseIOzh_fast
489 {
490   /* Args :: R1 :: Exception */
491   jump raisezh_fast;
492 }