e74bd14d1ed657aa64a84248f15ab24d7a81baa3
[ghc-hetmet.git] / ghc / compiler / codeGen / CgUtils.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Code generator utilities; mostly monadic
4 --
5 -- (c) The University of Glasgow 2004
6 --
7 -----------------------------------------------------------------------------
8
9 module CgUtils (
10         addIdReps,
11         cgLit,
12         emitDataLits, emitRODataLits, emitIf, emitIfThenElse,
13         emitRtsCall, emitRtsCallWithVols, emitRtsCallWithResult,
14         assignTemp, newTemp,
15         emitSimultaneously,
16         emitSwitch, emitLitSwitch,
17         tagToClosure,
18
19         cmmAndWord, cmmOrWord, cmmNegate, cmmEqWord, cmmNeWord,
20         cmmOffsetExprW, cmmOffsetExprB,
21         cmmRegOffW, cmmRegOffB,
22         cmmLabelOffW, cmmLabelOffB,
23         cmmOffsetW, cmmOffsetB,
24         cmmOffsetLitW, cmmOffsetLitB,
25         cmmLoadIndexW,
26
27         addToMem, addToMemE,
28         mkWordCLit,
29         mkStringCLit,
30         packHalfWordsCLit,
31         blankWord
32   ) where
33
34 #include "HsVersions.h"
35
36 import CgMonad
37 import TyCon            ( TyCon, tyConName )
38 import Id               ( Id )
39 import Constants        ( wORD_SIZE )
40 import SMRep            ( CgRep, StgWord, hALF_WORD_SIZE_IN_BITS, ByteOff,
41                           WordOff, idCgRep )
42 import PprCmm           ( {- instances -} )
43 import Cmm
44 import CLabel
45 import CmmUtils
46 import MachOp           ( MachRep(..), wordRep, MachOp(..),  MachHint(..),
47                           mo_wordOr, mo_wordAnd, mo_wordNe, mo_wordEq,
48                           mo_wordULt, machRepByteWidth )
49 import ForeignCall      ( CCallConv(..) )
50 import Literal          ( Literal(..) )
51 import CLabel           ( CLabel, mkAsmTempLabel )
52 import Digraph          ( SCC(..), stronglyConnComp )
53 import ListSetOps       ( assocDefault )
54 import Util             ( filterOut, sortLt )
55 import Char             ( ord )
56 import FastString       ( LitString, FastString, unpackFS )
57 import Outputable
58
59 import DATA_BITS
60
61 #include "../includes/ghcconfig.h"
62         -- For WORDS_BIGENDIAN
63
64 -------------------------------------------------------------------------
65 --
66 --      Random small functions
67 --
68 -------------------------------------------------------------------------
69
70 addIdReps :: [Id] -> [(CgRep, Id)]
71 addIdReps ids = [(idCgRep id, id) | id <- ids]
72
73 -------------------------------------------------------------------------
74 --
75 --      Literals
76 --
77 -------------------------------------------------------------------------
78
79 cgLit :: Literal -> FCode CmmLit
80 cgLit (MachStr s) = mkStringCLit (unpackFS s)
81 cgLit other_lit   = return (mkSimpleLit other_lit)
82
83 mkSimpleLit :: Literal -> CmmLit
84 mkSimpleLit (MachChar   c)    = CmmInt (fromIntegral (ord c)) wordRep
85 mkSimpleLit MachNullAddr      = zeroCLit
86 mkSimpleLit (MachInt i)       = CmmInt i wordRep
87 mkSimpleLit (MachInt64 i)     = CmmInt i I64
88 mkSimpleLit (MachWord i)      = CmmInt i wordRep
89 mkSimpleLit (MachWord64 i)    = CmmInt i I64
90 mkSimpleLit (MachFloat r)     = CmmFloat r F32
91 mkSimpleLit (MachDouble r)    = CmmFloat r F64
92 mkSimpleLit (MachLabel fs ms) = CmmLabel (mkForeignLabel fs ms is_dyn)
93                               where
94                                 is_dyn = False  -- ToDo: fix me
95         
96 mkLtOp :: Literal -> MachOp
97 -- On signed literals we must do a signed comparison
98 mkLtOp (MachInt _)    = MO_S_Lt wordRep
99 mkLtOp (MachFloat _)  = MO_S_Lt F32
100 mkLtOp (MachDouble _) = MO_S_Lt F64
101 mkLtOp lit            = MO_U_Lt (cmmLitRep (mkSimpleLit lit))
102
103
104 ---------------------------------------------------
105 --
106 --      Cmm data type functions
107 --
108 ---------------------------------------------------
109
110 -----------------------
111 -- The "B" variants take byte offsets
112 cmmRegOffB :: CmmReg -> ByteOff -> CmmExpr
113 cmmRegOffB = cmmRegOff
114
115 cmmOffsetB :: CmmExpr -> ByteOff -> CmmExpr
116 cmmOffsetB = cmmOffset
117
118 cmmOffsetExprB :: CmmExpr -> CmmExpr -> CmmExpr
119 cmmOffsetExprB = cmmOffsetExpr
120
121 cmmLabelOffB :: CLabel -> ByteOff -> CmmLit
122 cmmLabelOffB = cmmLabelOff
123
124 cmmOffsetLitB :: CmmLit -> ByteOff -> CmmLit
125 cmmOffsetLitB = cmmOffsetLit
126
127 -----------------------
128 -- The "W" variants take word offsets
129 cmmOffsetExprW :: CmmExpr -> CmmExpr -> CmmExpr
130 -- The second arg is a *word* offset; need to change it to bytes
131 cmmOffsetExprW e (CmmLit (CmmInt n _)) = cmmOffsetW e (fromInteger n)
132 cmmOffsetExprW e wd_off = cmmIndexExpr wordRep e wd_off
133
134 cmmOffsetW :: CmmExpr -> WordOff -> CmmExpr
135 cmmOffsetW e n = cmmOffsetB e (wORD_SIZE * n)
136
137 cmmRegOffW :: CmmReg -> WordOff -> CmmExpr
138 cmmRegOffW reg wd_off = cmmRegOffB reg (wd_off * wORD_SIZE)
139
140 cmmOffsetLitW :: CmmLit -> WordOff -> CmmLit
141 cmmOffsetLitW lit wd_off = cmmOffsetLitB lit (wORD_SIZE * wd_off)
142
143 cmmLabelOffW :: CLabel -> WordOff -> CmmLit
144 cmmLabelOffW lbl wd_off = cmmLabelOffB lbl (wORD_SIZE * wd_off)
145
146 cmmLoadIndexW :: CmmExpr -> Int -> CmmExpr
147 cmmLoadIndexW base off
148   = CmmLoad (cmmOffsetW base off) wordRep
149
150 -----------------------
151 cmmNeWord, cmmEqWord, cmmOrWord, cmmAndWord :: CmmExpr -> CmmExpr -> CmmExpr
152 cmmOrWord  e1 e2 = CmmMachOp mo_wordOr  [e1, e2]
153 cmmAndWord e1 e2 = CmmMachOp mo_wordAnd [e1, e2]
154 cmmNeWord  e1 e2 = CmmMachOp mo_wordNe  [e1, e2]
155 cmmEqWord  e1 e2 = CmmMachOp mo_wordEq  [e1, e2]
156 cmmULtWord e1 e2 = CmmMachOp mo_wordULt  [e1, e2]
157
158 cmmNegate :: CmmExpr -> CmmExpr
159 cmmNegate (CmmLit (CmmInt n rep)) = CmmLit (CmmInt (-n) rep)
160 cmmNegate e                       = CmmMachOp (MO_S_Neg (cmmExprRep e)) [e]
161
162 blankWord :: CmmStatic
163 blankWord = CmmUninitialised wORD_SIZE
164
165 -----------------------
166 --      Making literals
167
168 mkWordCLit :: StgWord -> CmmLit
169 mkWordCLit wd = CmmInt (fromIntegral wd) wordRep
170
171 packHalfWordsCLit :: (Integral a, Integral b) => a -> b -> CmmLit
172 -- Make a single word literal in which the lower_half_word is
173 -- at the lower address, and the upper_half_word is at the 
174 -- higher address
175 -- ToDo: consider using half-word lits instead
176 --       but be careful: that's vulnerable when reversed
177 packHalfWordsCLit lower_half_word upper_half_word
178 #ifdef WORDS_BIGENDIAN
179    = mkWordCLit ((fromIntegral lower_half_word `shiftL` hALF_WORD_SIZE_IN_BITS)
180                  .|. fromIntegral upper_half_word)
181 #else 
182    = mkWordCLit ((fromIntegral lower_half_word) 
183                  .|. (fromIntegral upper_half_word `shiftL` hALF_WORD_SIZE_IN_BITS))
184 #endif
185
186 --------------------------------------------------------------------------
187 --
188 -- Incrementing a memory location
189 --
190 --------------------------------------------------------------------------
191
192 addToMem :: MachRep     -- rep of the counter
193          -> CmmExpr     -- Address
194          -> Int         -- What to add (a word)
195          -> CmmStmt
196 addToMem rep ptr n = addToMemE rep ptr (CmmLit (CmmInt (toInteger n) rep))
197
198 addToMemE :: MachRep    -- rep of the counter
199           -> CmmExpr    -- Address
200           -> CmmExpr    -- What to add (a word-typed expression)
201           -> CmmStmt
202 addToMemE rep ptr n
203   = CmmStore ptr (CmmMachOp (MO_Add rep) [CmmLoad ptr rep, n])
204
205 -------------------------------------------------------------------------
206 --
207 --      Converting a closure tag to a closure for enumeration types
208 --      (this is the implementation of tagToEnum#).
209 --
210 -------------------------------------------------------------------------
211
212 tagToClosure :: TyCon -> CmmExpr -> CmmExpr
213 tagToClosure tycon tag
214   = CmmLoad (cmmOffsetExprW closure_tbl tag) wordRep
215   where closure_tbl = CmmLit (CmmLabel (mkClosureTblLabel (tyConName tycon)))
216
217 -------------------------------------------------------------------------
218 --
219 --      Conditionals and rts calls
220 --
221 -------------------------------------------------------------------------
222
223 emitIf :: CmmExpr       -- Boolean
224        -> Code          -- Then part
225        -> Code          
226 -- Emit (if e then x)
227 -- ToDo: reverse the condition to avoid the extra branch instruction if possible
228 -- (some conditionals aren't reversible. eg. floating point comparisons cannot
229 -- be inverted because there exist some values for which both comparisons
230 -- return False, such as NaN.)
231 emitIf cond then_part
232   = do { then_id <- newLabelC
233        ; join_id <- newLabelC
234        ; stmtC (CmmCondBranch cond then_id)
235        ; stmtC (CmmBranch join_id)
236        ; labelC then_id
237        ; then_part
238        ; labelC join_id
239        }
240
241 emitIfThenElse :: CmmExpr       -- Boolean
242                 -> Code         -- Then part
243                 -> Code         -- Else part
244                 -> Code         
245 -- Emit (if e then x else y)
246 emitIfThenElse cond then_part else_part
247   = do { then_id <- newLabelC
248        ; else_id <- newLabelC
249        ; join_id <- newLabelC
250        ; stmtC (CmmCondBranch cond then_id)
251        ; else_part
252        ; stmtC (CmmBranch join_id)
253        ; labelC then_id
254        ; then_part
255        ; labelC join_id
256        }
257
258 emitRtsCall :: LitString -> [(CmmExpr,MachHint)] -> Code
259 emitRtsCall fun args = emitRtsCall' [] fun args Nothing
260    -- The 'Nothing' says "save all global registers"
261
262 emitRtsCallWithVols :: LitString -> [(CmmExpr,MachHint)] -> [GlobalReg] -> Code
263 emitRtsCallWithVols fun args vols
264    = emitRtsCall' [] fun args (Just vols)
265
266 emitRtsCallWithResult :: CmmReg -> MachHint -> LitString
267         -> [(CmmExpr,MachHint)] -> Code
268 emitRtsCallWithResult res hint fun args
269    = emitRtsCall' [(res,hint)] fun args Nothing
270
271 -- Make a call to an RTS C procedure
272 emitRtsCall'
273    :: [(CmmReg,MachHint)]
274    -> LitString
275    -> [(CmmExpr,MachHint)]
276    -> Maybe [GlobalReg]
277    -> Code
278 emitRtsCall' res fun args vols = stmtC (CmmCall target res args vols)
279   where
280     target   = CmmForeignCall fun_expr CCallConv
281     fun_expr = mkLblExpr (mkRtsCodeLabel fun)
282
283
284 -------------------------------------------------------------------------
285 --
286 --      Strings gnerate a top-level data block
287 --
288 -------------------------------------------------------------------------
289
290 emitDataLits :: CLabel -> [CmmLit] -> Code
291 -- Emit a data-segment data block
292 emitDataLits lbl lits
293   = emitData Data (CmmDataLabel lbl : map CmmStaticLit lits)
294
295 emitRODataLits :: CLabel -> [CmmLit] -> Code
296 -- Emit a read-only data block
297 emitRODataLits lbl lits
298   = emitData ReadOnlyData (CmmDataLabel lbl : map CmmStaticLit lits)
299
300 mkStringCLit :: String -> FCode CmmLit
301 -- Make a global definition for the string,
302 -- and return its label
303 mkStringCLit str 
304   = do  { uniq <- newUnique
305         ; let lbl = mkAsmTempLabel uniq
306         ; emitData ReadOnlyData [CmmDataLabel lbl, CmmString str]
307         ; return (CmmLabel lbl) }
308
309 -------------------------------------------------------------------------
310 --
311 --      Assigning expressions to temporaries
312 --
313 -------------------------------------------------------------------------
314
315 assignTemp :: CmmExpr -> FCode CmmExpr
316 -- For a non-trivial expression, e, create a local
317 -- variable and assign the expression to it
318 assignTemp e 
319   | isTrivialCmmExpr e = return e
320   | otherwise          = do { reg <- newTemp (cmmExprRep e)
321                             ; stmtC (CmmAssign reg e)
322                             ; return (CmmReg reg) }
323
324
325 newTemp :: MachRep -> FCode CmmReg
326 newTemp rep = do { uniq <- newUnique; return (CmmLocal (LocalReg uniq rep)) }
327
328
329 -------------------------------------------------------------------------
330 --
331 --      Building case analysis
332 --
333 -------------------------------------------------------------------------
334
335 emitSwitch
336         :: CmmExpr                -- Tag to switch on
337         -> [(ConTagZ, CgStmts)]   -- Tagged branches
338         -> Maybe CgStmts          -- Default branch (if any)
339         -> ConTagZ -> ConTagZ     -- Min and Max possible values; behaviour
340                                   --    outside this range is undefined
341         -> Code
342
343 -- ONLY A DEFAULT BRANCH: no case analysis to do
344 emitSwitch tag_expr [] (Just stmts) _ _
345   = emitCgStmts stmts
346
347 -- Right, off we go
348 emitSwitch tag_expr branches mb_deflt lo_tag hi_tag
349   =     -- Just sort the branches before calling mk_sritch
350     do  { mb_deflt_id <-
351                 case mb_deflt of
352                   Nothing    -> return Nothing
353                   Just stmts -> do id <- forkCgStmts stmts; return (Just id)
354
355         ; stmts <- mk_switch tag_expr (sortLt lt branches) 
356                         mb_deflt_id lo_tag hi_tag
357         ; emitCgStmts stmts
358         }
359   where
360     (t1,_) `lt` (t2,_) = t1 < t2
361
362
363 mk_switch :: CmmExpr -> [(ConTagZ, CgStmts)]
364           -> Maybe BlockId -> ConTagZ -> ConTagZ
365           -> FCode CgStmts
366
367 -- SINGLETON TAG RANGE: no case analysis to do
368 mk_switch tag_expr [(tag,stmts)] _ lo_tag hi_tag
369   | lo_tag == hi_tag
370   = ASSERT( tag == lo_tag )
371     return stmts
372
373 -- SINGLETON BRANCH, NO DEFUALT: no case analysis to do
374 mk_switch tag_expr [(tag,stmts)] Nothing lo_tag hi_tag
375   = return stmts
376         -- The simplifier might have eliminated a case
377         --       so we may have e.g. case xs of 
378         --                               [] -> e
379         -- In that situation we can be sure the (:) case 
380         -- can't happen, so no need to test
381
382 -- SINGLETON BRANCH: one equality check to do
383 mk_switch tag_expr [(tag,stmts)] (Just deflt) lo_tag hi_tag
384   = return (CmmCondBranch cond deflt `consCgStmt` stmts)
385   where
386     cond  =  cmmNeWord tag_expr (CmmLit (mkIntCLit tag))
387         -- We have lo_tag < hi_tag, but there's only one branch, 
388         -- so there must be a default
389
390 -- ToDo: we might want to check for the two branch case, where one of
391 -- the branches is the tag 0, because comparing '== 0' is likely to be
392 -- more efficient than other kinds of comparison.
393
394 -- DENSE TAG RANGE: use a switch statment
395 mk_switch tag_expr branches mb_deflt lo_tag hi_tag
396   | use_switch  -- Use a switch
397   = do  { deflt_id <- get_deflt_id mb_deflt
398         ; branch_ids <- mapM forkCgStmts (map snd branches)
399         ; let 
400                 tagged_blk_ids = zip (map fst branches) branch_ids
401
402                 find_branch :: BlockId -> ConTagZ -> BlockId
403                 find_branch deflt_id i = assocDefault deflt_id tagged_blk_ids i
404
405                 arms = [ Just (find_branch deflt_id (i+lo_tag))
406                        | i <- [0..n_tags-1]]
407
408                 switch_stmt = CmmSwitch (cmmOffset tag_expr (- lo_tag)) arms
409
410         ; return (oneCgStmt switch_stmt)
411         }
412
413   | otherwise   -- Use an if-tree
414   = do  { (assign_tag, tag_expr') <- assignTemp' tag_expr
415                 -- To avoid duplication
416         ; lo_stmts <- mk_switch tag_expr' lo_branches mb_deflt lo_tag (mid_tag-1)
417         ; hi_stmts <- mk_switch tag_expr' hi_branches mb_deflt mid_tag hi_tag
418         ; lo_id <- forkCgStmts lo_stmts
419         ; let cond = cmmULtWord tag_expr' (CmmLit (mkIntCLit mid_tag))
420               branch_stmt = CmmCondBranch cond lo_id
421         ; return (assign_tag `consCgStmt` (branch_stmt `consCgStmt` hi_stmts)) 
422         }
423   where
424     use_switch   = ASSERT( n_branches > 1 && n_tags > 1 ) 
425                    n_tags > 2 && (small || dense)
426                  -- a 2-branch switch always turns into an if.
427     small        = n_tags <= 4
428     dense        = n_branches > (n_tags `div` 2)
429     exhaustive   = n_tags == n_branches
430     n_tags       = hi_tag - lo_tag + 1
431     n_branches   = length branches
432     
433         -- INVARIANT: Provided hi_tag > lo_tag (which is true)
434         --      lo_tag <= mid_tag < hi_tag
435         --      lo_branches have tags <  mid_tag
436         --      hi_branches have tags >= mid_tag
437
438     (mid_tag,_) = branches !! (n_branches `div` 2)
439         -- 2 branches => n_branches `div` 2 = 1
440         --            => branches !! 1 give the *second* tag
441         -- There are always at least 2 branches here
442
443     (lo_branches, hi_branches) = span is_lo branches
444     is_lo (t,_) = t < mid_tag
445
446         -- Add a default block if the case is not exhaustive
447     get_deflt_id  (Just deflt_id) = return deflt_id
448     get_deflt_id  Nothing
449         | exhaustive 
450         = return (pprPanic "mk_deflt_blks" (ppr tag_expr))
451         | otherwise
452         = do { stmts <- getCgStmts (stmtC jump_to_impossible)
453              ; id <- forkCgStmts stmts
454              ; return id }
455
456     jump_to_impossible 
457       = CmmJump (mkLblExpr mkErrorStdEntryLabel) []
458
459
460 assignTemp' e
461   | isTrivialCmmExpr e = return (CmmNop, e)
462   | otherwise          = do { reg <- newTemp (cmmExprRep e)
463                             ; return (CmmAssign reg e, CmmReg reg) }
464
465
466 emitLitSwitch :: CmmExpr                        -- Tag to switch on
467               -> [(Literal, CgStmts)]           -- Tagged branches
468               -> CgStmts                        -- Default branch (always)
469               -> Code                           -- Emit the code
470 -- Used for general literals, whose size might not be a word, 
471 -- where there is always a default case, and where we don't know
472 -- the range of values for certain.  For simplicity we always generate a tree.
473 emitLitSwitch scrut [] deflt 
474   = emitCgStmts deflt
475 emitLitSwitch scrut branches deflt_blk
476   = do  { scrut' <- assignTemp scrut
477         ; deflt_blk_id <- forkCgStmts deflt_blk
478         ; blk <- mk_lit_switch scrut' deflt_blk_id (sortLt lt branches)
479         ; emitCgStmts blk }
480   where
481     lt (t1,_) (t2,_) = t1 < t2
482
483 mk_lit_switch :: CmmExpr -> BlockId 
484               -> [(Literal,CgStmts)]
485               -> FCode CgStmts
486 mk_lit_switch scrut deflt_blk_id [(lit,blk)] 
487   = return (consCgStmt if_stmt blk)
488   where
489     cmm_lit = mkSimpleLit lit
490     rep     = cmmLitRep cmm_lit
491     cond    = CmmMachOp (MO_Ne rep) [scrut, CmmLit cmm_lit]
492     if_stmt = CmmCondBranch cond deflt_blk_id
493
494 mk_lit_switch scrut deflt_blk_id branches
495   = do  { hi_blk <- mk_lit_switch scrut deflt_blk_id hi_branches
496         ; lo_blk <- mk_lit_switch scrut deflt_blk_id lo_branches
497         ; lo_blk_id <- forkCgStmts lo_blk
498         ; let if_stmt = CmmCondBranch cond lo_blk_id
499         ; return (if_stmt `consCgStmt` hi_blk) }
500   where
501     n_branches = length branches
502     (mid_lit,_) = branches !! (n_branches `div` 2)
503         -- See notes above re mid_tag
504
505     (lo_branches, hi_branches) = span is_lo branches
506     is_lo (t,_) = t < mid_lit
507
508     cond    = CmmMachOp (mkLtOp mid_lit) 
509                         [scrut, CmmLit (mkSimpleLit mid_lit)]
510
511 -------------------------------------------------------------------------
512 --
513 --      Simultaneous assignment
514 --
515 -------------------------------------------------------------------------
516
517
518 emitSimultaneously :: CmmStmts -> Code
519 -- Emit code to perform the assignments in the
520 -- input simultaneously, using temporary variables when necessary.
521 --
522 -- The Stmts must be:
523 --      CmmNop, CmmComment, CmmAssign, CmmStore
524 -- and nothing else
525
526
527 -- We use the strongly-connected component algorithm, in which
528 --      * the vertices are the statements
529 --      * an edge goes from s1 to s2 iff
530 --              s1 assigns to something s2 uses
531 --        that is, if s1 should *follow* s2 in the final order
532
533 type CVertex = (Int, CmmStmt)   -- Give each vertex a unique number,
534                                 -- for fast comparison
535
536 emitSimultaneously stmts
537   = codeOnly $
538     case filterOut isNopStmt (stmtList stmts) of 
539         -- Remove no-ops
540       []        -> nopC
541       [stmt]    -> stmtC stmt   -- It's often just one stmt
542       stmt_list -> doSimultaneously1 (zip [(1::Int)..] stmt_list)
543
544 doSimultaneously1 :: [CVertex] -> Code
545 doSimultaneously1 vertices
546   = let
547         edges = [ (vertex, key1, edges_from stmt1)
548                 | vertex@(key1, stmt1) <- vertices
549                 ]
550         edges_from stmt1 = [ key2 | (key2, stmt2) <- vertices, 
551                                     stmt1 `mustFollow` stmt2
552                            ]
553         components = stronglyConnComp edges
554
555         -- do_components deal with one strongly-connected component
556         -- Not cyclic, or singleton?  Just do it
557         do_component (AcyclicSCC (n,stmt))  = stmtC stmt
558         do_component (CyclicSCC [(n,stmt)]) = stmtC stmt
559
560                 -- Cyclic?  Then go via temporaries.  Pick one to
561                 -- break the loop and try again with the rest.
562         do_component (CyclicSCC ((n,first_stmt) : rest))
563           = do  { from_temp <- go_via_temp first_stmt
564                 ; doSimultaneously1 rest
565                 ; stmtC from_temp }
566
567         go_via_temp (CmmAssign dest src)
568           = do  { tmp <- newTemp (cmmRegRep dest)
569                 ; stmtC (CmmAssign tmp src)
570                 ; return (CmmAssign dest (CmmReg tmp)) }
571         go_via_temp (CmmStore dest src)
572           = do  { tmp <- newTemp (cmmExprRep src)
573                 ; stmtC (CmmAssign tmp src)
574                 ; return (CmmStore dest (CmmReg tmp)) }
575     in
576     mapCs do_component components
577
578 mustFollow :: CmmStmt -> CmmStmt -> Bool
579 CmmAssign reg _  `mustFollow` stmt = anySrc (reg `regUsedIn`) stmt
580 CmmStore loc e   `mustFollow` stmt = anySrc (locUsedIn loc (cmmExprRep e)) stmt
581 CmmNop           `mustFollow` stmt = False
582 CmmComment _     `mustFollow` stmt = False
583
584
585 anySrc :: (CmmExpr -> Bool) -> CmmStmt -> Bool
586 -- True if the fn is true of any input of the stmt
587 anySrc p (CmmAssign _ e)    = p e
588 anySrc p (CmmStore e1 e2)   = p e1 || p e2      -- Might be used in either side
589 anySrc p (CmmComment _)     = False
590 anySrc p CmmNop             = False
591 anySrc p other              = True              -- Conservative
592
593 regUsedIn :: CmmReg -> CmmExpr -> Bool
594 reg `regUsedIn` CmmLit _         = False
595 reg `regUsedIn` CmmLoad e  _     = reg `regUsedIn` e
596 reg `regUsedIn` CmmReg reg'      = reg == reg'
597 reg `regUsedIn` CmmRegOff reg' _ = reg == reg'
598 reg `regUsedIn` CmmMachOp _ es   = any (reg `regUsedIn`) es
599
600 locUsedIn :: CmmExpr -> MachRep -> CmmExpr -> Bool
601 -- (locUsedIn a r e) checks whether writing to r[a] could affect the value of
602 -- 'e'.  Returns True if it's not sure.
603 locUsedIn loc rep (CmmLit _)         = False
604 locUsedIn loc rep (CmmLoad e ld_rep) = possiblySameLoc loc rep e ld_rep
605 locUsedIn loc rep (CmmReg reg')      = False
606 locUsedIn loc rep (CmmRegOff reg' _) = False
607 locUsedIn loc rep (CmmMachOp _ es)   = any (locUsedIn loc rep) es
608
609 possiblySameLoc :: CmmExpr -> MachRep -> CmmExpr -> MachRep -> Bool
610 -- Assumes that distinct registers (eg Hp, Sp) do not 
611 -- point to the same location, nor any offset thereof.
612 possiblySameLoc (CmmReg r1)       rep1 (CmmReg r2)      rep2  = r1==r2
613 possiblySameLoc (CmmReg r1)       rep1 (CmmRegOff r2 0) rep2  = r1==r2
614 possiblySameLoc (CmmRegOff r1 0)  rep1 (CmmReg r2)      rep2  = r1==r2
615 possiblySameLoc (CmmRegOff r1 start1) rep1 (CmmRegOff r2 start2) rep2 
616   = r1==r2 && end1 > start2 && end2 > start1
617   where
618     end1 = start1 + machRepByteWidth rep1
619     end2 = start2 + machRepByteWidth rep2
620
621 possiblySameLoc l1 rep1 (CmmLit _) rep2 = False
622 possiblySameLoc l1 rep1 l2         rep2 = True  -- Conservative