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