1 -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow 2004-2006
7 -- The datatypes and functions here encapsulate the
8 -- calling and return conventions used by the code generator.
10 -----------------------------------------------------------------------------
14 -- Argument descriptors
15 mkArgDescr, argDescrType,
18 isBigLiveness, buildContLiveness, mkRegLiveness,
19 smallLiveness, mkLivenessCLit,
21 -- Register assignment
22 assignCallRegs, assignReturnRegs, assignPrimOpCallRegs,
25 constructSlowCall, slowArgs, slowCallPattern,
28 CtrlReturnConvention(..),
34 #include "HsVersions.h"
60 -------------------------------------------------------------------------
62 -- Making argument descriptors
64 -- An argument descriptor describes the layout of args on the stack,
65 -- both for * GC (stack-layout) purposes, and
66 -- * saving/restoring registers when a heap-check fails
68 -- Void arguments aren't important, therefore (contrast constructSlowCall)
70 -------------------------------------------------------------------------
72 -- bring in ARG_P, ARG_N, etc.
73 #include "../includes/StgFun.h"
75 -------------------------
76 argDescrType :: ArgDescr -> Int
77 -- The "argument type" RTS field type
78 argDescrType (ArgSpec n) = n
79 argDescrType (ArgGen liveness)
80 | isBigLiveness liveness = ARG_GEN_BIG
84 mkArgDescr :: Name -> [Id] -> FCode ArgDescr
86 = case stdPattern arg_reps of
87 Just spec_id -> return (ArgSpec spec_id)
88 Nothing -> do { liveness <- mkLiveness nm size bitmap
89 ; return (ArgGen liveness) }
91 arg_reps = filter nonVoidArg (map idCgRep args)
92 -- Getting rid of voids eases matching of standard patterns
94 bitmap = mkBitmap arg_bits
95 arg_bits = argBits arg_reps
96 size = length arg_bits
98 argBits :: [CgRep] -> [Bool] -- True for non-ptr, False for ptr
100 argBits (PtrArg : args) = False : argBits args
101 argBits (arg : args) = take (cgRepSizeW arg) (repeat True) ++ argBits args
103 stdPattern :: [CgRep] -> Maybe Int
104 stdPattern [] = Just ARG_NONE -- just void args, probably
106 stdPattern [PtrArg] = Just ARG_P
107 stdPattern [FloatArg] = Just ARG_F
108 stdPattern [DoubleArg] = Just ARG_D
109 stdPattern [LongArg] = Just ARG_L
110 stdPattern [NonPtrArg] = Just ARG_N
112 stdPattern [NonPtrArg,NonPtrArg] = Just ARG_NN
113 stdPattern [NonPtrArg,PtrArg] = Just ARG_NP
114 stdPattern [PtrArg,NonPtrArg] = Just ARG_PN
115 stdPattern [PtrArg,PtrArg] = Just ARG_PP
117 stdPattern [NonPtrArg,NonPtrArg,NonPtrArg] = Just ARG_NNN
118 stdPattern [NonPtrArg,NonPtrArg,PtrArg] = Just ARG_NNP
119 stdPattern [NonPtrArg,PtrArg,NonPtrArg] = Just ARG_NPN
120 stdPattern [NonPtrArg,PtrArg,PtrArg] = Just ARG_NPP
121 stdPattern [PtrArg,NonPtrArg,NonPtrArg] = Just ARG_PNN
122 stdPattern [PtrArg,NonPtrArg,PtrArg] = Just ARG_PNP
123 stdPattern [PtrArg,PtrArg,NonPtrArg] = Just ARG_PPN
124 stdPattern [PtrArg,PtrArg,PtrArg] = Just ARG_PPP
126 stdPattern [PtrArg,PtrArg,PtrArg,PtrArg] = Just ARG_PPPP
127 stdPattern [PtrArg,PtrArg,PtrArg,PtrArg,PtrArg] = Just ARG_PPPPP
128 stdPattern [PtrArg,PtrArg,PtrArg,PtrArg,PtrArg,PtrArg] = Just ARG_PPPPPP
129 stdPattern other = Nothing
132 -------------------------------------------------------------------------
136 -------------------------------------------------------------------------
138 mkLiveness :: Name -> Int -> Bitmap -> FCode Liveness
139 mkLiveness name size bits
140 | size > mAX_SMALL_BITMAP_SIZE -- Bitmap does not fit in one word
141 = do { let lbl = mkBitmapLabel name
142 ; emitRODataLits lbl ( mkWordCLit (fromIntegral size)
143 : map mkWordCLit bits)
144 ; return (BigLiveness lbl) }
146 | otherwise -- Bitmap fits in one word
148 small_bits = case bits of
150 [b] -> fromIntegral b
151 _ -> panic "livenessToAddrMode"
153 return (smallLiveness size small_bits)
155 smallLiveness :: Int -> StgWord -> Liveness
156 smallLiveness size small_bits = SmallLiveness bits
157 where bits = fromIntegral size .|. (small_bits `shiftL` bITMAP_BITS_SHIFT)
160 isBigLiveness :: Liveness -> Bool
161 isBigLiveness (BigLiveness _) = True
162 isBigLiveness (SmallLiveness _) = False
165 mkLivenessCLit :: Liveness -> CmmLit
166 mkLivenessCLit (BigLiveness lbl) = CmmLabel lbl
167 mkLivenessCLit (SmallLiveness bits) = mkWordCLit bits
170 -------------------------------------------------------------------------
172 -- Bitmap describing register liveness
173 -- across GC when doing a "generic" heap check
174 -- (a RET_DYN stack frame).
176 -- NB. Must agree with these macros (currently in StgMacros.h):
177 -- GET_NON_PTRS(), GET_PTRS(), GET_LIVENESS().
178 -------------------------------------------------------------------------
180 mkRegLiveness :: [(Id, GlobalReg)] -> Int -> Int -> StgWord
181 mkRegLiveness regs ptrs nptrs
182 = (fromIntegral nptrs `shiftL` 16) .|.
183 (fromIntegral ptrs `shiftL` 24) .|.
184 all_non_ptrs `xor` reg_bits regs
189 reg_bits ((id, VanillaReg i) : regs) | isFollowableArg (idCgRep id)
190 = (1 `shiftL` (i - 1)) .|. reg_bits regs
194 -------------------------------------------------------------------------
196 -- Pushing the arguments for a slow call
198 -------------------------------------------------------------------------
200 -- For a slow call, we must take a bunch of arguments and intersperse
201 -- some stg_ap_<pattern>_ret_info return addresses.
204 -> (CLabel, -- RTS entry point for call
205 [(CgRep,CmmExpr)], -- args to pass to the entry point
206 [(CgRep,CmmExpr)]) -- stuff to save on the stack
208 -- don't forget the zero case
210 = (mkRtsApFastLabel SLIT("stg_ap_0"), [], [])
212 constructSlowCall amodes
213 = (stg_ap_pat, these, rest)
215 stg_ap_pat = mkRtsApFastLabel arg_pat
216 (arg_pat, these, rest) = matchSlowPattern amodes
218 enterRtsRetLabel arg_pat
219 | tablesNextToCode = mkRtsRetInfoLabel arg_pat
220 | otherwise = mkRtsRetLabel arg_pat
222 -- | 'slowArgs' takes a list of function arguments and prepares them for
223 -- pushing on the stack for "extra" arguments to a function which requires
224 -- fewer arguments than we currently have.
225 slowArgs :: [(CgRep,CmmExpr)] -> [(CgRep,CmmExpr)]
227 slowArgs amodes = (NonPtrArg, mkLblExpr stg_ap_pat) : args ++ slowArgs rest
228 where (arg_pat, args, rest) = matchSlowPattern amodes
229 stg_ap_pat = mkRtsRetInfoLabel arg_pat
231 matchSlowPattern :: [(CgRep,CmmExpr)]
232 -> (LitString, [(CgRep,CmmExpr)], [(CgRep,CmmExpr)])
233 matchSlowPattern amodes = (arg_pat, these, rest)
234 where (arg_pat, n) = slowCallPattern (map fst amodes)
235 (these, rest) = splitAt n amodes
237 -- These cases were found to cover about 99% of all slow calls:
238 slowCallPattern (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: _) = (SLIT("stg_ap_pppppp"), 6)
239 slowCallPattern (PtrArg: PtrArg: PtrArg: PtrArg: PtrArg: _) = (SLIT("stg_ap_ppppp"), 5)
240 slowCallPattern (PtrArg: PtrArg: PtrArg: PtrArg: _) = (SLIT("stg_ap_pppp"), 4)
241 slowCallPattern (PtrArg: PtrArg: PtrArg: VoidArg: _) = (SLIT("stg_ap_pppv"), 4)
242 slowCallPattern (PtrArg: PtrArg: PtrArg: _) = (SLIT("stg_ap_ppp"), 3)
243 slowCallPattern (PtrArg: PtrArg: VoidArg: _) = (SLIT("stg_ap_ppv"), 3)
244 slowCallPattern (PtrArg: PtrArg: _) = (SLIT("stg_ap_pp"), 2)
245 slowCallPattern (PtrArg: VoidArg: _) = (SLIT("stg_ap_pv"), 2)
246 slowCallPattern (PtrArg: _) = (SLIT("stg_ap_p"), 1)
247 slowCallPattern (VoidArg: _) = (SLIT("stg_ap_v"), 1)
248 slowCallPattern (NonPtrArg: _) = (SLIT("stg_ap_n"), 1)
249 slowCallPattern (FloatArg: _) = (SLIT("stg_ap_f"), 1)
250 slowCallPattern (DoubleArg: _) = (SLIT("stg_ap_d"), 1)
251 slowCallPattern (LongArg: _) = (SLIT("stg_ap_l"), 1)
252 slowCallPattern _ = panic "CgStackery.slowCallPattern"
254 -------------------------------------------------------------------------
256 -- Return conventions
258 -------------------------------------------------------------------------
260 -- A @CtrlReturnConvention@ says how {\em control} is returned.
262 data CtrlReturnConvention
263 = VectoredReturn Int -- size of the vector table (family size)
264 | UnvectoredReturn Int -- family size
266 ctrlReturnConvAlg :: TyCon -> CtrlReturnConvention
267 ctrlReturnConvAlg tycon
268 = case (tyConFamilySize tycon) of
269 size -> -- we're supposed to know...
270 if (size > (1::Int) && size <= mAX_FAMILY_SIZE_FOR_VEC_RETURNS) then
273 UnvectoredReturn size
274 -- NB: unvectored returns Include size 0 (no constructors), so that
275 -- the following perverse code compiles (it crashed GHC in 5.02)
277 -- data T2 = T2 !T1 Int
278 -- The only value of type T1 is bottom, which never returns anyway.
280 dataReturnConvPrim :: CgRep -> CmmReg
281 dataReturnConvPrim PtrArg = CmmGlobal (VanillaReg 1)
282 dataReturnConvPrim NonPtrArg = CmmGlobal (VanillaReg 1)
283 dataReturnConvPrim LongArg = CmmGlobal (LongReg 1)
284 dataReturnConvPrim FloatArg = CmmGlobal (FloatReg 1)
285 dataReturnConvPrim DoubleArg = CmmGlobal (DoubleReg 1)
286 dataReturnConvPrim VoidArg = panic "dataReturnConvPrim: void"
289 -- getSequelAmode returns an amode which refers to an info table. The info
290 -- table will always be of the RET(_VEC)?_(BIG|SMALL) kind. We're careful
291 -- not to handle real code pointers, just in case we're compiling for
292 -- an unregisterised/untailcallish architecture, where info pointers and
293 -- code pointers aren't the same.
295 -- The OnStack case of sequelToAmode delivers an Amode which is only
296 -- valid just before the final control transfer, because it assumes
297 -- that Sp is pointing to the top word of the return address. This
298 -- seems unclean but there you go.
300 getSequelAmode :: FCode CmmExpr
302 = do { EndOfBlockInfo virt_sp sequel <- getEndOfBlockInfo
304 OnStack -> do { sp_rel <- getSpRelOffset virt_sp
305 ; returnFC (CmmLoad sp_rel wordRep) }
307 UpdateCode -> returnFC (CmmLit (CmmLabel mkUpdInfoLabel))
308 CaseAlts lbl _ _ True -> returnFC (CmmLit (CmmLabel mkSeqInfoLabel))
309 CaseAlts lbl _ _ False -> returnFC (CmmLit (CmmLabel lbl))
312 -------------------------------------------------------------------------
314 -- Build a liveness mask for the current stack
316 -------------------------------------------------------------------------
318 -- There are four kinds of things on the stack:
320 -- - pointer variables (bound in the environment)
321 -- - non-pointer variables (boudn in the environment)
322 -- - free slots (recorded in the stack free list)
323 -- - non-pointer data slots (recorded in the stack free list)
325 -- We build up a bitmap of non-pointer slots by searching the environment
326 -- for all the pointer variables, and subtracting these from a bitmap
327 -- with initially all bits set (up to the size of the stack frame).
329 buildContLiveness :: Name -- Basis for label (only)
330 -> [VirtualSpOffset] -- Live stack slots
332 buildContLiveness name live_slots
333 = do { stk_usg <- getStkUsage
334 ; let StackUsage { realSp = real_sp,
335 frameSp = frame_sp } = stk_usg
337 start_sp :: VirtualSpOffset
338 start_sp = real_sp - retAddrSizeW
339 -- In a continuation, we want a liveness mask that
340 -- starts from just after the return address, which is
341 -- on the stack at real_sp.
343 frame_size :: WordOff
344 frame_size = start_sp - frame_sp
345 -- real_sp points to the frame-header for the current
346 -- stack frame, and the end of this frame is frame_sp.
347 -- The size is therefore real_sp - frame_sp - retAddrSizeW
348 -- (subtract one for the frame-header = return address).
350 rel_slots :: [WordOff]
351 rel_slots = sortLe (<=)
352 [ start_sp - ofs -- Get slots relative to top of frame
353 | ofs <- live_slots ]
355 bitmap = intsToReverseBitmap frame_size rel_slots
357 ; WARN( not (all (>=0) rel_slots),
358 ppr name $$ ppr live_slots $$ ppr frame_size $$ ppr start_sp $$ ppr rel_slots )
359 mkLiveness name frame_size bitmap }
362 -------------------------------------------------------------------------
364 -- Register assignment
366 -------------------------------------------------------------------------
368 -- How to assign registers for
370 -- 1) Calling a fast entry point.
371 -- 2) Returning an unboxed tuple.
372 -- 3) Invoking an out-of-line PrimOp.
374 -- Registers are assigned in order.
376 -- If we run out, we don't attempt to assign any further registers (even
377 -- though we might have run out of only one kind of register); we just
378 -- return immediately with the left-overs specified.
380 -- The alternative version @assignAllRegs@ uses the complete set of
381 -- registers, including those that aren't mapped to real machine
382 -- registers. This is used for calling special RTS functions and PrimOps
383 -- which expect their arguments to always be in the same registers.
385 assignCallRegs, assignPrimOpCallRegs, assignReturnRegs
386 :: [(CgRep,a)] -- Arg or result values to assign
387 -> ([(a, GlobalReg)], -- Register assignment in same order
388 -- for *initial segment of* input list
389 -- (but reversed; doesn't matter)
390 -- VoidRep args do not appear here
391 [(CgRep,a)]) -- Leftover arg or result values
394 = assign_regs args (mkRegTbl [node])
395 -- The entry convention for a function closure
396 -- never uses Node for argument passing; instead
397 -- Node points to the function closure itself
399 assignPrimOpCallRegs args
400 = assign_regs args (mkRegTbl_allRegs [])
401 -- For primops, *all* arguments must be passed in registers
403 assignReturnRegs args
404 = assign_regs args (mkRegTbl [])
405 -- For returning unboxed tuples etc,
408 assign_regs :: [(CgRep,a)] -- Arg or result values to assign
409 -> AvailRegs -- Regs still avail: Vanilla, Float, Double, Longs
410 -> ([(a, GlobalReg)], [(CgRep, a)])
411 assign_regs args supply
414 go [] acc supply = (acc, []) -- Return the results reversed (doesn't matter)
415 go ((VoidArg,_) : args) acc supply -- Skip void arguments; they aren't passed, and
416 = go args acc supply -- there's nothign to bind them to
417 go ((rep,arg) : args) acc supply
418 = case assign_reg rep supply of
419 Just (reg, supply') -> go args ((arg,reg):acc) supply'
420 Nothing -> (acc, (rep,arg):args) -- No more regs
422 assign_reg :: CgRep -> AvailRegs -> Maybe (GlobalReg, AvailRegs)
423 assign_reg FloatArg (vs, f:fs, ds, ls) = Just (FloatReg f, (vs, fs, ds, ls))
424 assign_reg DoubleArg (vs, fs, d:ds, ls) = Just (DoubleReg d, (vs, fs, ds, ls))
425 assign_reg LongArg (vs, fs, ds, l:ls) = Just (LongReg l, (vs, fs, ds, ls))
426 assign_reg PtrArg (v:vs, fs, ds, ls) = Just (VanillaReg v, (vs, fs, ds, ls))
427 assign_reg NonPtrArg (v:vs, fs, ds, ls) = Just (VanillaReg v, (vs, fs, ds, ls))
428 -- PtrArg and NonPtrArg both go in a vanilla register
429 assign_reg other not_enough_regs = Nothing
432 -------------------------------------------------------------------------
436 -------------------------------------------------------------------------
438 -- Vanilla registers can contain pointers, Ints, Chars.
439 -- Floats and doubles have separate register supplies.
441 -- We take these register supplies from the *real* registers, i.e. those
442 -- that are guaranteed to map to machine registers.
444 useVanillaRegs | opt_Unregisterised = 0
445 | otherwise = mAX_Real_Vanilla_REG
446 useFloatRegs | opt_Unregisterised = 0
447 | otherwise = mAX_Real_Float_REG
448 useDoubleRegs | opt_Unregisterised = 0
449 | otherwise = mAX_Real_Double_REG
450 useLongRegs | opt_Unregisterised = 0
451 | otherwise = mAX_Real_Long_REG
453 vanillaRegNos, floatRegNos, doubleRegNos, longRegNos :: [Int]
454 vanillaRegNos = regList useVanillaRegs
455 floatRegNos = regList useFloatRegs
456 doubleRegNos = regList useDoubleRegs
457 longRegNos = regList useLongRegs
459 allVanillaRegNos, allFloatRegNos, allDoubleRegNos, allLongRegNos :: [Int]
460 allVanillaRegNos = regList mAX_Vanilla_REG
461 allFloatRegNos = regList mAX_Float_REG
462 allDoubleRegNos = regList mAX_Double_REG
463 allLongRegNos = regList mAX_Long_REG
468 type AvailRegs = ( [Int] -- available vanilla regs.
471 , [Int] -- longs (int64 and word64)
474 mkRegTbl :: [GlobalReg] -> AvailRegs
476 = mkRegTbl' regs_in_use vanillaRegNos floatRegNos doubleRegNos longRegNos
478 mkRegTbl_allRegs :: [GlobalReg] -> AvailRegs
479 mkRegTbl_allRegs regs_in_use
480 = mkRegTbl' regs_in_use allVanillaRegNos allFloatRegNos allDoubleRegNos allLongRegNos
482 mkRegTbl' regs_in_use vanillas floats doubles longs
483 = (ok_vanilla, ok_float, ok_double, ok_long)
485 ok_vanilla = mapCatMaybes (select VanillaReg) vanillas
486 ok_float = mapCatMaybes (select FloatReg) floats
487 ok_double = mapCatMaybes (select DoubleReg) doubles
488 ok_long = mapCatMaybes (select LongReg) longs
489 -- rep isn't looked at, hence we can use any old rep.
491 select :: (Int -> GlobalReg) -> Int{-cand-} -> Maybe Int
492 -- one we've unboxed the Int, we make a GlobalReg
493 -- and see if it is already in use; if not, return its number.
495 select mk_reg_fun cand
497 reg = mk_reg_fun cand
499 if reg `not_elem` regs_in_use
503 not_elem = isn'tIn "mkRegTbl"