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