CmmLayoutStack: Minor simplification
[ghc.git] / compiler / cmm / CmmLayoutStack.hs
1 {-# LANGUAGE CPP, RecordWildCards, GADTs #-}
2 module CmmLayoutStack (
3 cmmLayoutStack, setInfoTableStackMap
4 ) where
5
6 import StgCmmUtils ( callerSaveVolatileRegs ) -- XXX layering violation
7 import StgCmmForeign ( saveThreadState, loadThreadState ) -- XXX layering violation
8
9 import BasicTypes
10 import Cmm
11 import CmmInfo
12 import BlockId
13 import CLabel
14 import CmmUtils
15 import MkGraph
16 import ForeignCall
17 import CmmLive
18 import CmmProcPoint
19 import SMRep
20 import Hoopl
21 import UniqSupply
22 import StgCmmUtils ( newTemp )
23 import Maybes
24 import UniqFM
25 import Util
26
27 import DynFlags
28 import FastString
29 import Outputable hiding ( isEmpty )
30 import qualified Data.Set as Set
31 import Control.Monad.Fix
32 import Data.Array as Array
33 import Data.Bits
34 import Data.List (nub)
35 import Control.Monad (liftM)
36
37 import Prelude hiding ((<*>))
38
39 #include "HsVersions.h"
40
41 {- Note [Stack Layout]
42
43 The job of this pass is to
44
45 - replace references to abstract stack Areas with fixed offsets from Sp.
46
47 - replace the CmmHighStackMark constant used in the stack check with
48 the maximum stack usage of the proc.
49
50 - save any variables that are live across a call, and reload them as
51 necessary.
52
53 Before stack allocation, local variables remain live across native
54 calls (CmmCall{ cmm_cont = Just _ }), and after stack allocation local
55 variables are clobbered by native calls.
56
57 We want to do stack allocation so that as far as possible
58 - stack use is minimized, and
59 - unnecessary stack saves and loads are avoided.
60
61 The algorithm we use is a variant of linear-scan register allocation,
62 where the stack is our register file.
63
64 - First, we do a liveness analysis, which annotates every block with
65 the variables live on entry to the block.
66
67 - We traverse blocks in reverse postorder DFS; that is, we visit at
68 least one predecessor of a block before the block itself. The
69 stack layout flowing from the predecessor of the block will
70 determine the stack layout on entry to the block.
71
72 - We maintain a data structure
73
74 Map Label StackMap
75
76 which describes the contents of the stack and the stack pointer on
77 entry to each block that is a successor of a block that we have
78 visited.
79
80 - For each block we visit:
81
82 - Look up the StackMap for this block.
83
84 - If this block is a proc point (or a call continuation, if we
85 aren't splitting proc points), emit instructions to reload all
86 the live variables from the stack, according to the StackMap.
87
88 - Walk forwards through the instructions:
89 - At an assignment x = Sp[loc]
90 - Record the fact that Sp[loc] contains x, so that we won't
91 need to save x if it ever needs to be spilled.
92 - At an assignment x = E
93 - If x was previously on the stack, it isn't any more
94 - At the last node, if it is a call or a jump to a proc point
95 - Lay out the stack frame for the call (see setupStackFrame)
96 - emit instructions to save all the live variables
97 - Remember the StackMaps for all the successors
98 - emit an instruction to adjust Sp
99 - If the last node is a branch, then the current StackMap is the
100 StackMap for the successors.
101
102 - Manifest Sp: replace references to stack areas in this block
103 with real Sp offsets. We cannot do this until we have laid out
104 the stack area for the successors above.
105
106 In this phase we also eliminate redundant stores to the stack;
107 see elimStackStores.
108
109 - There is one important gotcha: sometimes we'll encounter a control
110 transfer to a block that we've already processed (a join point),
111 and in that case we might need to rearrange the stack to match
112 what the block is expecting. (exactly the same as in linear-scan
113 register allocation, except here we have the luxury of an infinite
114 supply of temporary variables).
115
116 - Finally, we update the magic CmmHighStackMark constant with the
117 stack usage of the function, and eliminate the whole stack check
118 if there was no stack use. (in fact this is done as part of the
119 main traversal, by feeding the high-water-mark output back in as
120 an input. I hate cyclic programming, but it's just too convenient
121 sometimes.)
122
123 There are plenty of tricky details: update frames, proc points, return
124 addresses, foreign calls, and some ad-hoc optimisations that are
125 convenient to do here and effective in common cases. Comments in the
126 code below explain these.
127
128 -}
129
130
131 -- All stack locations are expressed as positive byte offsets from the
132 -- "base", which is defined to be the address above the return address
133 -- on the stack on entry to this CmmProc.
134 --
135 -- Lower addresses have higher StackLocs.
136 --
137 type StackLoc = ByteOff
138
139 {-
140 A StackMap describes the stack at any given point. At a continuation
141 it has a particular layout, like this:
142
143 | | <- base
144 |-------------|
145 | ret0 | <- base + 8
146 |-------------|
147 . upd frame . <- base + sm_ret_off
148 |-------------|
149 | |
150 . vars .
151 . (live/dead) .
152 | | <- base + sm_sp - sm_args
153 |-------------|
154 | ret1 |
155 . ret vals . <- base + sm_sp (<--- Sp points here)
156 |-------------|
157
158 Why do we include the final return address (ret0) in our stack map? I
159 have absolutely no idea, but it seems to be done that way consistently
160 in the rest of the code generator, so I played along here. --SDM
161
162 Note that we will be constructing an info table for the continuation
163 (ret1), which needs to describe the stack down to, but not including,
164 the update frame (or ret0, if there is no update frame).
165 -}
166
167 data StackMap = StackMap
168 { sm_sp :: StackLoc
169 -- ^ the offset of Sp relative to the base on entry
170 -- to this block.
171 , sm_args :: ByteOff
172 -- ^ the number of bytes of arguments in the area for this block
173 -- Defn: the offset of young(L) relative to the base is given by
174 -- (sm_sp - sm_args) of the StackMap for block L.
175 , sm_ret_off :: ByteOff
176 -- ^ Number of words of stack that we do not describe with an info
177 -- table, because it contains an update frame.
178 , sm_regs :: UniqFM (LocalReg,StackLoc)
179 -- ^ regs on the stack
180 }
181
182 instance Outputable StackMap where
183 ppr StackMap{..} =
184 text "Sp = " <> int sm_sp $$
185 text "sm_args = " <> int sm_args $$
186 text "sm_ret_off = " <> int sm_ret_off $$
187 text "sm_regs = " <> pprUFM sm_regs ppr
188
189
190 cmmLayoutStack :: DynFlags -> ProcPointSet -> ByteOff -> CmmGraph
191 -> UniqSM (CmmGraph, BlockEnv StackMap)
192 cmmLayoutStack dflags procpoints entry_args
193 graph@(CmmGraph { g_entry = entry })
194 = do
195 -- We need liveness info. Dead assignments are removed later
196 -- by the sinking pass.
197 let liveness = cmmLocalLiveness dflags graph
198 blocks = postorderDfs graph
199
200 (final_stackmaps, _final_high_sp, new_blocks) <-
201 mfix $ \ ~(rec_stackmaps, rec_high_sp, _new_blocks) ->
202 layout dflags procpoints liveness entry entry_args
203 rec_stackmaps rec_high_sp blocks
204
205 new_blocks' <- mapM (lowerSafeForeignCall dflags) new_blocks
206 return (ofBlockList entry new_blocks', final_stackmaps)
207
208
209 layout :: DynFlags
210 -> BlockSet -- proc points
211 -> BlockEnv CmmLocalLive -- liveness
212 -> BlockId -- entry
213 -> ByteOff -- stack args on entry
214
215 -> BlockEnv StackMap -- [final] stack maps
216 -> ByteOff -- [final] Sp high water mark
217
218 -> [CmmBlock] -- [in] blocks
219
220 -> UniqSM
221 ( BlockEnv StackMap -- [out] stack maps
222 , ByteOff -- [out] Sp high water mark
223 , [CmmBlock] -- [out] new blocks
224 )
225
226 layout dflags procpoints liveness entry entry_args final_stackmaps final_sp_high blocks
227 = go blocks init_stackmap entry_args []
228 where
229 (updfr, cont_info) = collectContInfo blocks
230
231 init_stackmap = mapSingleton entry StackMap{ sm_sp = entry_args
232 , sm_args = entry_args
233 , sm_ret_off = updfr
234 , sm_regs = emptyUFM
235 }
236
237 go [] acc_stackmaps acc_hwm acc_blocks
238 = return (acc_stackmaps, acc_hwm, acc_blocks)
239
240 go (b0 : bs) acc_stackmaps acc_hwm acc_blocks
241 = do
242 let (entry0@(CmmEntry entry_lbl tscope), middle0, last0) = blockSplit b0
243
244 let stack0@StackMap { sm_sp = sp0 }
245 = mapFindWithDefault
246 (pprPanic "no stack map for" (ppr entry_lbl))
247 entry_lbl acc_stackmaps
248
249 -- (a) Update the stack map to include the effects of
250 -- assignments in this block
251 let stack1 = foldBlockNodesF (procMiddle acc_stackmaps) middle0 stack0
252
253 -- (b) Insert assignments to reload all the live variables if this
254 -- block is a proc point
255 let middle1 = if entry_lbl `setMember` procpoints
256 then foldr blockCons middle0 (insertReloads stack0)
257 else middle0
258
259 -- (c) Look at the last node and if we are making a call or
260 -- jumping to a proc point, we must save the live
261 -- variables, adjust Sp, and construct the StackMaps for
262 -- each of the successor blocks. See handleLastNode for
263 -- details.
264 (middle2, sp_off, last1, fixup_blocks, out)
265 <- handleLastNode dflags procpoints liveness cont_info
266 acc_stackmaps stack1 tscope middle0 last0
267
268 -- (d) Manifest Sp: run over the nodes in the block and replace
269 -- CmmStackSlot with CmmLoad from Sp with a concrete offset.
270 --
271 -- our block:
272 -- middle1 -- the original middle nodes
273 -- middle2 -- live variable saves from handleLastNode
274 -- Sp = Sp + sp_off -- Sp adjustment goes here
275 -- last1 -- the last node
276 --
277 let middle_pre = blockToList $ foldl blockSnoc middle1 middle2
278
279 final_blocks = manifestSp dflags final_stackmaps stack0 sp0 final_sp_high entry0
280 middle_pre sp_off last1 fixup_blocks
281
282 acc_stackmaps' = mapUnion acc_stackmaps out
283
284 -- If this block jumps to the GC, then we do not take its
285 -- stack usage into account for the high-water mark.
286 -- Otherwise, if the only stack usage is in the stack-check
287 -- failure block itself, we will do a redundant stack
288 -- check. The stack has a buffer designed to accommodate
289 -- the largest amount of stack needed for calling the GC.
290 --
291 this_sp_hwm | isGcJump last0 = 0
292 | otherwise = sp0 - sp_off
293
294 hwm' = maximum (acc_hwm : this_sp_hwm : map sm_sp (mapElems out))
295
296 go bs acc_stackmaps' hwm' (final_blocks ++ acc_blocks)
297
298
299 -- -----------------------------------------------------------------------------
300
301 -- Not foolproof, but GCFun is the culprit we most want to catch
302 isGcJump :: CmmNode O C -> Bool
303 isGcJump (CmmCall { cml_target = CmmReg (CmmGlobal l) })
304 = l == GCFun || l == GCEnter1
305 isGcJump _something_else = False
306
307 -- -----------------------------------------------------------------------------
308
309 -- This doesn't seem right somehow. We need to find out whether this
310 -- proc will push some update frame material at some point, so that we
311 -- can avoid using that area of the stack for spilling. The
312 -- updfr_space field of the CmmProc *should* tell us, but it doesn't
313 -- (I think maybe it gets filled in later when we do proc-point
314 -- splitting).
315 --
316 -- So we'll just take the max of all the cml_ret_offs. This could be
317 -- unnecessarily pessimistic, but probably not in the code we
318 -- generate.
319
320 collectContInfo :: [CmmBlock] -> (ByteOff, BlockEnv ByteOff)
321 collectContInfo blocks
322 = (maximum ret_offs, mapFromList (catMaybes mb_argss))
323 where
324 (mb_argss, ret_offs) = mapAndUnzip get_cont blocks
325
326 get_cont :: Block CmmNode x C -> (Maybe (Label, ByteOff), ByteOff)
327 get_cont b =
328 case lastNode b of
329 CmmCall { cml_cont = Just l, .. }
330 -> (Just (l, cml_ret_args), cml_ret_off)
331 CmmForeignCall { .. }
332 -> (Just (succ, ret_args), ret_off)
333 _other -> (Nothing, 0)
334
335
336 -- -----------------------------------------------------------------------------
337 -- Updating the StackMap from middle nodes
338
339 -- Look for loads from stack slots, and update the StackMap. This is
340 -- purely for optimisation reasons, so that we can avoid saving a
341 -- variable back to a different stack slot if it is already on the
342 -- stack.
343 --
344 -- This happens a lot: for example when function arguments are passed
345 -- on the stack and need to be immediately saved across a call, we
346 -- want to just leave them where they are on the stack.
347 --
348 procMiddle :: BlockEnv StackMap -> CmmNode e x -> StackMap -> StackMap
349 procMiddle stackmaps node sm
350 = case node of
351 CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot area off) _)
352 -> sm { sm_regs = addToUFM (sm_regs sm) r (r,loc) }
353 where loc = getStackLoc area off stackmaps
354 CmmAssign (CmmLocal r) _other
355 -> sm { sm_regs = delFromUFM (sm_regs sm) r }
356 _other
357 -> sm
358
359 getStackLoc :: Area -> ByteOff -> BlockEnv StackMap -> StackLoc
360 getStackLoc Old n _ = n
361 getStackLoc (Young l) n stackmaps =
362 case mapLookup l stackmaps of
363 Nothing -> pprPanic "getStackLoc" (ppr l)
364 Just sm -> sm_sp sm - sm_args sm + n
365
366
367 -- -----------------------------------------------------------------------------
368 -- Handling stack allocation for a last node
369
370 -- We take a single last node and turn it into:
371 --
372 -- C1 (some statements)
373 -- Sp = Sp + N
374 -- C2 (some more statements)
375 -- call f() -- the actual last node
376 --
377 -- plus possibly some more blocks (we may have to add some fixup code
378 -- between the last node and the continuation).
379 --
380 -- C1: is the code for saving the variables across this last node onto
381 -- the stack, if the continuation is a call or jumps to a proc point.
382 --
383 -- C2: if the last node is a safe foreign call, we have to inject some
384 -- extra code that goes *after* the Sp adjustment.
385
386 handleLastNode
387 :: DynFlags -> ProcPointSet -> BlockEnv CmmLocalLive -> BlockEnv ByteOff
388 -> BlockEnv StackMap -> StackMap -> CmmTickScope
389 -> Block CmmNode O O
390 -> CmmNode O C
391 -> UniqSM
392 ( [CmmNode O O] -- nodes to go *before* the Sp adjustment
393 , ByteOff -- amount to adjust Sp
394 , CmmNode O C -- new last node
395 , [CmmBlock] -- new blocks
396 , BlockEnv StackMap -- stackmaps for the continuations
397 )
398
399 handleLastNode dflags procpoints liveness cont_info stackmaps
400 stack0@StackMap { sm_sp = sp0 } tscp middle last
401 = case last of
402 -- At each return / tail call,
403 -- adjust Sp to point to the last argument pushed, which
404 -- is cml_args, after popping any other junk from the stack.
405 CmmCall{ cml_cont = Nothing, .. } -> do
406 let sp_off = sp0 - cml_args
407 return ([], sp_off, last, [], mapEmpty)
408
409 -- At each CmmCall with a continuation:
410 CmmCall{ cml_cont = Just cont_lbl, .. } ->
411 return $ lastCall cont_lbl cml_args cml_ret_args cml_ret_off
412
413 CmmForeignCall{ succ = cont_lbl, .. } -> do
414 return $ lastCall cont_lbl (wORD_SIZE dflags) ret_args ret_off
415 -- one word of args: the return address
416
417 CmmBranch {} -> handleBranches
418 CmmCondBranch {} -> handleBranches
419 CmmSwitch {} -> handleBranches
420
421 where
422 -- Calls and ForeignCalls are handled the same way:
423 lastCall :: BlockId -> ByteOff -> ByteOff -> ByteOff
424 -> ( [CmmNode O O]
425 , ByteOff
426 , CmmNode O C
427 , [CmmBlock]
428 , BlockEnv StackMap
429 )
430 lastCall lbl cml_args cml_ret_args cml_ret_off
431 = ( assignments
432 , spOffsetForCall sp0 cont_stack cml_args
433 , last
434 , [] -- no new blocks
435 , mapSingleton lbl cont_stack )
436 where
437 (assignments, cont_stack) = prepareStack lbl cml_ret_args cml_ret_off
438
439
440 prepareStack lbl cml_ret_args cml_ret_off
441 | Just cont_stack <- mapLookup lbl stackmaps
442 -- If we have already seen this continuation before, then
443 -- we just have to make the stack look the same:
444 = (fixupStack stack0 cont_stack, cont_stack)
445 -- Otherwise, we have to allocate the stack frame
446 | otherwise
447 = (save_assignments, new_cont_stack)
448 where
449 (new_cont_stack, save_assignments)
450 = setupStackFrame dflags lbl liveness cml_ret_off cml_ret_args stack0
451
452
453 -- For other last nodes (branches), if any of the targets is a
454 -- proc point, we have to set up the stack to match what the proc
455 -- point is expecting.
456 --
457 handleBranches :: UniqSM ( [CmmNode O O]
458 , ByteOff
459 , CmmNode O C
460 , [CmmBlock]
461 , BlockEnv StackMap )
462
463 handleBranches
464 -- Note [diamond proc point]
465 | Just l <- futureContinuation middle
466 , (nub $ filter (`setMember` procpoints) $ successors last) == [l]
467 = do
468 let cont_args = mapFindWithDefault 0 l cont_info
469 (assigs, cont_stack) = prepareStack l cont_args (sm_ret_off stack0)
470 out = mapFromList [ (l', cont_stack)
471 | l' <- successors last ]
472 return ( assigs
473 , spOffsetForCall sp0 cont_stack (wORD_SIZE dflags)
474 , last
475 , []
476 , out)
477
478 | otherwise = do
479 pps <- mapM handleBranch (successors last)
480 let lbl_map :: LabelMap Label
481 lbl_map = mapFromList [ (l,tmp) | (l,tmp,_,_) <- pps ]
482 fix_lbl l = mapFindWithDefault l l lbl_map
483 return ( []
484 , 0
485 , mapSuccessors fix_lbl last
486 , concat [ blk | (_,_,_,blk) <- pps ]
487 , mapFromList [ (l, sm) | (l,_,sm,_) <- pps ] )
488
489 -- For each successor of this block
490 handleBranch :: BlockId -> UniqSM (BlockId, BlockId, StackMap, [CmmBlock])
491 handleBranch l
492 -- (a) if the successor already has a stackmap, we need to
493 -- shuffle the current stack to make it look the same.
494 -- We have to insert a new block to make this happen.
495 | Just stack2 <- mapLookup l stackmaps
496 = do
497 let assigs = fixupStack stack0 stack2
498 (tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 tscp assigs
499 return (l, tmp_lbl, stack2, block)
500
501 -- (b) if the successor is a proc point, save everything
502 -- on the stack.
503 | l `setMember` procpoints
504 = do
505 let cont_args = mapFindWithDefault 0 l cont_info
506 (stack2, assigs) =
507 setupStackFrame dflags l liveness (sm_ret_off stack0)
508 cont_args stack0
509 (tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 tscp assigs
510 return (l, tmp_lbl, stack2, block)
511
512 -- (c) otherwise, the current StackMap is the StackMap for
513 -- the continuation. But we must remember to remove any
514 -- variables from the StackMap that are *not* live at
515 -- the destination, because this StackMap might be used
516 -- by fixupStack if this is a join point.
517 | otherwise = return (l, l, stack1, [])
518 where live = mapFindWithDefault (panic "handleBranch") l liveness
519 stack1 = stack0 { sm_regs = filterUFM is_live (sm_regs stack0) }
520 is_live (r,_) = r `elemRegSet` live
521
522
523 makeFixupBlock :: DynFlags -> ByteOff -> Label -> StackMap
524 -> CmmTickScope -> [CmmNode O O]
525 -> UniqSM (Label, [CmmBlock])
526 makeFixupBlock dflags sp0 l stack tscope assigs
527 | null assigs && sp0 == sm_sp stack = return (l, [])
528 | otherwise = do
529 tmp_lbl <- liftM mkBlockId $ getUniqueM
530 let sp_off = sp0 - sm_sp stack
531 block = blockJoin (CmmEntry tmp_lbl tscope)
532 (maybeAddSpAdj dflags sp_off (blockFromList assigs))
533 (CmmBranch l)
534 return (tmp_lbl, [block])
535
536
537 -- Sp is currently pointing to current_sp,
538 -- we want it to point to
539 -- (sm_sp cont_stack - sm_args cont_stack + args)
540 -- so the difference is
541 -- sp0 - (sm_sp cont_stack - sm_args cont_stack + args)
542 spOffsetForCall :: ByteOff -> StackMap -> ByteOff -> ByteOff
543 spOffsetForCall current_sp cont_stack args
544 = current_sp - (sm_sp cont_stack - sm_args cont_stack + args)
545
546
547 -- | create a sequence of assignments to establish the new StackMap,
548 -- given the old StackMap.
549 fixupStack :: StackMap -> StackMap -> [CmmNode O O]
550 fixupStack old_stack new_stack = concatMap move new_locs
551 where
552 old_map = sm_regs old_stack
553 new_locs = stackSlotRegs new_stack
554
555 move (r,n)
556 | Just (_,m) <- lookupUFM old_map r, n == m = []
557 | otherwise = [CmmStore (CmmStackSlot Old n)
558 (CmmReg (CmmLocal r))]
559
560
561
562 setupStackFrame
563 :: DynFlags
564 -> BlockId -- label of continuation
565 -> BlockEnv CmmLocalLive -- liveness
566 -> ByteOff -- updfr
567 -> ByteOff -- bytes of return values on stack
568 -> StackMap -- current StackMap
569 -> (StackMap, [CmmNode O O])
570
571 setupStackFrame dflags lbl liveness updfr_off ret_args stack0
572 = (cont_stack, assignments)
573 where
574 -- get the set of LocalRegs live in the continuation
575 live = mapFindWithDefault Set.empty lbl liveness
576
577 -- the stack from the base to updfr_off is off-limits.
578 -- our new stack frame contains:
579 -- * saved live variables
580 -- * the return address [young(C) + 8]
581 -- * the args for the call,
582 -- which are replaced by the return values at the return
583 -- point.
584
585 -- everything up to updfr_off is off-limits
586 -- stack1 contains updfr_off, plus everything we need to save
587 (stack1, assignments) = allocate dflags updfr_off live stack0
588
589 -- And the Sp at the continuation is:
590 -- sm_sp stack1 + ret_args
591 cont_stack = stack1{ sm_sp = sm_sp stack1 + ret_args
592 , sm_args = ret_args
593 , sm_ret_off = updfr_off
594 }
595
596
597 -- -----------------------------------------------------------------------------
598 -- Note [diamond proc point]
599 --
600 -- This special case looks for the pattern we get from a typical
601 -- tagged case expression:
602 --
603 -- Sp[young(L1)] = L1
604 -- if (R1 & 7) != 0 goto L1 else goto L2
605 -- L2:
606 -- call [R1] returns to L1
607 -- L1: live: {y}
608 -- x = R1
609 --
610 -- If we let the generic case handle this, we get
611 --
612 -- Sp[-16] = L1
613 -- if (R1 & 7) != 0 goto L1a else goto L2
614 -- L2:
615 -- Sp[-8] = y
616 -- Sp = Sp - 16
617 -- call [R1] returns to L1
618 -- L1a:
619 -- Sp[-8] = y
620 -- Sp = Sp - 16
621 -- goto L1
622 -- L1:
623 -- x = R1
624 --
625 -- The code for saving the live vars is duplicated in each branch, and
626 -- furthermore there is an extra jump in the fast path (assuming L1 is
627 -- a proc point, which it probably is if there is a heap check).
628 --
629 -- So to fix this we want to set up the stack frame before the
630 -- conditional jump. How do we know when to do this, and when it is
631 -- safe? The basic idea is, when we see the assignment
632 --
633 -- Sp[young(L)] = L
634 --
635 -- we know that
636 -- * we are definitely heading for L
637 -- * there can be no more reads from another stack area, because young(L)
638 -- overlaps with it.
639 --
640 -- We don't necessarily know that everything live at L is live now
641 -- (some might be assigned between here and the jump to L). So we
642 -- simplify and only do the optimisation when we see
643 --
644 -- (1) a block containing an assignment of a return address L
645 -- (2) ending in a branch where one (and only) continuation goes to L,
646 -- and no other continuations go to proc points.
647 --
648 -- then we allocate the stack frame for L at the end of the block,
649 -- before the branch.
650 --
651 -- We could generalise (2), but that would make it a bit more
652 -- complicated to handle, and this currently catches the common case.
653
654 futureContinuation :: Block CmmNode O O -> Maybe BlockId
655 futureContinuation middle = foldBlockNodesB f middle Nothing
656 where f :: CmmNode a b -> Maybe BlockId -> Maybe BlockId
657 f (CmmStore (CmmStackSlot (Young l) _) (CmmLit (CmmBlock _))) _
658 = Just l
659 f _ r = r
660
661 -- -----------------------------------------------------------------------------
662 -- Saving live registers
663
664 -- | Given a set of live registers and a StackMap, save all the registers
665 -- on the stack and return the new StackMap and the assignments to do
666 -- the saving.
667 --
668 allocate :: DynFlags -> ByteOff -> LocalRegSet -> StackMap
669 -> (StackMap, [CmmNode O O])
670 allocate dflags ret_off live stackmap@StackMap{ sm_sp = sp0
671 , sm_regs = regs0 }
672 =
673 -- we only have to save regs that are not already in a slot
674 let to_save = filter (not . (`elemUFM` regs0)) (Set.elems live)
675 regs1 = filterUFM (\(r,_) -> elemRegSet r live) regs0
676 in
677
678 -- make a map of the stack
679 let stack = reverse $ Array.elems $
680 accumArray (\_ x -> x) Empty (1, toWords dflags (max sp0 ret_off)) $
681 ret_words ++ live_words
682 where ret_words =
683 [ (x, Occupied)
684 | x <- [ 1 .. toWords dflags ret_off] ]
685 live_words =
686 [ (toWords dflags x, Occupied)
687 | (r,off) <- nonDetEltsUFM regs1,
688 -- See Note [Unique Determinism and code generation]
689 let w = localRegBytes dflags r,
690 x <- [ off, off - wORD_SIZE dflags .. off - w + 1] ]
691 in
692
693 -- Pass over the stack: find slots to save all the new live variables,
694 -- choosing the oldest slots first (hence a foldr).
695 let
696 save slot ([], stack, n, assigs, regs) -- no more regs to save
697 = ([], slot:stack, plusW dflags n 1, assigs, regs)
698 save slot (to_save, stack, n, assigs, regs)
699 = case slot of
700 Occupied -> (to_save, Occupied:stack, plusW dflags n 1, assigs, regs)
701 Empty
702 | Just (stack', r, to_save') <-
703 select_save to_save (slot:stack)
704 -> let assig = CmmStore (CmmStackSlot Old n')
705 (CmmReg (CmmLocal r))
706 n' = plusW dflags n 1
707 in
708 (to_save', stack', n', assig : assigs, (r,(r,n')):regs)
709
710 | otherwise
711 -> (to_save, slot:stack, plusW dflags n 1, assigs, regs)
712
713 -- we should do better here: right now we'll fit the smallest first,
714 -- but it would make more sense to fit the biggest first.
715 select_save :: [LocalReg] -> [StackSlot]
716 -> Maybe ([StackSlot], LocalReg, [LocalReg])
717 select_save regs stack = go regs []
718 where go [] _no_fit = Nothing
719 go (r:rs) no_fit
720 | Just rest <- dropEmpty words stack
721 = Just (replicate words Occupied ++ rest, r, rs++no_fit)
722 | otherwise
723 = go rs (r:no_fit)
724 where words = localRegWords dflags r
725
726 -- fill in empty slots as much as possible
727 (still_to_save, save_stack, n, save_assigs, save_regs)
728 = foldr save (to_save, [], 0, [], []) stack
729
730 -- push any remaining live vars on the stack
731 (push_sp, push_assigs, push_regs)
732 = foldr push (n, [], []) still_to_save
733 where
734 push r (n, assigs, regs)
735 = (n', assig : assigs, (r,(r,n')) : regs)
736 where
737 n' = n + localRegBytes dflags r
738 assig = CmmStore (CmmStackSlot Old n')
739 (CmmReg (CmmLocal r))
740
741 trim_sp
742 | not (null push_regs) = push_sp
743 | otherwise
744 = plusW dflags n (- length (takeWhile isEmpty save_stack))
745
746 final_regs = regs1 `addListToUFM` push_regs
747 `addListToUFM` save_regs
748
749 in
750 -- XXX should be an assert
751 if ( n /= max sp0 ret_off ) then pprPanic "allocate" (ppr n <+> ppr sp0 <+> ppr ret_off) else
752
753 if (trim_sp .&. (wORD_SIZE dflags - 1)) /= 0 then pprPanic "allocate2" (ppr trim_sp <+> ppr final_regs <+> ppr push_sp) else
754
755 ( stackmap { sm_regs = final_regs , sm_sp = trim_sp }
756 , push_assigs ++ save_assigs )
757
758
759 -- -----------------------------------------------------------------------------
760 -- Manifesting Sp
761
762 -- | Manifest Sp: turn all the CmmStackSlots into CmmLoads from Sp. The
763 -- block looks like this:
764 --
765 -- middle_pre -- the middle nodes
766 -- Sp = Sp + sp_off -- Sp adjustment goes here
767 -- last -- the last node
768 --
769 -- And we have some extra blocks too (that don't contain Sp adjustments)
770 --
771 -- The adjustment for middle_pre will be different from that for
772 -- middle_post, because the Sp adjustment intervenes.
773 --
774 manifestSp
775 :: DynFlags
776 -> BlockEnv StackMap -- StackMaps for other blocks
777 -> StackMap -- StackMap for this block
778 -> ByteOff -- Sp on entry to the block
779 -> ByteOff -- SpHigh
780 -> CmmNode C O -- first node
781 -> [CmmNode O O] -- middle
782 -> ByteOff -- sp_off
783 -> CmmNode O C -- last node
784 -> [CmmBlock] -- new blocks
785 -> [CmmBlock] -- final blocks with Sp manifest
786
787 manifestSp dflags stackmaps stack0 sp0 sp_high
788 first middle_pre sp_off last fixup_blocks
789 = final_block : fixup_blocks'
790 where
791 area_off = getAreaOff stackmaps
792
793 adj_pre_sp, adj_post_sp :: CmmNode e x -> CmmNode e x
794 adj_pre_sp = mapExpDeep (areaToSp dflags sp0 sp_high area_off)
795 adj_post_sp = mapExpDeep (areaToSp dflags (sp0 - sp_off) sp_high area_off)
796
797 -- Add unwind pseudo-instructions to document Sp level for debugging
798 add_unwind_info block
799 | debugLevel dflags > 0 = CmmUnwind Sp sp_unwind : block
800 | otherwise = block
801 sp_unwind = CmmRegOff (CmmGlobal Sp) (sp0 - wORD_SIZE dflags)
802
803 final_middle = maybeAddSpAdj dflags sp_off $
804 blockFromList $
805 add_unwind_info $
806 map adj_pre_sp $
807 elimStackStores stack0 stackmaps area_off $
808 middle_pre
809
810 final_last = optStackCheck (adj_post_sp last)
811
812 final_block = blockJoin first final_middle final_last
813
814 fixup_blocks' = map (mapBlock3' (id, adj_post_sp, id)) fixup_blocks
815
816
817 getAreaOff :: BlockEnv StackMap -> (Area -> StackLoc)
818 getAreaOff _ Old = 0
819 getAreaOff stackmaps (Young l) =
820 case mapLookup l stackmaps of
821 Just sm -> sm_sp sm - sm_args sm
822 Nothing -> pprPanic "getAreaOff" (ppr l)
823
824
825 maybeAddSpAdj :: DynFlags -> ByteOff -> Block CmmNode O O -> Block CmmNode O O
826 maybeAddSpAdj _ 0 block = block
827 maybeAddSpAdj dflags sp_off block
828 = block `blockSnoc` CmmAssign spReg (cmmOffset dflags (CmmReg spReg) sp_off)
829
830
831 {-
832 Sp(L) is the Sp offset on entry to block L relative to the base of the
833 OLD area.
834
835 SpArgs(L) is the size of the young area for L, i.e. the number of
836 arguments.
837
838 - in block L, each reference to [old + N] turns into
839 [Sp + Sp(L) - N]
840
841 - in block L, each reference to [young(L') + N] turns into
842 [Sp + Sp(L) - Sp(L') + SpArgs(L') - N]
843
844 - be careful with the last node of each block: Sp has already been adjusted
845 to be Sp + Sp(L) - Sp(L')
846 -}
847
848 areaToSp :: DynFlags -> ByteOff -> ByteOff -> (Area -> StackLoc) -> CmmExpr -> CmmExpr
849
850 areaToSp dflags sp_old _sp_hwm area_off (CmmStackSlot area n)
851 = cmmOffset dflags (CmmReg spReg) (sp_old - area_off area - n)
852 -- Replace (CmmStackSlot area n) with an offset from Sp
853
854 areaToSp dflags _ sp_hwm _ (CmmLit CmmHighStackMark)
855 = mkIntExpr dflags sp_hwm
856 -- Replace CmmHighStackMark with the number of bytes of stack used,
857 -- the sp_hwm. See Note [Stack usage] in StgCmmHeap
858
859 areaToSp dflags _ _ _ (CmmMachOp (MO_U_Lt _) args)
860 | falseStackCheck args
861 = zeroExpr dflags
862 areaToSp dflags _ _ _ (CmmMachOp (MO_U_Ge _) args)
863 | falseStackCheck args
864 = mkIntExpr dflags 1
865 -- Replace a stack-overflow test that cannot fail with a no-op
866 -- See Note [Always false stack check]
867
868 areaToSp _ _ _ _ other = other
869
870 -- | Determine whether a stack check cannot fail.
871 falseStackCheck :: [CmmExpr] -> Bool
872 falseStackCheck [ CmmMachOp (MO_Sub _)
873 [ CmmRegOff (CmmGlobal Sp) x_off
874 , CmmLit (CmmInt y_lit _)]
875 , CmmReg (CmmGlobal SpLim)]
876 = fromIntegral x_off >= y_lit
877 falseStackCheck _ = False
878
879 -- Note [Always false stack check]
880 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
881 -- We can optimise stack checks of the form
882 --
883 -- if ((Sp + x) - y < SpLim) then .. else ..
884 --
885 -- where are non-negative integer byte offsets. Since we know that
886 -- SpLim <= Sp (remember the stack grows downwards), this test must
887 -- yield False if (x >= y), so we can rewrite the comparison to False.
888 -- A subsequent sinking pass will later drop the dead code.
889 -- Optimising this away depends on knowing that SpLim <= Sp, so it is
890 -- really the job of the stack layout algorithm, hence we do it now.
891 --
892 -- The control flow optimiser may negate a conditional to increase
893 -- the likelihood of a fallthrough if the branch is not taken. But
894 -- not every conditional is inverted as the control flow optimiser
895 -- places some requirements on the predecessors of both branch targets.
896 -- So we better look for the inverted comparison too.
897
898 optStackCheck :: CmmNode O C -> CmmNode O C
899 optStackCheck n = -- Note [Always false stack check]
900 case n of
901 CmmCondBranch (CmmLit (CmmInt 0 _)) _true false _ -> CmmBranch false
902 CmmCondBranch (CmmLit (CmmInt _ _)) true _false _ -> CmmBranch true
903 other -> other
904
905
906 -- -----------------------------------------------------------------------------
907
908 -- | Eliminate stores of the form
909 --
910 -- Sp[area+n] = r
911 --
912 -- when we know that r is already in the same slot as Sp[area+n]. We
913 -- could do this in a later optimisation pass, but that would involve
914 -- a separate analysis and we already have the information to hand
915 -- here. It helps clean up some extra stack stores in common cases.
916 --
917 -- Note that we may have to modify the StackMap as we walk through the
918 -- code using procMiddle, since an assignment to a variable in the
919 -- StackMap will invalidate its mapping there.
920 --
921 elimStackStores :: StackMap
922 -> BlockEnv StackMap
923 -> (Area -> ByteOff)
924 -> [CmmNode O O]
925 -> [CmmNode O O]
926 elimStackStores stackmap stackmaps area_off nodes
927 = go stackmap nodes
928 where
929 go _stackmap [] = []
930 go stackmap (n:ns)
931 = case n of
932 CmmStore (CmmStackSlot area m) (CmmReg (CmmLocal r))
933 | Just (_,off) <- lookupUFM (sm_regs stackmap) r
934 , area_off area + m == off
935 -> go stackmap ns
936 _otherwise
937 -> n : go (procMiddle stackmaps n stackmap) ns
938
939
940 -- -----------------------------------------------------------------------------
941 -- Update info tables to include stack liveness
942
943
944 setInfoTableStackMap :: DynFlags -> BlockEnv StackMap -> CmmDecl -> CmmDecl
945 setInfoTableStackMap dflags stackmaps (CmmProc top_info@TopInfo{..} l v g)
946 = CmmProc top_info{ info_tbls = mapMapWithKey fix_info info_tbls } l v g
947 where
948 fix_info lbl info_tbl@CmmInfoTable{ cit_rep = StackRep _ } =
949 info_tbl { cit_rep = StackRep (get_liveness lbl) }
950 fix_info _ other = other
951
952 get_liveness :: BlockId -> Liveness
953 get_liveness lbl
954 = case mapLookup lbl stackmaps of
955 Nothing -> pprPanic "setInfoTableStackMap" (ppr lbl <+> ppr info_tbls)
956 Just sm -> stackMapToLiveness dflags sm
957
958 setInfoTableStackMap _ _ d = d
959
960
961 stackMapToLiveness :: DynFlags -> StackMap -> Liveness
962 stackMapToLiveness dflags StackMap{..} =
963 reverse $ Array.elems $
964 accumArray (\_ x -> x) True (toWords dflags sm_ret_off + 1,
965 toWords dflags (sm_sp - sm_args)) live_words
966 where
967 live_words = [ (toWords dflags off, False)
968 | (r,off) <- nonDetEltsUFM sm_regs
969 , isGcPtrType (localRegType r) ]
970 -- See Note [Unique Determinism and code generation]
971
972
973 -- -----------------------------------------------------------------------------
974 -- Lowering safe foreign calls
975
976 {-
977 Note [Lower safe foreign calls]
978
979 We start with
980
981 Sp[young(L1)] = L1
982 ,-----------------------
983 | r1 = foo(x,y,z) returns to L1
984 '-----------------------
985 L1:
986 R1 = r1 -- copyIn, inserted by mkSafeCall
987 ...
988
989 the stack layout algorithm will arrange to save and reload everything
990 live across the call. Our job now is to expand the call so we get
991
992 Sp[young(L1)] = L1
993 ,-----------------------
994 | SAVE_THREAD_STATE()
995 | token = suspendThread(BaseReg, interruptible)
996 | r = foo(x,y,z)
997 | BaseReg = resumeThread(token)
998 | LOAD_THREAD_STATE()
999 | R1 = r -- copyOut
1000 | jump Sp[0]
1001 '-----------------------
1002 L1:
1003 r = R1 -- copyIn, inserted by mkSafeCall
1004 ...
1005
1006 Note the copyOut, which saves the results in the places that L1 is
1007 expecting them (see Note {safe foreign call convention]). Note also
1008 that safe foreign call is replace by an unsafe one in the Cmm graph.
1009 -}
1010
1011 lowerSafeForeignCall :: DynFlags -> CmmBlock -> UniqSM CmmBlock
1012 lowerSafeForeignCall dflags block
1013 | (entry@(CmmEntry _ tscp), middle, CmmForeignCall { .. }) <- blockSplit block
1014 = do
1015 -- Both 'id' and 'new_base' are KindNonPtr because they're
1016 -- RTS-only objects and are not subject to garbage collection
1017 id <- newTemp (bWord dflags)
1018 new_base <- newTemp (cmmRegType dflags (CmmGlobal BaseReg))
1019 let (caller_save, caller_load) = callerSaveVolatileRegs dflags
1020 save_state_code <- saveThreadState dflags
1021 load_state_code <- loadThreadState dflags
1022 let suspend = save_state_code <*>
1023 caller_save <*>
1024 mkMiddle (callSuspendThread dflags id intrbl)
1025 midCall = mkUnsafeCall tgt res args
1026 resume = mkMiddle (callResumeThread new_base id) <*>
1027 -- Assign the result to BaseReg: we
1028 -- might now have a different Capability!
1029 mkAssign (CmmGlobal BaseReg) (CmmReg (CmmLocal new_base)) <*>
1030 caller_load <*>
1031 load_state_code
1032
1033 (_, regs, copyout) =
1034 copyOutOflow dflags NativeReturn Jump (Young succ)
1035 (map (CmmExprArg . CmmReg . CmmLocal) res)
1036 ret_off []
1037
1038 -- NB. after resumeThread returns, the top-of-stack probably contains
1039 -- the stack frame for succ, but it might not: if the current thread
1040 -- received an exception during the call, then the stack might be
1041 -- different. Hence we continue by jumping to the top stack frame,
1042 -- not by jumping to succ.
1043 jump = CmmCall { cml_target = entryCode dflags $
1044 CmmLoad (CmmReg spReg) (bWord dflags)
1045 , cml_cont = Just succ
1046 , cml_args_regs = regs
1047 , cml_args = widthInBytes (wordWidth dflags)
1048 , cml_ret_args = ret_args
1049 , cml_ret_off = ret_off }
1050
1051 graph' <- lgraphOfAGraph ( suspend <*>
1052 midCall <*>
1053 resume <*>
1054 copyout <*>
1055 mkLast jump, tscp)
1056
1057 case toBlockList graph' of
1058 [one] -> let (_, middle', last) = blockSplit one
1059 in return (blockJoin entry (middle `blockAppend` middle') last)
1060 _ -> panic "lowerSafeForeignCall0"
1061
1062 -- Block doesn't end in a safe foreign call:
1063 | otherwise = return block
1064
1065
1066 foreignLbl :: FastString -> CmmExpr
1067 foreignLbl name = CmmLit (CmmLabel (mkForeignLabel name Nothing ForeignLabelInExternalPackage IsFunction))
1068
1069 callSuspendThread :: DynFlags -> LocalReg -> Bool -> CmmNode O O
1070 callSuspendThread dflags id intrbl =
1071 CmmUnsafeForeignCall
1072 (ForeignTarget (foreignLbl (fsLit "suspendThread"))
1073 (ForeignConvention CCallConv [AddrHint, NoHint] [AddrHint] CmmMayReturn))
1074 [id] [CmmReg (CmmGlobal BaseReg), mkIntExpr dflags (fromEnum intrbl)]
1075
1076 callResumeThread :: LocalReg -> LocalReg -> CmmNode O O
1077 callResumeThread new_base id =
1078 CmmUnsafeForeignCall
1079 (ForeignTarget (foreignLbl (fsLit "resumeThread"))
1080 (ForeignConvention CCallConv [AddrHint] [AddrHint] CmmMayReturn))
1081 [new_base] [CmmReg (CmmLocal id)]
1082
1083 -- -----------------------------------------------------------------------------
1084
1085 plusW :: DynFlags -> ByteOff -> WordOff -> ByteOff
1086 plusW dflags b w = b + w * wORD_SIZE dflags
1087
1088 data StackSlot = Occupied | Empty
1089 -- Occupied: a return address or part of an update frame
1090
1091 instance Outputable StackSlot where
1092 ppr Occupied = text "XXX"
1093 ppr Empty = text "---"
1094
1095 dropEmpty :: WordOff -> [StackSlot] -> Maybe [StackSlot]
1096 dropEmpty 0 ss = Just ss
1097 dropEmpty n (Empty : ss) = dropEmpty (n-1) ss
1098 dropEmpty _ _ = Nothing
1099
1100 isEmpty :: StackSlot -> Bool
1101 isEmpty Empty = True
1102 isEmpty _ = False
1103
1104 localRegBytes :: DynFlags -> LocalReg -> ByteOff
1105 localRegBytes dflags r
1106 = roundUpToWords dflags (widthInBytes (typeWidth (localRegType r)))
1107
1108 localRegWords :: DynFlags -> LocalReg -> WordOff
1109 localRegWords dflags = toWords dflags . localRegBytes dflags
1110
1111 toWords :: DynFlags -> ByteOff -> WordOff
1112 toWords dflags x = x `quot` wORD_SIZE dflags
1113
1114
1115 insertReloads :: StackMap -> [CmmNode O O]
1116 insertReloads stackmap =
1117 [ CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot Old sp)
1118 (localRegType r))
1119 | (r,sp) <- stackSlotRegs stackmap
1120 ]
1121
1122
1123 stackSlotRegs :: StackMap -> [(LocalReg, StackLoc)]
1124 stackSlotRegs sm = nonDetEltsUFM (sm_regs sm)
1125 -- See Note [Unique Determinism and code generation]