2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 % Code generation for tail calls.
9 cgTailCall, performTailCall,
10 performReturn, performPrimReturn,
11 returnUnboxedTuple, ccallReturnUnboxedTuple,
18 #include "HsVersions.h"
41 -----------------------------------------------------------------------------
44 cgTailCall :: Id -> [StgArg] -> Code
46 -- Here's the code we generate for a tail call. (NB there may be no
47 -- arguments, in which case this boils down to just entering a variable.)
49 -- * Put args in the top locations of the stack.
50 -- * Adjust the stack ptr
51 -- * Make R1 point to the function closure if necessary.
52 -- * Perform the call.
54 -- Things to be careful about:
56 -- * Don't overwrite stack locations before you have finished with
57 -- them (remember you need the function and the as-yet-unmoved
59 -- * Preferably, generate no code to replace x by x on the stack (a
60 -- common situation in tail-recursion).
61 -- * Adjust the stack high water mark appropriately.
63 -- Treat unboxed locals exactly like literals (above) except use the addr
64 -- mode for the local instead of (CLit lit) in the assignment.
67 = do { fun_info <- getCgIdInfo fun
69 ; if isUnLiftedType (idType fun)
70 then -- Primitive return
72 do { fun_amode <- idInfoToAmode fun_info
73 ; performPrimReturn (cgIdInfoArgRep fun_info) fun_amode }
75 else -- Normal case, fun is boxed
76 do { arg_amodes <- getArgAmodes args
77 ; performTailCall fun_info arg_amodes noStmts }
81 -- -----------------------------------------------------------------------------
82 -- The guts of a tail-call
85 :: CgIdInfo -- The function
86 -> [(CgRep,CmmExpr)] -- Args
87 -> CmmStmts -- Pending simultaneous assignments
88 -- *** GUARANTEED to contain only stack assignments.
91 performTailCall fun_info arg_amodes pending_assts
92 | Just join_sp <- maybeLetNoEscape fun_info
93 = -- A let-no-escape is slightly different, because we
94 -- arrange the stack arguments into pointers and non-pointers
95 -- to make the heap check easier. The tail-call sequence
96 -- is very similar to returning an unboxed tuple, so we
98 do { (final_sp, arg_assts) <- pushUnboxedTuple join_sp arg_amodes
99 ; emitSimultaneously (pending_assts `plusStmts` arg_assts)
100 ; let lbl = enterReturnPtLabel (idUnique (cgIdInfoId fun_info))
101 ; doFinalJump final_sp True {- Is LNE -} (jumpToLbl lbl) }
104 = do { fun_amode <- idInfoToAmode fun_info
105 ; let assignSt = CmmAssign nodeReg fun_amode
106 node_asst = oneStmt assignSt
107 opt_node_asst | nodeMustPointToIt lf_info = node_asst
108 | otherwise = noStmts
109 ; EndOfBlockInfo sp _ <- getEndOfBlockInfo
111 ; dflags <- getDynFlags
112 ; case (getCallMethod dflags fun_name fun_has_cafs lf_info (length arg_amodes)) of
114 -- Node must always point to things we enter
116 { emitSimultaneously (node_asst `plusStmts` pending_assts)
117 ; let target = entryCode (closureInfoPtr (CmmReg nodeReg))
118 enterClosure = stmtC (CmmJump target [])
119 -- If this is a scrutinee
120 -- let's check if the closure is a constructor
121 -- so we can directly jump to the alternatives switch
123 jumpInstr = getEndOfBlockInfo >>=
124 maybeSwitchOnCons enterClosure
125 ; doFinalJump sp False jumpInstr }
127 -- A function, but we have zero arguments. It is already in WHNF,
128 -- so we can just return it.
129 -- As with any return, Node must point to it.
131 { emitSimultaneously (node_asst `plusStmts` pending_assts)
132 ; doFinalJump sp False emitReturnInstr }
134 -- A real constructor. Don't bother entering it,
135 -- just do the right sort of return instead.
136 -- As with any return, Node must point to it.
138 { emitSimultaneously (node_asst `plusStmts` pending_assts)
139 ; doFinalJump sp False emitReturnInstr }
142 { emitSimultaneously (opt_node_asst `plusStmts` pending_assts)
143 ; doFinalJump sp False (jumpToLbl lbl) }
145 -- A slow function call via the RTS apply routines
146 -- Node must definitely point to the thing
148 { when (not (null arg_amodes)) $ do
149 { if (isKnownFun lf_info)
150 then tickyKnownCallTooFewArgs
151 else tickyUnknownCall
152 ; tickySlowCallPat (map fst arg_amodes)
155 ; let (apply_lbl, args, extra_args)
156 = constructSlowCall arg_amodes
158 ; directCall sp apply_lbl args extra_args
159 (node_asst `plusStmts` pending_assts)
163 -- A direct function call (possibly with some left-over arguments)
164 DirectEntry lbl arity -> do
165 { if arity == length arg_amodes
166 then tickyKnownCallExact
167 else do tickyKnownCallExtraArgs
168 tickySlowCallPat (map fst (drop arity arg_amodes))
171 -- The args beyond the arity go straight on the stack
172 (arity_args, extra_args) = splitAt arity arg_amodes
174 ; directCall sp lbl arity_args extra_args
175 (opt_node_asst `plusStmts` pending_assts)
179 fun_id = cgIdInfoId fun_info
180 fun_name = idName fun_id
181 lf_info = cgIdInfoLF fun_info
182 fun_has_cafs = idCafInfo fun_id
183 untag_node = CmmAssign nodeReg (cmmUntag (CmmReg nodeReg))
184 -- Test if closure is a constructor
185 maybeSwitchOnCons enterClosure eob
186 | EndOfBlockInfo _ (CaseAlts lbl _ _) <- eob
187 = do { is_constr <- newLabelC
188 -- Is the pointer tagged?
189 -- Yes, jump to switch statement
190 ; stmtC (CmmCondBranch (cmmIsTagged (CmmReg nodeReg))
192 -- No, enter the closure.
195 ; stmtC (CmmJump (entryCode $ CmmLit (CmmLabel lbl)) [])
198 -- This is a scrutinee for a case expression
199 -- so let's see if we can directly inspect the closure
200 | EndOfBlockInfo _ (CaseAlts lbl _ _ _) <- eob
201 = do { no_cons <- newLabelC
202 -- Both the NCG and gcc optimize away the temp
203 ; z <- newTemp wordRep
204 ; stmtC (CmmAssign z tag_expr)
206 -- Is the closure a cons?
207 ; stmtC (CmmCondBranch (cond1 tag) no_cons)
208 ; stmtC (CmmCondBranch (cond2 tag) no_cons)
209 -- Yes, jump to switch statement
210 ; stmtC (CmmJump (CmmLit (CmmLabel lbl)) [])
212 -- No, enter the closure.
216 -- No case expression involved, enter the closure.
218 = do { stmtC untag_node
222 --cond1 tag = cmmULtWord tag lowCons
223 -- More efficient than the above?
225 tag_expr = cmmGetClosureType (CmmReg nodeReg)
226 cond1 tag = cmmEqWord tag (CmmLit (mkIntCLit 0))
227 cond2 tag = cmmUGtWord tag highCons
228 lowCons = CmmLit (mkIntCLit 1)
230 highCons = CmmLit (mkIntCLit 8)
231 -- CONSTR_NOCAF_STATIC (from ClosureType.h)
234 directCall :: VirtualSpOffset -> CLabel -> [(CgRep, CmmExpr)]
235 -> [(CgRep, CmmExpr)] -> CmmStmts
237 directCall sp lbl args extra_args assts = do
239 -- First chunk of args go in registers
240 (reg_arg_amodes, stk_args) = assignCallRegs args
242 -- Any "extra" arguments are placed in frames on the
243 -- stack after the other arguments.
244 slow_stk_args = slowArgs extra_args
246 reg_assts = assignToRegs reg_arg_amodes
248 (final_sp, stk_assts) <- mkStkAmodes sp (stk_args ++ slow_stk_args)
250 emitSimultaneously (reg_assts `plusStmts`
251 stk_assts `plusStmts`
254 doFinalJump final_sp False (jumpToLbl lbl)
256 -- -----------------------------------------------------------------------------
257 -- The final clean-up before we do a jump at the end of a basic block.
258 -- This code is shared by tail-calls and returns.
260 doFinalJump :: VirtualSpOffset -> Bool -> Code -> Code
261 doFinalJump final_sp is_let_no_escape jump_code
262 = do { -- Adjust the high-water mark if necessary
263 adjustStackHW final_sp
265 -- Push a return address if necessary (after the assignments
266 -- above, in case we clobber a live stack location)
268 -- DONT push the return address when we're about to jump to a
269 -- let-no-escape: the final tail call in the let-no-escape
271 ; eob <- getEndOfBlockInfo
272 ; whenC (not is_let_no_escape) (pushReturnAddress eob)
274 -- Final adjustment of Sp/Hp
275 ; adjustSpAndHp final_sp
280 -- ----------------------------------------------------------------------------
281 -- A general return (just a special case of doFinalJump, above)
283 performReturn :: Code -- The code to execute to actually do the return
286 performReturn finish_code
287 = do { EndOfBlockInfo args_sp _sequel <- getEndOfBlockInfo
288 ; doFinalJump args_sp False{-not a LNE-} finish_code }
290 -- ----------------------------------------------------------------------------
292 -- Just load the return value into the right register, and return.
294 performPrimReturn :: CgRep -> CmmExpr -- The thing to return
296 performPrimReturn rep amode
297 = do { whenC (not (isVoidArg rep))
298 (stmtC (CmmAssign ret_reg amode))
299 ; performReturn emitReturnInstr }
301 ret_reg = dataReturnConvPrim rep
303 -- ---------------------------------------------------------------------------
304 -- Unboxed tuple returns
306 -- These are a bit like a normal tail call, except that:
308 -- - The tail-call target is an info table on the stack
310 -- - We separate stack arguments into pointers and non-pointers,
311 -- to make it easier to leave things in a sane state for a heap check.
312 -- This is OK because we can never partially-apply an unboxed tuple,
313 -- unlike a function. The same technique is used when calling
314 -- let-no-escape functions, because they also can't be partially
317 returnUnboxedTuple :: [(CgRep, CmmExpr)] -> Code
318 returnUnboxedTuple amodes
319 = do { (EndOfBlockInfo args_sp _sequel) <- getEndOfBlockInfo
320 ; tickyUnboxedTupleReturn (length amodes)
321 ; (final_sp, assts) <- pushUnboxedTuple args_sp amodes
322 ; emitSimultaneously assts
323 ; doFinalJump final_sp False{-not a LNE-} emitReturnInstr }
325 pushUnboxedTuple :: VirtualSpOffset -- Sp at which to start pushing
326 -> [(CgRep, CmmExpr)] -- amodes of the components
327 -> FCode (VirtualSpOffset, -- final Sp
328 CmmStmts) -- assignments (regs+stack)
330 pushUnboxedTuple sp []
331 = return (sp, noStmts)
332 pushUnboxedTuple sp amodes
333 = do { let (reg_arg_amodes, stk_arg_amodes) = assignReturnRegs amodes
335 -- separate the rest of the args into pointers and non-pointers
336 (ptr_args, nptr_args) = separateByPtrFollowness stk_arg_amodes
337 reg_arg_assts = assignToRegs reg_arg_amodes
339 -- push ptrs, then nonptrs, on the stack
340 ; (ptr_sp, ptr_assts) <- mkStkAmodes sp ptr_args
341 ; (final_sp, nptr_assts) <- mkStkAmodes ptr_sp nptr_args
343 ; returnFC (final_sp,
344 reg_arg_assts `plusStmts`
345 ptr_assts `plusStmts` nptr_assts) }
348 -- -----------------------------------------------------------------------------
349 -- Returning unboxed tuples. This is mainly to support _ccall_GC_, where
350 -- we want to do things in a slightly different order to normal:
352 -- - push return address
353 -- - adjust stack pointer
354 -- - r = call(args...)
355 -- - assign regs for unboxed tuple (usually just R1 = r)
356 -- - return to continuation
358 -- The return address (i.e. stack frame) must be on the stack before
359 -- doing the call in case the call ends up in the garbage collector.
361 -- Sadly, the information about the continuation is lost after we push it
362 -- (in order to avoid pushing it again), so we end up doing a needless
363 -- indirect jump (ToDo).
365 ccallReturnUnboxedTuple :: [(CgRep, CmmExpr)] -> Code -> Code
366 ccallReturnUnboxedTuple amodes before_jump
367 = do { eob@(EndOfBlockInfo args_sp _) <- getEndOfBlockInfo
369 -- Push a return address if necessary
370 ; pushReturnAddress eob
371 ; setEndOfBlockInfo (EndOfBlockInfo args_sp OnStack)
372 (do { adjustSpAndHp args_sp
374 ; returnUnboxedTuple amodes })
377 -- -----------------------------------------------------------------------------
378 -- Calling an out-of-line primop
380 tailCallPrimOp :: PrimOp -> [StgArg] -> Code
381 tailCallPrimOp op args
382 = do { -- We're going to perform a normal-looking tail call,
383 -- except that *all* the arguments will be in registers.
384 -- Hence the ASSERT( null leftovers )
385 arg_amodes <- getArgAmodes args
386 ; let (arg_regs, leftovers) = assignPrimOpCallRegs arg_amodes
387 jump_to_primop = jumpToLbl (mkRtsPrimOpLabel op)
389 ; ASSERT(null leftovers) -- no stack-resident args
390 emitSimultaneously (assignToRegs arg_regs)
392 ; EndOfBlockInfo args_sp _ <- getEndOfBlockInfo
393 ; doFinalJump args_sp False{-not a LNE-} jump_to_primop }
395 -- -----------------------------------------------------------------------------
398 -- We always push the return address just before performing a tail call
399 -- or return. The reason we leave it until then is because the stack
400 -- slot that the return address is to go into might contain something
403 -- If the end of block info is 'CaseAlts', then we're in the scrutinee of a
404 -- case expression and the return address is still to be pushed.
406 -- There are cases where it doesn't look necessary to push the return
407 -- address: for example, just before doing a return to a known
408 -- continuation. However, the continuation will expect to find the
409 -- return address on the stack in case it needs to do a heap check.
411 pushReturnAddress :: EndOfBlockInfo -> Code
413 pushReturnAddress (EndOfBlockInfo args_sp (CaseAlts lbl _ _))
414 = do { sp_rel <- getSpRelOffset args_sp
415 ; stmtC (CmmStore sp_rel (mkLblExpr lbl)) }
417 pushReturnAddress _ = nopC
419 -- -----------------------------------------------------------------------------
422 jumpToLbl :: CLabel -> Code
423 -- Passes no argument to the destination procedure
424 jumpToLbl lbl = stmtC (CmmJump (CmmLit (CmmLabel lbl)) [{- No args -}])
426 assignToRegs :: [(CmmExpr, GlobalReg)] -> CmmStmts
427 assignToRegs reg_args
428 = mkStmts [ CmmAssign (CmmGlobal reg_id) expr
429 | (expr, reg_id) <- reg_args ]
433 %************************************************************************
435 \subsection[CgStackery-adjust]{Adjusting the stack pointers}
437 %************************************************************************
439 This function adjusts the stack and heap pointers just before a tail
440 call or return. The stack pointer is adjusted to its final position
441 (i.e. to point to the last argument for a tail call, or the activation
442 record for a return). The heap pointer may be moved backwards, in
443 cases where we overallocated at the beginning of the basic block (see
444 CgCase.lhs for discussion).
446 These functions {\em do not} deal with high-water-mark adjustment.
447 That's done by functions which allocate stack space.
450 adjustSpAndHp :: VirtualSpOffset -- New offset for Arg stack ptr
452 adjustSpAndHp newRealSp
453 = do { -- Adjust stack, if necessary.
454 -- NB: the conditional on the monad-carried realSp
455 -- is out of line (via codeOnly), to avoid a black hole
456 ; new_sp <- getSpRelOffset newRealSp
457 ; checkedAbsC (CmmAssign spReg new_sp) -- Will generate no code in the case
458 ; setRealSp newRealSp -- where realSp==newRealSp
460 -- Adjust heap. The virtual heap pointer may be less than the real Hp
461 -- because the latter was advanced to deal with the worst-case branch
462 -- of the code, and we may be in a better-case branch. In that case,
463 -- move the real Hp *back* and retract some ticky allocation count.
464 ; hp_usg <- getHpUsage
465 ; let rHp = realHp hp_usg
467 ; new_hp <- getHpRelOffset vHp
468 ; checkedAbsC (CmmAssign hpReg new_hp) -- Generates nothing when vHp==rHp
469 ; tickyAllocHeap (vHp - rHp) -- ...ditto