[project @ 2005-04-08 09:54:54 by simonmar]
[ghc-hetmet.git] / ghc / compiler / nativeGen / MachCodeGen.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Generating machine code (instruction selection)
4 --
5 -- (c) The University of Glasgow 1996-2004
6 --
7 -----------------------------------------------------------------------------
8
9 -- This is a big module, but, if you pay attention to
10 -- (a) the sectioning, (b) the type signatures, and
11 -- (c) the #if blah_TARGET_ARCH} things, the
12 -- structure should not be too overwhelming.
13
14 module MachCodeGen ( cmmTopCodeGen, InstrBlock ) where
15
16 #include "HsVersions.h"
17 #include "nativeGen/NCG.h"
18 #include "MachDeps.h"
19
20 -- NCG stuff:
21 import MachInstrs
22 import MachRegs
23 import NCGMonad
24 import PositionIndependentCode ( cmmMakeDynamicReference, initializePicBase )
25
26 -- Our intermediate code:
27 import PprCmm           ( pprExpr )
28 import Cmm
29 import MachOp
30 import CLabel
31
32 -- The rest:
33 import StaticFlags      ( opt_PIC )
34 import ForeignCall      ( CCallConv(..) )
35 import OrdList
36 import Pretty
37 import Outputable
38 import qualified Outputable
39 import FastString
40 import FastTypes        ( isFastTrue )
41 import Constants        ( wORD_SIZE )
42
43 #ifdef DEBUG
44 import Outputable       ( assertPanic )
45 import TRACE            ( trace )
46 #endif
47
48 import Control.Monad    ( mapAndUnzipM )
49 import Maybe            ( fromJust )
50 import DATA_BITS
51 import DATA_WORD
52
53 -- -----------------------------------------------------------------------------
54 -- Top-level of the instruction selector
55
56 -- | 'InstrBlock's are the insn sequences generated by the insn selectors.
57 -- They are really trees of insns to facilitate fast appending, where a
58 -- left-to-right traversal (pre-order?) yields the insns in the correct
59 -- order.
60
61 type InstrBlock = OrdList Instr
62
63 cmmTopCodeGen :: CmmTop -> NatM [NatCmmTop]
64 cmmTopCodeGen (CmmProc info lab params blocks) = do
65   (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
66   picBaseMb <- getPicBaseMaybeNat
67   let proc = CmmProc info lab params (concat nat_blocks)
68       tops = proc : concat statics
69   case picBaseMb of
70       Just picBase -> initializePicBase picBase tops
71       Nothing -> return tops
72   
73 cmmTopCodeGen (CmmData sec dat) = do
74   return [CmmData sec dat]  -- no translation, we just use CmmStatic
75
76 basicBlockCodeGen :: CmmBasicBlock -> NatM ([NatBasicBlock],[NatCmmTop])
77 basicBlockCodeGen (BasicBlock id stmts) = do
78   instrs <- stmtsToInstrs stmts
79   -- code generation may introduce new basic block boundaries, which
80   -- are indicated by the NEWBLOCK instruction.  We must split up the
81   -- instruction stream into basic blocks again.  Also, we extract
82   -- LDATAs here too.
83   let
84         (top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
85         
86         mkBlocks (NEWBLOCK id) (instrs,blocks,statics) 
87           = ([], BasicBlock id instrs : blocks, statics)
88         mkBlocks (LDATA sec dat) (instrs,blocks,statics) 
89           = (instrs, blocks, CmmData sec dat:statics)
90         mkBlocks instr (instrs,blocks,statics)
91           = (instr:instrs, blocks, statics)
92   -- in
93   return (BasicBlock id top : other_blocks, statics)
94
95 stmtsToInstrs :: [CmmStmt] -> NatM InstrBlock
96 stmtsToInstrs stmts
97    = do instrss <- mapM stmtToInstrs stmts
98         return (concatOL instrss)
99
100 stmtToInstrs :: CmmStmt -> NatM InstrBlock
101 stmtToInstrs stmt = case stmt of
102     CmmNop         -> return nilOL
103     CmmComment s   -> return (unitOL (COMMENT s))
104
105     CmmAssign reg src
106       | isFloatingRep kind -> assignReg_FltCode kind reg src
107 #if WORD_SIZE_IN_BITS==32
108       | kind == I64        -> assignReg_I64Code      reg src
109 #endif
110       | otherwise          -> assignReg_IntCode kind reg src
111         where kind = cmmRegRep reg
112
113     CmmStore addr src
114       | isFloatingRep kind -> assignMem_FltCode kind addr src
115 #if WORD_SIZE_IN_BITS==32
116       | kind == I64      -> assignMem_I64Code      addr src
117 #endif
118       | otherwise        -> assignMem_IntCode kind addr src
119         where kind = cmmExprRep src
120
121     CmmCall target result_regs args vols
122        -> genCCall target result_regs args vols
123
124     CmmBranch id          -> genBranch id
125     CmmCondBranch arg id  -> genCondJump id arg
126     CmmSwitch arg ids     -> genSwitch arg ids
127     CmmJump arg params    -> genJump arg
128
129 -- -----------------------------------------------------------------------------
130 -- General things for putting together code sequences
131
132 -- Expand CmmRegOff.  ToDo: should we do it this way around, or convert
133 -- CmmExprs into CmmRegOff?
134 mangleIndexTree :: CmmExpr -> CmmExpr
135 mangleIndexTree (CmmRegOff reg off)
136   = CmmMachOp (MO_Add rep) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) rep)]
137   where rep = cmmRegRep reg
138
139 -- -----------------------------------------------------------------------------
140 --  Code gen for 64-bit arithmetic on 32-bit platforms
141
142 {-
143 Simple support for generating 64-bit code (ie, 64 bit values and 64
144 bit assignments) on 32-bit platforms.  Unlike the main code generator
145 we merely shoot for generating working code as simply as possible, and
146 pay little attention to code quality.  Specifically, there is no
147 attempt to deal cleverly with the fixed-vs-floating register
148 distinction; all values are generated into (pairs of) floating
149 registers, even if this would mean some redundant reg-reg moves as a
150 result.  Only one of the VRegUniques is returned, since it will be
151 of the VRegUniqueLo form, and the upper-half VReg can be determined
152 by applying getHiVRegFromLo to it.
153 -}
154
155 data ChildCode64        -- a.k.a "Register64"
156    = ChildCode64 
157         InstrBlock      -- code
158         Reg             -- the lower 32-bit temporary which contains the
159                         -- result; use getHiVRegFromLo to find the other
160                         -- VRegUnique.  Rules of this simplified insn
161                         -- selection game are therefore that the returned
162                         -- Reg may be modified
163
164 #if WORD_SIZE_IN_BITS==32
165 assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
166 assignReg_I64Code :: CmmReg  -> CmmExpr -> NatM InstrBlock
167 #endif
168
169 #ifndef x86_64_TARGET_ARCH
170 iselExpr64        :: CmmExpr -> NatM ChildCode64
171 #endif
172
173 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
174
175 #if i386_TARGET_ARCH
176
177 assignMem_I64Code addrTree valueTree = do
178   Amode addr addr_code <- getAmode addrTree
179   ChildCode64 vcode rlo <- iselExpr64 valueTree
180   let 
181         rhi = getHiVRegFromLo rlo
182
183         -- Little-endian store
184         mov_lo = MOV I32 (OpReg rlo) (OpAddr addr)
185         mov_hi = MOV I32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
186   -- in
187   return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
188
189
190 assignReg_I64Code (CmmLocal (LocalReg u_dst pk)) valueTree = do
191    ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
192    let 
193          r_dst_lo = mkVReg u_dst I32
194          r_dst_hi = getHiVRegFromLo r_dst_lo
195          r_src_hi = getHiVRegFromLo r_src_lo
196          mov_lo = MOV I32 (OpReg r_src_lo) (OpReg r_dst_lo)
197          mov_hi = MOV I32 (OpReg r_src_hi) (OpReg r_dst_hi)
198    -- in
199    return (
200         vcode `snocOL` mov_lo `snocOL` mov_hi
201      )
202
203 assignReg_I64Code lvalue valueTree
204    = panic "assignReg_I64Code(i386): invalid lvalue"
205
206 ------------
207
208 iselExpr64 (CmmLit (CmmInt i _)) = do
209   (rlo,rhi) <- getNewRegPairNat I32
210   let
211         r = fromIntegral (fromIntegral i :: Word32)
212         q = fromIntegral ((fromIntegral i `shiftR` 32) :: Word32)
213         code = toOL [
214                 MOV I32 (OpImm (ImmInteger r)) (OpReg rlo),
215                 MOV I32 (OpImm (ImmInteger q)) (OpReg rhi)
216                 ]
217   -- in
218   return (ChildCode64 code rlo)
219
220 iselExpr64 (CmmLoad addrTree I64) = do
221    Amode addr addr_code <- getAmode addrTree
222    (rlo,rhi) <- getNewRegPairNat I32
223    let 
224         mov_lo = MOV I32 (OpAddr addr) (OpReg rlo)
225         mov_hi = MOV I32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
226    -- in
227    return (
228             ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) 
229                         rlo
230      )
231
232 iselExpr64 (CmmReg (CmmLocal (LocalReg vu I64)))
233    = return (ChildCode64 nilOL (mkVReg vu I32))
234          
235 -- we handle addition, but rather badly
236 iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
237    ChildCode64 code1 r1lo <- iselExpr64 e1
238    (rlo,rhi) <- getNewRegPairNat I32
239    let
240         r = fromIntegral (fromIntegral i :: Word32)
241         q = fromIntegral ((fromIntegral i `shiftR` 32) :: Word32)
242         r1hi = getHiVRegFromLo r1lo
243         code =  code1 `appOL`
244                 toOL [ MOV I32 (OpReg r1lo) (OpReg rlo),
245                        ADD I32 (OpImm (ImmInteger r)) (OpReg rlo),
246                        MOV I32 (OpReg r1hi) (OpReg rhi),
247                        ADC I32 (OpImm (ImmInteger q)) (OpReg rhi) ]
248    -- in
249    return (ChildCode64 code rlo)
250
251 iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
252    ChildCode64 code1 r1lo <- iselExpr64 e1
253    ChildCode64 code2 r2lo <- iselExpr64 e2
254    (rlo,rhi) <- getNewRegPairNat I32
255    let
256         r1hi = getHiVRegFromLo r1lo
257         r2hi = getHiVRegFromLo r2lo
258         code =  code1 `appOL`
259                 code2 `appOL`
260                 toOL [ MOV I32 (OpReg r1lo) (OpReg rlo),
261                        ADD I32 (OpReg r2lo) (OpReg rlo),
262                        MOV I32 (OpReg r1hi) (OpReg rhi),
263                        ADC I32 (OpReg r2hi) (OpReg rhi) ]
264    -- in
265    return (ChildCode64 code rlo)
266
267 iselExpr64 expr
268    = pprPanic "iselExpr64(i386)" (ppr expr)
269
270 #endif /* i386_TARGET_ARCH */
271
272 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
273
274 #if sparc_TARGET_ARCH
275
276 assignMem_I64Code addrTree valueTree
277    = iselExpr64 valueTree               `thenNat` \ (ChildCode64 vcode vrlo) ->
278      getRegister addrTree               `thenNat` \ register_addr ->
279      getNewRegNat IntRep                `thenNat` \ t_addr ->
280      let rlo = VirtualRegI vrlo
281          rhi = getHiVRegFromLo rlo
282          code_addr = registerCode register_addr t_addr
283          reg_addr  = registerName register_addr t_addr
284          -- Big-endian store
285          mov_hi = ST W rhi (AddrRegImm reg_addr (ImmInt 0))
286          mov_lo = ST W rlo (AddrRegImm reg_addr (ImmInt 4))
287      in
288          return (vcode `appOL` code_addr `snocOL` mov_hi `snocOL` mov_lo)
289
290
291 assignReg_I64Code (StixTemp (StixVReg u_dst pk)) valueTree
292    = iselExpr64 valueTree               `thenNat` \ (ChildCode64 vcode vr_src_lo) ->
293      let 
294          r_dst_lo = mkVReg u_dst IntRep
295          r_src_lo = VirtualRegI vr_src_lo
296          r_dst_hi = getHiVRegFromLo r_dst_lo
297          r_src_hi = getHiVRegFromLo r_src_lo
298          mov_lo = mkMOV r_src_lo r_dst_lo
299          mov_hi = mkMOV r_src_hi r_dst_hi
300          mkMOV sreg dreg = OR False g0 (RIReg sreg) dreg
301      in
302          return (
303             vcode `snocOL` mov_hi `snocOL` mov_lo
304          )
305 assignReg_I64Code lvalue valueTree
306    = pprPanic "assignReg_I64Code(sparc): invalid lvalue"
307               (pprStixReg lvalue)
308
309
310 -- Don't delete this -- it's very handy for debugging.
311 --iselExpr64 expr 
312 --   | trace ("iselExpr64: " ++ showSDoc (pprCmmExpr expr)) False
313 --   = panic "iselExpr64(???)"
314
315 iselExpr64 (CmmLoad I64 addrTree)
316    = getRegister addrTree               `thenNat` \ register_addr ->
317      getNewRegNat IntRep                `thenNat` \ t_addr ->
318      getNewRegNat IntRep                `thenNat` \ rlo ->
319      let rhi = getHiVRegFromLo rlo
320          code_addr = registerCode register_addr t_addr
321          reg_addr  = registerName register_addr t_addr
322          mov_hi = LD W (AddrRegImm reg_addr (ImmInt 0)) rhi
323          mov_lo = LD W (AddrRegImm reg_addr (ImmInt 4)) rlo
324      in
325          return (
326             ChildCode64 (code_addr `snocOL` mov_hi `snocOL` mov_lo) 
327                         (getVRegUnique rlo)
328          )
329
330 iselExpr64 (CmmReg (CmmLocal (LocalReg uq I64)))
331    = getNewRegNat IntRep                `thenNat` \ r_dst_lo ->
332      let r_dst_hi = getHiVRegFromLo r_dst_lo
333          r_src_lo = mkVReg vu IntRep
334          r_src_hi = getHiVRegFromLo r_src_lo
335          mov_lo = mkMOV r_src_lo r_dst_lo
336          mov_hi = mkMOV r_src_hi r_dst_hi
337          mkMOV sreg dreg = OR False g0 (RIReg sreg) dreg
338      in
339          return (
340             ChildCode64 (toOL [mov_hi, mov_lo]) (getVRegUnique r_dst_lo)
341          )
342
343 iselExpr64 (StCall fn cconv I64 args)
344   = genCCall fn cconv kind args                 `thenNat` \ call ->
345     getNewRegNat IntRep                         `thenNat` \ r_dst_lo ->
346     let r_dst_hi = getHiVRegFromLo r_dst_lo
347         mov_lo = mkMOV o0 r_dst_lo
348         mov_hi = mkMOV o1 r_dst_hi
349         mkMOV sreg dreg = OR False g0 (RIReg sreg) dreg
350     in
351     return (
352        ChildCode64 (call `snocOL` mov_hi `snocOL` mov_lo) 
353                    (getVRegUnique r_dst_lo)
354     )
355
356 iselExpr64 expr
357    = pprPanic "iselExpr64(sparc)" (pprCmmExpr expr)
358
359 #endif /* sparc_TARGET_ARCH */
360
361 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
362
363 #if powerpc_TARGET_ARCH
364
365 getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock)
366 getI64Amodes addrTree = do
367     Amode hi_addr addr_code <- getAmode addrTree
368     case addrOffset hi_addr 4 of
369         Just lo_addr -> return (hi_addr, lo_addr, addr_code)
370         Nothing      -> do (hi_ptr, code) <- getSomeReg addrTree
371                            return (AddrRegImm hi_ptr (ImmInt 0),
372                                    AddrRegImm hi_ptr (ImmInt 4),
373                                    code)
374
375 assignMem_I64Code addrTree valueTree = do
376         (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
377         ChildCode64 vcode rlo <- iselExpr64 valueTree
378         let 
379                 rhi = getHiVRegFromLo rlo
380
381                 -- Big-endian store
382                 mov_hi = ST I32 rhi hi_addr
383                 mov_lo = ST I32 rlo lo_addr
384         -- in
385         return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
386
387 assignReg_I64Code (CmmLocal (LocalReg u_dst pk)) valueTree = do
388    ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
389    let 
390          r_dst_lo = mkVReg u_dst I32
391          r_dst_hi = getHiVRegFromLo r_dst_lo
392          r_src_hi = getHiVRegFromLo r_src_lo
393          mov_lo = MR r_dst_lo r_src_lo
394          mov_hi = MR r_dst_hi r_src_hi
395    -- in
396    return (
397         vcode `snocOL` mov_lo `snocOL` mov_hi
398      )
399
400 assignReg_I64Code lvalue valueTree
401    = panic "assignReg_I64Code(powerpc): invalid lvalue"
402
403
404 -- Don't delete this -- it's very handy for debugging.
405 --iselExpr64 expr 
406 --   | trace ("iselExpr64: " ++ showSDoc (pprCmmExpr expr)) False
407 --   = panic "iselExpr64(???)"
408
409 iselExpr64 (CmmLoad addrTree I64) = do
410     (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree
411     (rlo, rhi) <- getNewRegPairNat I32
412     let mov_hi = LD I32 rhi hi_addr
413         mov_lo = LD I32 rlo lo_addr
414     return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) 
415                          rlo
416
417 iselExpr64 (CmmReg (CmmLocal (LocalReg vu I64)))
418    = return (ChildCode64 nilOL (mkVReg vu I32))
419
420 iselExpr64 (CmmLit (CmmInt i _)) = do
421   (rlo,rhi) <- getNewRegPairNat I32
422   let
423         half0 = fromIntegral (fromIntegral i :: Word16)
424         half1 = fromIntegral ((fromIntegral i `shiftR` 16) :: Word16)
425         half2 = fromIntegral ((fromIntegral i `shiftR` 32) :: Word16)
426         half3 = fromIntegral ((fromIntegral i `shiftR` 48) :: Word16)
427         
428         code = toOL [
429                 LIS rlo (ImmInt half1),
430                 OR rlo rlo (RIImm $ ImmInt half0),
431                 LIS rhi (ImmInt half3),
432                 OR rlo rlo (RIImm $ ImmInt half2)
433                 ]
434   -- in
435   return (ChildCode64 code rlo)
436
437 iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
438    ChildCode64 code1 r1lo <- iselExpr64 e1
439    ChildCode64 code2 r2lo <- iselExpr64 e2
440    (rlo,rhi) <- getNewRegPairNat I32
441    let
442         r1hi = getHiVRegFromLo r1lo
443         r2hi = getHiVRegFromLo r2lo
444         code =  code1 `appOL`
445                 code2 `appOL`
446                 toOL [ ADDC rlo r1lo r2lo,
447                        ADDE rhi r1hi r2hi ]
448    -- in
449    return (ChildCode64 code rlo)
450
451 iselExpr64 expr
452    = pprPanic "iselExpr64(powerpc)" (ppr expr)
453
454 #endif /* powerpc_TARGET_ARCH */
455
456
457 -- -----------------------------------------------------------------------------
458 -- The 'Register' type
459
460 -- 'Register's passed up the tree.  If the stix code forces the register
461 -- to live in a pre-decided machine register, it comes out as @Fixed@;
462 -- otherwise, it comes out as @Any@, and the parent can decide which
463 -- register to put it in.
464
465 data Register
466   = Fixed   MachRep Reg InstrBlock
467   | Any     MachRep (Reg -> InstrBlock)
468
469 swizzleRegisterRep :: Register -> MachRep -> Register
470 swizzleRegisterRep (Fixed _ reg code) rep = Fixed rep reg code
471 swizzleRegisterRep (Any _ codefn)     rep = Any rep codefn
472
473
474 -- -----------------------------------------------------------------------------
475 -- Utils based on getRegister, below
476
477 -- The dual to getAnyReg: compute an expression into a register, but
478 -- we don't mind which one it is.
479 getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
480 getSomeReg expr = do
481   r <- getRegister expr
482   case r of
483     Any rep code -> do
484         tmp <- getNewRegNat rep
485         return (tmp, code tmp)
486     Fixed _ reg code -> 
487         return (reg, code)
488
489 -- -----------------------------------------------------------------------------
490 -- Grab the Reg for a CmmReg
491
492 getRegisterReg :: CmmReg -> Reg
493
494 getRegisterReg (CmmLocal (LocalReg u pk))
495   = mkVReg u pk
496
497 getRegisterReg (CmmGlobal mid)
498   = case get_GlobalReg_reg_or_addr mid of
499        Left (RealReg rrno) -> RealReg rrno
500        _other -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
501           -- By this stage, the only MagicIds remaining should be the
502           -- ones which map to a real machine register on this
503           -- platform.  Hence ...
504
505
506 -- -----------------------------------------------------------------------------
507 -- Generate code to get a subtree into a Register
508
509 -- Don't delete this -- it's very handy for debugging.
510 --getRegister expr 
511 --   | trace ("getRegister: " ++ showSDoc (pprCmmExpr expr)) False
512 --   = panic "getRegister(???)"
513
514 getRegister :: CmmExpr -> NatM Register
515
516 getRegister (CmmReg reg) 
517   = return (Fixed (cmmRegRep reg) (getRegisterReg reg) nilOL)
518
519 getRegister tree@(CmmRegOff _ _) 
520   = getRegister (mangleIndexTree tree)
521
522 getRegister CmmPicBaseReg
523   = do
524       reg <- getPicBaseNat wordRep
525       return (Fixed wordRep reg nilOL)
526
527 -- end of machine-"independent" bit; here we go on the rest...
528
529 #if alpha_TARGET_ARCH
530
531 getRegister (StDouble d)
532   = getBlockIdNat                   `thenNat` \ lbl ->
533     getNewRegNat PtrRep             `thenNat` \ tmp ->
534     let code dst = mkSeqInstrs [
535             LDATA RoDataSegment lbl [
536                     DATA TF [ImmLab (rational d)]
537                 ],
538             LDA tmp (AddrImm (ImmCLbl lbl)),
539             LD TF dst (AddrReg tmp)]
540     in
541         return (Any F64 code)
542
543 getRegister (StPrim primop [x]) -- unary PrimOps
544   = case primop of
545       IntNegOp -> trivialUCode (NEG Q False) x
546
547       NotOp    -> trivialUCode NOT x
548
549       FloatNegOp  -> trivialUFCode FloatRep  (FNEG TF) x
550       DoubleNegOp -> trivialUFCode F64 (FNEG TF) x
551
552       OrdOp -> coerceIntCode IntRep x
553       ChrOp -> chrCode x
554
555       Float2IntOp  -> coerceFP2Int    x
556       Int2FloatOp  -> coerceInt2FP pr x
557       Double2IntOp -> coerceFP2Int    x
558       Int2DoubleOp -> coerceInt2FP pr x
559
560       Double2FloatOp -> coerceFltCode x
561       Float2DoubleOp -> coerceFltCode x
562
563       other_op -> getRegister (StCall fn CCallConv F64 [x])
564         where
565           fn = case other_op of
566                  FloatExpOp    -> FSLIT("exp")
567                  FloatLogOp    -> FSLIT("log")
568                  FloatSqrtOp   -> FSLIT("sqrt")
569                  FloatSinOp    -> FSLIT("sin")
570                  FloatCosOp    -> FSLIT("cos")
571                  FloatTanOp    -> FSLIT("tan")
572                  FloatAsinOp   -> FSLIT("asin")
573                  FloatAcosOp   -> FSLIT("acos")
574                  FloatAtanOp   -> FSLIT("atan")
575                  FloatSinhOp   -> FSLIT("sinh")
576                  FloatCoshOp   -> FSLIT("cosh")
577                  FloatTanhOp   -> FSLIT("tanh")
578                  DoubleExpOp   -> FSLIT("exp")
579                  DoubleLogOp   -> FSLIT("log")
580                  DoubleSqrtOp  -> FSLIT("sqrt")
581                  DoubleSinOp   -> FSLIT("sin")
582                  DoubleCosOp   -> FSLIT("cos")
583                  DoubleTanOp   -> FSLIT("tan")
584                  DoubleAsinOp  -> FSLIT("asin")
585                  DoubleAcosOp  -> FSLIT("acos")
586                  DoubleAtanOp  -> FSLIT("atan")
587                  DoubleSinhOp  -> FSLIT("sinh")
588                  DoubleCoshOp  -> FSLIT("cosh")
589                  DoubleTanhOp  -> FSLIT("tanh")
590   where
591     pr = panic "MachCode.getRegister: no primrep needed for Alpha"
592
593 getRegister (StPrim primop [x, y]) -- dyadic PrimOps
594   = case primop of
595       CharGtOp -> trivialCode (CMP LTT) y x
596       CharGeOp -> trivialCode (CMP LE) y x
597       CharEqOp -> trivialCode (CMP EQQ) x y
598       CharNeOp -> int_NE_code x y
599       CharLtOp -> trivialCode (CMP LTT) x y
600       CharLeOp -> trivialCode (CMP LE) x y
601
602       IntGtOp  -> trivialCode (CMP LTT) y x
603       IntGeOp  -> trivialCode (CMP LE) y x
604       IntEqOp  -> trivialCode (CMP EQQ) x y
605       IntNeOp  -> int_NE_code x y
606       IntLtOp  -> trivialCode (CMP LTT) x y
607       IntLeOp  -> trivialCode (CMP LE) x y
608
609       WordGtOp -> trivialCode (CMP ULT) y x
610       WordGeOp -> trivialCode (CMP ULE) x y
611       WordEqOp -> trivialCode (CMP EQQ)  x y
612       WordNeOp -> int_NE_code x y
613       WordLtOp -> trivialCode (CMP ULT) x y
614       WordLeOp -> trivialCode (CMP ULE) x y
615
616       AddrGtOp -> trivialCode (CMP ULT) y x
617       AddrGeOp -> trivialCode (CMP ULE) y x
618       AddrEqOp -> trivialCode (CMP EQQ)  x y
619       AddrNeOp -> int_NE_code x y
620       AddrLtOp -> trivialCode (CMP ULT) x y
621       AddrLeOp -> trivialCode (CMP ULE) x y
622         
623       FloatGtOp -> cmpF_code (FCMP TF LE) EQQ x y
624       FloatGeOp -> cmpF_code (FCMP TF LTT) EQQ x y
625       FloatEqOp -> cmpF_code (FCMP TF EQQ) NE x y
626       FloatNeOp -> cmpF_code (FCMP TF EQQ) EQQ x y
627       FloatLtOp -> cmpF_code (FCMP TF LTT) NE x y
628       FloatLeOp -> cmpF_code (FCMP TF LE) NE x y
629
630       DoubleGtOp -> cmpF_code (FCMP TF LE) EQQ x y
631       DoubleGeOp -> cmpF_code (FCMP TF LTT) EQQ x y
632       DoubleEqOp -> cmpF_code (FCMP TF EQQ) NE x y
633       DoubleNeOp -> cmpF_code (FCMP TF EQQ) EQQ x y
634       DoubleLtOp -> cmpF_code (FCMP TF LTT) NE x y
635       DoubleLeOp -> cmpF_code (FCMP TF LE) NE x y
636
637       IntAddOp  -> trivialCode (ADD Q False) x y
638       IntSubOp  -> trivialCode (SUB Q False) x y
639       IntMulOp  -> trivialCode (MUL Q False) x y
640       IntQuotOp -> trivialCode (DIV Q False) x y
641       IntRemOp  -> trivialCode (REM Q False) x y
642
643       WordAddOp  -> trivialCode (ADD Q False) x y
644       WordSubOp  -> trivialCode (SUB Q False) x y
645       WordMulOp  -> trivialCode (MUL Q False) x y
646       WordQuotOp -> trivialCode (DIV Q True) x y
647       WordRemOp  -> trivialCode (REM Q True) x y
648
649       FloatAddOp -> trivialFCode  FloatRep (FADD TF) x y
650       FloatSubOp -> trivialFCode  FloatRep (FSUB TF) x y
651       FloatMulOp -> trivialFCode  FloatRep (FMUL TF) x y
652       FloatDivOp -> trivialFCode  FloatRep (FDIV TF) x y
653
654       DoubleAddOp -> trivialFCode  F64 (FADD TF) x y
655       DoubleSubOp -> trivialFCode  F64 (FSUB TF) x y
656       DoubleMulOp -> trivialFCode  F64 (FMUL TF) x y
657       DoubleDivOp -> trivialFCode  F64 (FDIV TF) x y
658
659       AddrAddOp  -> trivialCode (ADD Q False) x y
660       AddrSubOp  -> trivialCode (SUB Q False) x y
661       AddrRemOp  -> trivialCode (REM Q True) x y
662
663       AndOp  -> trivialCode AND x y
664       OrOp   -> trivialCode OR  x y
665       XorOp  -> trivialCode XOR x y
666       SllOp  -> trivialCode SLL x y
667       SrlOp  -> trivialCode SRL x y
668
669       ISllOp -> trivialCode SLL x y -- was: panic "AlphaGen:isll"
670       ISraOp -> trivialCode SRA x y -- was: panic "AlphaGen:isra"
671       ISrlOp -> trivialCode SRL x y -- was: panic "AlphaGen:isrl"
672
673       FloatPowerOp  -> getRegister (StCall FSLIT("pow") CCallConv F64 [x,y])
674       DoublePowerOp -> getRegister (StCall FSLIT("pow") CCallConv F64 [x,y])
675   where
676     {- ------------------------------------------------------------
677         Some bizarre special code for getting condition codes into
678         registers.  Integer non-equality is a test for equality
679         followed by an XOR with 1.  (Integer comparisons always set
680         the result register to 0 or 1.)  Floating point comparisons of
681         any kind leave the result in a floating point register, so we
682         need to wrangle an integer register out of things.
683     -}
684     int_NE_code :: StixTree -> StixTree -> NatM Register
685
686     int_NE_code x y
687       = trivialCode (CMP EQQ) x y       `thenNat` \ register ->
688         getNewRegNat IntRep             `thenNat` \ tmp ->
689         let
690             code = registerCode register tmp
691             src  = registerName register tmp
692             code__2 dst = code . mkSeqInstr (XOR src (RIImm (ImmInt 1)) dst)
693         in
694         return (Any IntRep code__2)
695
696     {- ------------------------------------------------------------
697         Comments for int_NE_code also apply to cmpF_code
698     -}
699     cmpF_code
700         :: (Reg -> Reg -> Reg -> Instr)
701         -> Cond
702         -> StixTree -> StixTree
703         -> NatM Register
704
705     cmpF_code instr cond x y
706       = trivialFCode pr instr x y       `thenNat` \ register ->
707         getNewRegNat F64                `thenNat` \ tmp ->
708         getBlockIdNat                   `thenNat` \ lbl ->
709         let
710             code = registerCode register tmp
711             result  = registerName register tmp
712
713             code__2 dst = code . mkSeqInstrs [
714                 OR zeroh (RIImm (ImmInt 1)) dst,
715                 BF cond  result (ImmCLbl lbl),
716                 OR zeroh (RIReg zeroh) dst,
717                 NEWBLOCK lbl]
718         in
719         return (Any IntRep code__2)
720       where
721         pr = panic "trivialU?FCode: does not use PrimRep on Alpha"
722       ------------------------------------------------------------
723
724 getRegister (CmmLoad pk mem)
725   = getAmode mem                    `thenNat` \ amode ->
726     let
727         code = amodeCode amode
728         src   = amodeAddr amode
729         size = primRepToSize pk
730         code__2 dst = code . mkSeqInstr (LD size dst src)
731     in
732     return (Any pk code__2)
733
734 getRegister (StInt i)
735   | fits8Bits i
736   = let
737         code dst = mkSeqInstr (OR zeroh (RIImm src) dst)
738     in
739     return (Any IntRep code)
740   | otherwise
741   = let
742         code dst = mkSeqInstr (LDI Q dst src)
743     in
744     return (Any IntRep code)
745   where
746     src = ImmInt (fromInteger i)
747
748 getRegister leaf
749   | isJust imm
750   = let
751         code dst = mkSeqInstr (LDA dst (AddrImm imm__2))
752     in
753     return (Any PtrRep code)
754   where
755     imm = maybeImm leaf
756     imm__2 = case imm of Just x -> x
757
758 #endif /* alpha_TARGET_ARCH */
759
760 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
761
762 #if i386_TARGET_ARCH
763
764 getRegister (CmmLit (CmmFloat f F32)) = do
765     lbl <- getNewLabelNat
766     let code dst = toOL [
767             LDATA ReadOnlyData
768                         [CmmDataLabel lbl,
769                          CmmStaticLit (CmmFloat f F32)],
770             GLD F32 (ImmAddr (ImmCLbl lbl) 0) dst
771             ]
772     -- in
773     return (Any F32 code)
774
775
776 getRegister (CmmLit (CmmFloat d F64))
777   | d == 0.0
778   = let code dst = unitOL (GLDZ dst)
779     in  return (Any F64 code)
780
781   | d == 1.0
782   = let code dst = unitOL (GLD1 dst)
783     in  return (Any F64 code)
784
785   | otherwise = do
786     lbl <- getNewLabelNat
787     let code dst = toOL [
788             LDATA ReadOnlyData
789                         [CmmDataLabel lbl,
790                          CmmStaticLit (CmmFloat d F64)],
791             GLD F64 (ImmAddr (ImmCLbl lbl) 0) dst
792             ]
793     -- in
794     return (Any F64 code)
795
796 #endif /* i386_TARGET_ARCH */
797
798 #if x86_64_TARGET_ARCH
799
800 getRegister (CmmLit (CmmFloat 0.0 rep)) = do
801    let code dst = unitOL  (XOR rep (OpReg dst) (OpReg dst))
802         -- I don't know why there are xorpd, xorps, and pxor instructions.
803         -- They all appear to do the same thing --SDM
804    return (Any rep code)
805
806 getRegister (CmmLit (CmmFloat f rep)) = do
807     lbl <- getNewLabelNat
808     let code dst = toOL [
809             LDATA ReadOnlyData
810                         [CmmDataLabel lbl,
811                          CmmStaticLit (CmmFloat f rep)],
812             MOV rep (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
813             ]
814     -- in
815     return (Any rep code)
816
817 #endif /* x86_64_TARGET_ARCH */
818
819 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
820
821 -- catch simple cases of zero- or sign-extended load
822 getRegister (CmmMachOp (MO_U_Conv I8 I32) [CmmLoad addr _]) = do
823   code <- intLoadCode (MOVZxL I8) addr
824   return (Any I32 code)
825
826 getRegister (CmmMachOp (MO_S_Conv I8 I32) [CmmLoad addr _]) = do
827   code <- intLoadCode (MOVSxL I8) addr
828   return (Any I32 code)
829
830 getRegister (CmmMachOp (MO_U_Conv I16 I32) [CmmLoad addr _]) = do
831   code <- intLoadCode (MOVZxL I16) addr
832   return (Any I32 code)
833
834 getRegister (CmmMachOp (MO_S_Conv I16 I32) [CmmLoad addr _]) = do
835   code <- intLoadCode (MOVSxL I16) addr
836   return (Any I32 code)
837
838 #endif
839
840 #if x86_64_TARGET_ARCH
841
842 -- catch simple cases of zero- or sign-extended load
843 getRegister (CmmMachOp (MO_U_Conv I8 I64) [CmmLoad addr _]) = do
844   code <- intLoadCode (MOVZxL I8) addr
845   return (Any I64 code)
846
847 getRegister (CmmMachOp (MO_S_Conv I8 I64) [CmmLoad addr _]) = do
848   code <- intLoadCode (MOVSxL I8) addr
849   return (Any I64 code)
850
851 getRegister (CmmMachOp (MO_U_Conv I16 I64) [CmmLoad addr _]) = do
852   code <- intLoadCode (MOVZxL I16) addr
853   return (Any I64 code)
854
855 getRegister (CmmMachOp (MO_S_Conv I16 I64) [CmmLoad addr _]) = do
856   code <- intLoadCode (MOVSxL I16) addr
857   return (Any I64 code)
858
859 getRegister (CmmMachOp (MO_U_Conv I32 I64) [CmmLoad addr _]) = do
860   code <- intLoadCode (MOV I32) addr -- 32-bit loads zero-extend
861   return (Any I64 code)
862
863 getRegister (CmmMachOp (MO_S_Conv I32 I64) [CmmLoad addr _]) = do
864   code <- intLoadCode (MOVSxL I32) addr
865   return (Any I64 code)
866
867 #endif
868
869 #if x86_64_TARGET_ARCH
870 getRegister (CmmMachOp (MO_S_Neg F32) [x]) = do
871   x_code <- getAnyReg x
872   lbl <- getNewLabelNat
873   let
874     code dst = x_code dst `appOL` toOL [
875         -- This is how gcc does it, so it can't be that bad:
876         LDATA ReadOnlyData16 [
877                 CmmAlign 16,
878                 CmmDataLabel lbl,
879                 CmmStaticLit (CmmInt 0x80000000 I32),
880                 CmmStaticLit (CmmInt 0 I32),
881                 CmmStaticLit (CmmInt 0 I32),
882                 CmmStaticLit (CmmInt 0 I32)
883         ],
884         XOR F32 (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
885                 -- xorps, so we need the 128-bit constant
886                 -- ToDo: rip-relative
887         ]
888   --
889   return (Any F32 code)
890
891 getRegister (CmmMachOp (MO_S_Neg F64) [x]) = do
892   x_code <- getAnyReg x
893   lbl <- getNewLabelNat
894   let
895         -- This is how gcc does it, so it can't be that bad:
896     code dst = x_code dst `appOL` toOL [
897         LDATA ReadOnlyData16 [
898                 CmmAlign 16,
899                 CmmDataLabel lbl,
900                 CmmStaticLit (CmmInt 0x8000000000000000 I64),
901                 CmmStaticLit (CmmInt 0 I64)
902         ],
903                 -- gcc puts an unpck here.  Wonder if we need it.
904         XOR F64 (OpAddr (ripRel (ImmCLbl lbl))) (OpReg dst)
905                 -- xorpd, so we need the 128-bit constant
906         ]
907   --
908   return (Any F64 code)
909 #endif
910
911 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
912
913 getRegister (CmmMachOp mop [x]) -- unary MachOps
914   = case mop of
915 #if i386_TARGET_ARCH
916       MO_S_Neg F32 -> trivialUFCode F32 (GNEG F32) x
917       MO_S_Neg F64 -> trivialUFCode F64 (GNEG F64) x
918 #endif
919
920       MO_S_Neg rep -> trivialUCode rep (NEGI rep) x
921       MO_Not rep   -> trivialUCode rep (NOT  rep) x
922
923       -- Nop conversions
924       -- TODO: these are only nops if the arg is not a fixed register that
925       -- can't be byte-addressed.
926       MO_U_Conv I32 I8  -> conversionNop I32 x
927       MO_S_Conv I32 I8  -> conversionNop I32 x
928       MO_U_Conv I16 I8  -> conversionNop I16 x
929       MO_S_Conv I16 I8  -> conversionNop I16 x
930       MO_U_Conv I32 I16 -> conversionNop I32 x
931       MO_S_Conv I32 I16 -> conversionNop I32 x
932 #if x86_64_TARGET_ARCH
933       MO_U_Conv I64 I32 -> conversionNop I64 x
934       MO_S_Conv I64 I32 -> conversionNop I64 x
935       MO_U_Conv I64 I16 -> conversionNop I64 x
936       MO_S_Conv I64 I16 -> conversionNop I64 x
937       MO_U_Conv I64 I8  -> conversionNop I64 x
938       MO_S_Conv I64 I8  -> conversionNop I64 x
939 #endif
940
941       MO_U_Conv rep1 rep2 | rep1 == rep2 -> conversionNop rep1 x
942       MO_S_Conv rep1 rep2 | rep1 == rep2 -> conversionNop rep1 x
943
944       -- widenings
945       MO_U_Conv I8  I32 -> integerExtend I8  I32 MOVZxL x
946       MO_U_Conv I16 I32 -> integerExtend I16 I32 MOVZxL x
947       MO_U_Conv I8  I16 -> integerExtend I8  I16 MOVZxL x
948
949       MO_S_Conv I8  I32 -> integerExtend I8  I32 MOVSxL x
950       MO_S_Conv I16 I32 -> integerExtend I16 I32 MOVSxL x
951       MO_S_Conv I8  I16 -> integerExtend I8  I16 MOVSxL x
952
953 #if x86_64_TARGET_ARCH
954       MO_U_Conv I8  I64 -> integerExtend I8  I64 MOVZxL x
955       MO_U_Conv I16 I64 -> integerExtend I16 I64 MOVZxL x
956       MO_U_Conv I32 I64 -> integerExtend I32 I64 MOVZxL x
957       MO_S_Conv I8  I64 -> integerExtend I8  I64 MOVSxL x
958       MO_S_Conv I16 I64 -> integerExtend I16 I64 MOVSxL x
959       MO_S_Conv I32 I64 -> integerExtend I32 I64 MOVSxL x
960         -- for 32-to-64 bit zero extension, amd64 uses an ordinary movl.
961         -- However, we don't want the register allocator to throw it
962         -- away as an unnecessary reg-to-reg move, so we keep it in
963         -- the form of a movzl and print it as a movl later.
964 #endif
965
966 #if i386_TARGET_ARCH
967       MO_S_Conv F32 F64 -> conversionNop F64 x
968       MO_S_Conv F64 F32 -> conversionNop F32 x
969 #else
970       MO_S_Conv F32 F64 -> coerceFP2FP F64 x
971       MO_S_Conv F64 F32 -> coerceFP2FP F32 x
972 #endif
973
974       MO_S_Conv from to
975         | isFloatingRep from -> coerceFP2Int from to x
976         | isFloatingRep to   -> coerceInt2FP from to x
977
978       other -> pprPanic "getRegister" (pprMachOp mop)
979    where
980         -- signed or unsigned extension.
981         integerExtend from to instr expr = do
982             (reg,e_code) <- if from == I8 then getByteReg expr
983                                           else getSomeReg expr
984             let 
985                 code dst = 
986                   e_code `snocOL`
987                   instr from (OpReg reg) (OpReg dst)
988             return (Any to code)
989
990         conversionNop new_rep expr
991             = do e_code <- getRegister expr
992                  return (swizzleRegisterRep e_code new_rep)
993
994
995 getRegister e@(CmmMachOp mop [x, y]) -- dyadic MachOps
996   = ASSERT2(cmmExprRep x /= I8, pprExpr e)
997     case mop of
998       MO_Eq F32   -> condFltReg EQQ x y
999       MO_Ne F32   -> condFltReg NE x y
1000       MO_S_Gt F32 -> condFltReg GTT x y
1001       MO_S_Ge F32 -> condFltReg GE x y
1002       MO_S_Lt F32 -> condFltReg LTT x y
1003       MO_S_Le F32 -> condFltReg LE x y
1004
1005       MO_Eq F64   -> condFltReg EQQ x y
1006       MO_Ne F64   -> condFltReg NE x y
1007       MO_S_Gt F64 -> condFltReg GTT x y
1008       MO_S_Ge F64 -> condFltReg GE x y
1009       MO_S_Lt F64 -> condFltReg LTT x y
1010       MO_S_Le F64 -> condFltReg LE x y
1011
1012       MO_Eq rep   -> condIntReg EQQ x y
1013       MO_Ne rep   -> condIntReg NE x y
1014
1015       MO_S_Gt rep -> condIntReg GTT x y
1016       MO_S_Ge rep -> condIntReg GE x y
1017       MO_S_Lt rep -> condIntReg LTT x y
1018       MO_S_Le rep -> condIntReg LE x y
1019
1020       MO_U_Gt rep -> condIntReg GU  x y
1021       MO_U_Ge rep -> condIntReg GEU x y
1022       MO_U_Lt rep -> condIntReg LU  x y
1023       MO_U_Le rep -> condIntReg LEU x y
1024
1025 #if i386_TARGET_ARCH
1026       MO_Add F32 -> trivialFCode F32 GADD x y
1027       MO_Sub F32 -> trivialFCode F32 GSUB x y
1028
1029       MO_Add F64 -> trivialFCode F64 GADD x y
1030       MO_Sub F64 -> trivialFCode F64 GSUB x y
1031
1032       MO_S_Quot F32 -> trivialFCode F32 GDIV x y
1033       MO_S_Quot F64 -> trivialFCode F64 GDIV x y
1034 #endif
1035
1036 #if x86_64_TARGET_ARCH
1037       MO_Add F32 -> trivialFCode F32 ADD x y
1038       MO_Sub F32 -> trivialFCode F32 SUB x y
1039
1040       MO_Add F64 -> trivialFCode F64 ADD x y
1041       MO_Sub F64 -> trivialFCode F64 SUB x y
1042
1043       MO_S_Quot F32 -> trivialFCode F32 FDIV x y
1044       MO_S_Quot F64 -> trivialFCode F64 FDIV x y
1045 #endif
1046
1047       MO_Add rep -> add_code rep x y
1048       MO_Sub rep -> sub_code rep x y
1049
1050       MO_S_Quot rep -> div_code rep True  True  x y
1051       MO_S_Rem  rep -> div_code rep True  False x y
1052       MO_U_Quot rep -> div_code rep False True  x y
1053       MO_U_Rem  rep -> div_code rep False False x y
1054
1055 #if i386_TARGET_ARCH
1056       MO_Mul   F32 -> trivialFCode F32 GMUL x y
1057       MO_Mul   F64 -> trivialFCode F64 GMUL x y
1058 #endif
1059
1060 #if x86_64_TARGET_ARCH
1061       MO_Mul   F32 -> trivialFCode F32 MUL x y
1062       MO_Mul   F64 -> trivialFCode F64 MUL x y
1063 #endif
1064
1065       MO_Mul   rep -> let op = IMUL rep in 
1066                       trivialCode rep op (Just op) x y
1067
1068       MO_S_MulMayOflo rep -> imulMayOflo rep x y
1069
1070       MO_And rep -> let op = AND rep in 
1071                     trivialCode rep op (Just op) x y
1072       MO_Or  rep -> let op = OR  rep in
1073                     trivialCode rep op (Just op) x y
1074       MO_Xor rep -> let op = XOR rep in
1075                     trivialCode rep op (Just op) x y
1076
1077         {- Shift ops on x86s have constraints on their source, it
1078            either has to be Imm, CL or 1
1079             => trivialCode is not restrictive enough (sigh.)
1080         -}         
1081       MO_Shl rep   -> shift_code rep (SHL rep) x y {-False-}
1082       MO_U_Shr rep -> shift_code rep (SHR rep) x y {-False-}
1083       MO_S_Shr rep -> shift_code rep (SAR rep) x y {-False-}
1084
1085       other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
1086   where
1087     --------------------
1088     imulMayOflo :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1089     imulMayOflo rep a b = do
1090          (a_reg, a_code) <- getNonClobberedReg a
1091          b_code <- getAnyReg b
1092          let 
1093              shift_amt  = case rep of
1094                            I32 -> 31
1095                            I64 -> 63
1096                            _ -> panic "shift_amt"
1097
1098              code = a_code `appOL` b_code eax `appOL`
1099                         toOL [
1100                            IMUL2 rep (OpReg a_reg),   -- result in %edx:%eax
1101                            SAR rep (OpImm (ImmInt shift_amt)) (OpReg eax),
1102                                 -- sign extend lower part
1103                            SUB rep (OpReg edx) (OpReg eax)
1104                                 -- compare against upper
1105                            -- eax==0 if high part == sign extended low part
1106                         ]
1107          -- in
1108          return (Fixed rep eax code)
1109
1110     --------------------
1111     shift_code :: MachRep
1112                -> (Operand -> Operand -> Instr)
1113                -> CmmExpr
1114                -> CmmExpr
1115                -> NatM Register
1116
1117     {- Case1: shift length as immediate -}
1118     shift_code rep instr x y@(CmmLit lit) = do
1119           x_code <- getAnyReg x
1120           let
1121                code dst
1122                   = x_code dst `snocOL` 
1123                     instr (OpImm (litToImm lit)) (OpReg dst)
1124           -- in
1125           return (Any rep code)
1126         
1127     {- Case2: shift length is complex (non-immediate) -}
1128     shift_code rep instr x y{-amount-} = do
1129         (x_reg, x_code) <- getNonClobberedReg x
1130         y_code <- getAnyReg y
1131         let 
1132            code = x_code `appOL`
1133                   y_code ecx `snocOL`
1134                   instr (OpReg ecx) (OpReg x_reg)
1135         -- in
1136         return (Fixed rep x_reg code)
1137
1138     --------------------
1139     add_code :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1140     add_code rep x (CmmLit (CmmInt y _)) = add_int rep x y
1141     add_code rep x y = trivialCode rep (ADD rep) (Just (ADD rep)) x y
1142
1143     --------------------
1144     sub_code :: MachRep -> CmmExpr -> CmmExpr -> NatM Register
1145     sub_code rep x (CmmLit (CmmInt y _)) = add_int rep x (-y)
1146     sub_code rep x y = trivialCode rep (SUB rep) Nothing x y
1147
1148     -- our three-operand add instruction:
1149     add_int rep x y = do
1150         (x_reg, x_code) <- getSomeReg x
1151         let
1152             imm = ImmInt (fromInteger y)
1153             code dst
1154                = x_code `snocOL`
1155                  LEA rep
1156                         (OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
1157                         (OpReg dst)
1158         -- 
1159         return (Any rep code)
1160
1161     ----------------------
1162     div_code rep signed quotient x y = do
1163            (y_op, y_code) <- getRegOrMem y -- cannot be clobbered
1164            x_code <- getAnyReg x
1165            let
1166              widen | signed    = CLTD rep
1167                    | otherwise = XOR rep (OpReg edx) (OpReg edx)
1168
1169              instr | signed    = IDIV
1170                    | otherwise = DIV
1171
1172              code = y_code `appOL`
1173                     x_code eax `appOL`
1174                     toOL [widen, instr rep y_op]
1175
1176              result | quotient  = eax
1177                     | otherwise = edx
1178
1179            -- in
1180            return (Fixed rep result code)
1181
1182
1183 getRegister (CmmLoad mem pk)
1184   | isFloatingRep pk
1185   = do
1186     Amode src mem_code <- getAmode mem
1187     let
1188         code dst = mem_code `snocOL` 
1189                    IF_ARCH_i386(GLD pk src dst,
1190                                 MOV pk (OpAddr src) (OpReg dst))
1191     --
1192     return (Any pk code)
1193
1194 #if i386_TARGET_ARCH
1195 getRegister (CmmLoad mem pk)
1196   | pk /= I64
1197   = do 
1198     code <- intLoadCode (instr pk) mem
1199     return (Any pk code)
1200   where
1201         instr I8  = MOVZxL pk
1202         instr I16 = MOV I16
1203         instr I32 = MOV I32
1204         -- we always zero-extend 8-bit loads, if we
1205         -- can't think of anything better.  This is because
1206         -- we can't guarantee access to an 8-bit variant of every register
1207         -- (esi and edi don't have 8-bit variants), so to make things
1208         -- simpler we do our 8-bit arithmetic with full 32-bit registers.
1209 #endif
1210
1211 #if x86_64_TARGET_ARCH
1212 -- Simpler memory load code on x86_64
1213 getRegister (CmmLoad mem pk)
1214   = do 
1215     code <- intLoadCode (MOV pk) mem
1216     return (Any pk code)
1217 #endif
1218
1219 getRegister (CmmLit (CmmInt 0 rep))
1220   = let
1221         -- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
1222         adj_rep = case rep of I64 -> I32; _ -> rep
1223         rep1 = IF_ARCH_i386( rep, adj_rep ) 
1224         code dst 
1225            = unitOL (XOR rep1 (OpReg dst) (OpReg dst))
1226     in
1227         return (Any rep code)
1228
1229 #if x86_64_TARGET_ARCH
1230   -- optimisation for loading small literals on x86_64: take advantage
1231   -- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
1232   -- instruction forms are shorter.
1233 getRegister (CmmLit lit) 
1234   | I64 <- cmmLitRep lit, not (isBigLit lit)
1235   = let 
1236         imm = litToImm lit
1237         code dst = unitOL (MOV I32 (OpImm imm) (OpReg dst))
1238     in
1239         return (Any I64 code)
1240   where
1241    isBigLit (CmmInt i I64) = i < 0 || i > 0xffffffff
1242    isBigLit _ = False
1243         -- note1: not the same as is64BitLit, because that checks for
1244         -- signed literals that fit in 32 bits, but we want unsigned
1245         -- literals here.
1246         -- note2: all labels are small, because we're assuming the
1247         -- small memory model (see gcc docs, -mcmodel=small).
1248 #endif
1249
1250 getRegister (CmmLit lit)
1251   = let 
1252         rep = cmmLitRep lit
1253         imm = litToImm lit
1254         code dst = unitOL (MOV rep (OpImm imm) (OpReg dst))
1255     in
1256         return (Any rep code)
1257
1258 getRegister other = pprPanic "getRegister(x86)" (ppr other)
1259
1260
1261 intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
1262    -> NatM (Reg -> InstrBlock)
1263 intLoadCode instr mem = do
1264   Amode src mem_code <- getAmode mem
1265   return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))
1266
1267 -- Compute an expression into *any* register, adding the appropriate
1268 -- move instruction if necessary.
1269 getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
1270 getAnyReg expr = do
1271   r <- getRegister expr
1272   anyReg r
1273
1274 anyReg :: Register -> NatM (Reg -> InstrBlock)
1275 anyReg (Any _ code)          = return code
1276 anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)
1277
1278 -- A bit like getSomeReg, but we want a reg that can be byte-addressed.
1279 -- Fixed registers might not be byte-addressable, so we make sure we've
1280 -- got a temporary, inserting an extra reg copy if necessary.
1281 getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
1282 #if x86_64_TARGET_ARCH
1283 getByteReg = getSomeReg -- all regs are byte-addressable on x86_64
1284 #else
1285 getByteReg expr = do
1286   r <- getRegister expr
1287   case r of
1288     Any rep code -> do
1289         tmp <- getNewRegNat rep
1290         return (tmp, code tmp)
1291     Fixed rep reg code 
1292         | isVirtualReg reg -> return (reg,code)
1293         | otherwise -> do
1294             tmp <- getNewRegNat rep
1295             return (tmp, code `snocOL` reg2reg rep reg tmp)
1296         -- ToDo: could optimise slightly by checking for byte-addressable
1297         -- real registers, but that will happen very rarely if at all.
1298 #endif
1299
1300 -- Another variant: this time we want the result in a register that cannot
1301 -- be modified by code to evaluate an arbitrary expression.
1302 getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
1303 getNonClobberedReg expr = do
1304   r <- getRegister expr
1305   case r of
1306     Any rep code -> do
1307         tmp <- getNewRegNat rep
1308         return (tmp, code tmp)
1309     Fixed rep reg code
1310         -- only free regs can be clobbered
1311         | RealReg rr <- reg, isFastTrue (freeReg rr) -> do
1312                 tmp <- getNewRegNat rep
1313                 return (tmp, code `snocOL` reg2reg rep reg tmp)
1314         | otherwise -> 
1315                 return (reg, code)
1316
1317 reg2reg :: MachRep -> Reg -> Reg -> Instr
1318 reg2reg rep src dst 
1319 #if i386_TARGET_ARCH
1320   | isFloatingRep rep = GMOV src dst
1321 #endif
1322   | otherwise         = MOV rep (OpReg src) (OpReg dst)
1323
1324 #endif /* i386_TARGET_ARCH || x86_64_TARGET_ARCH */
1325
1326 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1327
1328 #if sparc_TARGET_ARCH
1329
1330 getRegister (StFloat d)
1331   = getBlockIdNat                   `thenNat` \ lbl ->
1332     getNewRegNat PtrRep             `thenNat` \ tmp ->
1333     let code dst = toOL [
1334             SEGMENT DataSegment,
1335             NEWBLOCK lbl,
1336             DATA F [ImmFloat d],
1337             SEGMENT TextSegment,
1338             SETHI (HI (ImmCLbl lbl)) tmp,
1339             LD F (AddrRegImm tmp (LO (ImmCLbl lbl))) dst]
1340     in
1341         return (Any F32 code)
1342
1343 getRegister (StDouble d)
1344   = getBlockIdNat                   `thenNat` \ lbl ->
1345     getNewRegNat PtrRep             `thenNat` \ tmp ->
1346     let code dst = toOL [
1347             SEGMENT DataSegment,
1348             NEWBLOCK lbl,
1349             DATA DF [ImmDouble d],
1350             SEGMENT TextSegment,
1351             SETHI (HI (ImmCLbl lbl)) tmp,
1352             LD DF (AddrRegImm tmp (LO (ImmCLbl lbl))) dst]
1353     in
1354         return (Any F64 code)
1355
1356
1357 getRegister (CmmMachOp mop [x]) -- unary PrimOps
1358   = case mop of
1359       MO_NatS_Neg      -> trivialUCode (SUB False False g0) x
1360       MO_Nat_Not       -> trivialUCode (XNOR False g0) x
1361       MO_32U_to_8U     -> trivialCode (AND False) x (StInt 255)
1362
1363       MO_F32_Neg       -> trivialUFCode F32 (FNEG F) x
1364       MO_F64_Neg       -> trivialUFCode F64 (FNEG DF) x
1365
1366       MO_F64_to_Flt    -> coerceDbl2Flt x
1367       MO_F32_to_Dbl    -> coerceFlt2Dbl x
1368
1369       MO_F32_to_NatS   -> coerceFP2Int F32 x
1370       MO_NatS_to_Flt   -> coerceInt2FP F32 x
1371       MO_F64_to_NatS   -> coerceFP2Int F64 x
1372       MO_NatS_to_Dbl   -> coerceInt2FP F64 x
1373
1374       -- Conversions which are a nop on sparc
1375       MO_32U_to_NatS   -> conversionNop IntRep   x
1376       MO_32S_to_NatS  -> conversionNop IntRep   x
1377       MO_NatS_to_32U   -> conversionNop WordRep  x
1378       MO_32U_to_NatU   -> conversionNop WordRep  x
1379
1380       MO_NatU_to_NatS -> conversionNop IntRep    x
1381       MO_NatS_to_NatU -> conversionNop WordRep   x
1382       MO_NatP_to_NatU -> conversionNop WordRep   x
1383       MO_NatU_to_NatP -> conversionNop PtrRep    x
1384       MO_NatS_to_NatP -> conversionNop PtrRep    x
1385       MO_NatP_to_NatS -> conversionNop IntRep    x
1386
1387       -- sign-extending widenings
1388       MO_8U_to_32U    -> integerExtend False 24 x
1389       MO_8U_to_NatU   -> integerExtend False 24 x
1390       MO_8S_to_NatS   -> integerExtend True  24 x
1391       MO_16U_to_NatU  -> integerExtend False 16 x
1392       MO_16S_to_NatS  -> integerExtend True  16 x
1393
1394       other_op ->
1395         let fixed_x = if   is_float_op  -- promote to double
1396                       then CmmMachOp MO_F32_to_Dbl [x]
1397                       else x
1398         in
1399         getRegister (StCall (Left fn) CCallConv F64 [fixed_x])
1400     where
1401         integerExtend signed nBits x
1402            = getRegister (
1403                 CmmMachOp (if signed then MO_Nat_Sar else MO_Nat_Shr) 
1404                          [CmmMachOp MO_Nat_Shl [x, StInt nBits], StInt nBits]
1405              )
1406         conversionNop new_rep expr
1407             = getRegister expr          `thenNat` \ e_code ->
1408               return (swizzleRegisterRep e_code new_rep)
1409
1410         (is_float_op, fn)
1411           = case mop of
1412               MO_F32_Exp    -> (True,  FSLIT("exp"))
1413               MO_F32_Log    -> (True,  FSLIT("log"))
1414               MO_F32_Sqrt   -> (True,  FSLIT("sqrt"))
1415
1416               MO_F32_Sin    -> (True,  FSLIT("sin"))
1417               MO_F32_Cos    -> (True,  FSLIT("cos"))
1418               MO_F32_Tan    -> (True,  FSLIT("tan"))
1419
1420               MO_F32_Asin   -> (True,  FSLIT("asin"))
1421               MO_F32_Acos   -> (True,  FSLIT("acos"))
1422               MO_F32_Atan   -> (True,  FSLIT("atan"))
1423
1424               MO_F32_Sinh   -> (True,  FSLIT("sinh"))
1425               MO_F32_Cosh   -> (True,  FSLIT("cosh"))
1426               MO_F32_Tanh   -> (True,  FSLIT("tanh"))
1427
1428               MO_F64_Exp    -> (False, FSLIT("exp"))
1429               MO_F64_Log    -> (False, FSLIT("log"))
1430               MO_F64_Sqrt   -> (False, FSLIT("sqrt"))
1431
1432               MO_F64_Sin    -> (False, FSLIT("sin"))
1433               MO_F64_Cos    -> (False, FSLIT("cos"))
1434               MO_F64_Tan    -> (False, FSLIT("tan"))
1435
1436               MO_F64_Asin   -> (False, FSLIT("asin"))
1437               MO_F64_Acos   -> (False, FSLIT("acos"))
1438               MO_F64_Atan   -> (False, FSLIT("atan"))
1439
1440               MO_F64_Sinh   -> (False, FSLIT("sinh"))
1441               MO_F64_Cosh   -> (False, FSLIT("cosh"))
1442               MO_F64_Tanh   -> (False, FSLIT("tanh"))
1443
1444               other -> pprPanic "getRegister(sparc) - binary CmmMachOp (2)" 
1445                                 (pprMachOp mop)
1446
1447
1448 getRegister (CmmMachOp mop [x, y]) -- dyadic PrimOps
1449   = case mop of
1450       MO_32U_Gt  -> condIntReg GTT x y
1451       MO_32U_Ge  -> condIntReg GE x y
1452       MO_32U_Eq  -> condIntReg EQQ x y
1453       MO_32U_Ne  -> condIntReg NE x y
1454       MO_32U_Lt  -> condIntReg LTT x y
1455       MO_32U_Le  -> condIntReg LE x y
1456
1457       MO_Nat_Eq   -> condIntReg EQQ x y
1458       MO_Nat_Ne   -> condIntReg NE x y
1459
1460       MO_NatS_Gt  -> condIntReg GTT x y
1461       MO_NatS_Ge  -> condIntReg GE x y
1462       MO_NatS_Lt  -> condIntReg LTT x y
1463       MO_NatS_Le  -> condIntReg LE x y
1464
1465       MO_NatU_Gt  -> condIntReg GU  x y
1466       MO_NatU_Ge  -> condIntReg GEU x y
1467       MO_NatU_Lt  -> condIntReg LU  x y
1468       MO_NatU_Le  -> condIntReg LEU x y
1469
1470       MO_F32_Gt -> condFltReg GTT x y
1471       MO_F32_Ge -> condFltReg GE x y
1472       MO_F32_Eq -> condFltReg EQQ x y
1473       MO_F32_Ne -> condFltReg NE x y
1474       MO_F32_Lt -> condFltReg LTT x y
1475       MO_F32_Le -> condFltReg LE x y
1476
1477       MO_F64_Gt -> condFltReg GTT x y
1478       MO_F64_Ge -> condFltReg GE x y
1479       MO_F64_Eq -> condFltReg EQQ x y
1480       MO_F64_Ne -> condFltReg NE x y
1481       MO_F64_Lt -> condFltReg LTT x y
1482       MO_F64_Le -> condFltReg LE x y
1483
1484       MO_Nat_Add -> trivialCode (ADD False False) x y
1485       MO_Nat_Sub -> trivialCode (SUB False False) x y
1486
1487       MO_NatS_Mul  -> trivialCode (SMUL False) x y
1488       MO_NatU_Mul  -> trivialCode (UMUL False) x y
1489       MO_NatS_MulMayOflo -> imulMayOflo x y
1490
1491       -- ToDo: teach about V8+ SPARC div instructions
1492       MO_NatS_Quot -> idiv FSLIT(".div")  x y
1493       MO_NatS_Rem  -> idiv FSLIT(".rem")  x y
1494       MO_NatU_Quot -> idiv FSLIT(".udiv")  x y
1495       MO_NatU_Rem  -> idiv FSLIT(".urem")  x y
1496
1497       MO_F32_Add   -> trivialFCode F32  FADD x y
1498       MO_F32_Sub   -> trivialFCode F32  FSUB x y
1499       MO_F32_Mul   -> trivialFCode F32  FMUL x y
1500       MO_F32_Div   -> trivialFCode F32  FDIV x y
1501
1502       MO_F64_Add   -> trivialFCode F64 FADD x y
1503       MO_F64_Sub   -> trivialFCode F64 FSUB x y
1504       MO_F64_Mul   -> trivialFCode F64 FMUL x y
1505       MO_F64_Div   -> trivialFCode F64 FDIV x y
1506
1507       MO_Nat_And   -> trivialCode (AND False) x y
1508       MO_Nat_Or    -> trivialCode (OR  False) x y
1509       MO_Nat_Xor   -> trivialCode (XOR False) x y
1510
1511       MO_Nat_Shl   -> trivialCode SLL x y
1512       MO_Nat_Shr   -> trivialCode SRL x y
1513       MO_Nat_Sar   -> trivialCode SRA x y
1514
1515       MO_F32_Pwr  -> getRegister (StCall (Left FSLIT("pow")) CCallConv F64 
1516                                          [promote x, promote y])
1517                        where promote x = CmmMachOp MO_F32_to_Dbl [x]
1518       MO_F64_Pwr -> getRegister (StCall (Left FSLIT("pow")) CCallConv F64 
1519                                         [x, y])
1520
1521       other -> pprPanic "getRegister(sparc) - binary CmmMachOp (1)" (pprMachOp mop)
1522   where
1523     idiv fn x y = getRegister (StCall (Left fn) CCallConv IntRep [x, y])
1524
1525     --------------------
1526     imulMayOflo :: CmmExpr -> CmmExpr -> NatM Register
1527     imulMayOflo a1 a2
1528        = getNewRegNat IntRep            `thenNat` \ t1 ->
1529          getNewRegNat IntRep            `thenNat` \ t2 ->
1530          getNewRegNat IntRep            `thenNat` \ res_lo ->
1531          getNewRegNat IntRep            `thenNat` \ res_hi ->
1532          getRegister a1                 `thenNat` \ reg1 ->
1533          getRegister a2                 `thenNat` \ reg2 ->
1534          let code1 = registerCode reg1 t1
1535              code2 = registerCode reg2 t2
1536              src1  = registerName reg1 t1
1537              src2  = registerName reg2 t2
1538              code dst = code1 `appOL` code2 `appOL`
1539                         toOL [
1540                            SMUL False src1 (RIReg src2) res_lo,
1541                            RDY res_hi,
1542                            SRA res_lo (RIImm (ImmInt 31)) res_lo,
1543                            SUB False False res_lo (RIReg res_hi) dst
1544                         ]
1545          in
1546             return (Any IntRep code)
1547
1548 getRegister (CmmLoad pk mem) = do
1549     Amode src code <- getAmode mem
1550     let
1551         size = primRepToSize pk
1552         code__2 dst = code `snocOL` LD size src dst
1553     --
1554     return (Any pk code__2)
1555
1556 getRegister (StInt i)
1557   | fits13Bits i
1558   = let
1559         src = ImmInt (fromInteger i)
1560         code dst = unitOL (OR False g0 (RIImm src) dst)
1561     in
1562         return (Any IntRep code)
1563
1564 getRegister leaf
1565   | isJust imm
1566   = let
1567         code dst = toOL [
1568             SETHI (HI imm__2) dst,
1569             OR False dst (RIImm (LO imm__2)) dst]
1570     in
1571         return (Any PtrRep code)
1572   | otherwise
1573   = ncgPrimopMoan "getRegister(sparc)" (pprCmmExpr leaf)
1574   where
1575     imm = maybeImm leaf
1576     imm__2 = case imm of Just x -> x
1577
1578 #endif /* sparc_TARGET_ARCH */
1579
1580 #if powerpc_TARGET_ARCH
1581 getRegister (CmmLoad mem pk)
1582   | pk /= I64
1583   = do
1584         Amode addr addr_code <- getAmode mem
1585         let code dst = ASSERT((regClass dst == RcDouble) == isFloatingRep pk)
1586                        addr_code `snocOL` LD pk dst addr
1587         return (Any pk code)
1588
1589 -- catch simple cases of zero- or sign-extended load
1590 getRegister (CmmMachOp (MO_U_Conv I8 I32) [CmmLoad mem _]) = do
1591     Amode addr addr_code <- getAmode mem
1592     return (Any I32 (\dst -> addr_code `snocOL` LD I8 dst addr))
1593
1594 -- Note: there is no Load Byte Arithmetic instruction, so no signed case here
1595
1596 getRegister (CmmMachOp (MO_U_Conv I16 I32) [CmmLoad mem _]) = do
1597     Amode addr addr_code <- getAmode mem
1598     return (Any I32 (\dst -> addr_code `snocOL` LD I16 dst addr))
1599
1600 getRegister (CmmMachOp (MO_S_Conv I16 I32) [CmmLoad mem _]) = do
1601     Amode addr addr_code <- getAmode mem
1602     return (Any I32 (\dst -> addr_code `snocOL` LA I16 dst addr))
1603
1604 getRegister (CmmMachOp mop [x]) -- unary MachOps
1605   = case mop of
1606       MO_Not rep   -> trivialUCode rep NOT x
1607
1608       MO_S_Conv F64 F32 -> trivialUCode F32 FRSP x
1609       MO_S_Conv F32 F64 -> conversionNop F64 x
1610
1611       MO_S_Conv from to
1612         | from == to         -> conversionNop to x
1613         | isFloatingRep from -> coerceFP2Int from to x
1614         | isFloatingRep to   -> coerceInt2FP from to x
1615
1616         -- narrowing is a nop: we treat the high bits as undefined
1617       MO_S_Conv I32 to -> conversionNop to x
1618       MO_S_Conv I16 I8 -> conversionNop I8 x
1619       MO_S_Conv I8 to -> trivialUCode to (EXTS I8) x
1620       MO_S_Conv I16 to -> trivialUCode to (EXTS I16) x
1621
1622       MO_U_Conv from to
1623         | from == to -> conversionNop to x
1624         -- narrowing is a nop: we treat the high bits as undefined
1625       MO_U_Conv I32 to -> conversionNop to x
1626       MO_U_Conv I16 I8 -> conversionNop I8 x
1627       MO_U_Conv I8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 I32))
1628       MO_U_Conv I16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 I32)) 
1629
1630       MO_S_Neg F32      -> trivialUCode F32 FNEG x
1631       MO_S_Neg F64      -> trivialUCode F64 FNEG x
1632       MO_S_Neg rep      -> trivialUCode rep NEG x
1633       
1634     where
1635         conversionNop new_rep expr
1636             = do e_code <- getRegister expr
1637                  return (swizzleRegisterRep e_code new_rep)
1638
1639 getRegister (CmmMachOp mop [x, y]) -- dyadic PrimOps
1640   = case mop of
1641       MO_Eq F32 -> condFltReg EQQ x y
1642       MO_Ne F32 -> condFltReg NE  x y
1643
1644       MO_S_Gt F32 -> condFltReg GTT x y
1645       MO_S_Ge F32 -> condFltReg GE  x y
1646       MO_S_Lt F32 -> condFltReg LTT x y
1647       MO_S_Le F32 -> condFltReg LE  x y
1648
1649       MO_Eq F64 -> condFltReg EQQ x y
1650       MO_Ne F64 -> condFltReg NE  x y
1651
1652       MO_S_Gt F64 -> condFltReg GTT x y
1653       MO_S_Ge F64 -> condFltReg GE  x y
1654       MO_S_Lt F64 -> condFltReg LTT x y
1655       MO_S_Le F64 -> condFltReg LE  x y
1656
1657       MO_Eq rep -> condIntReg EQQ  (extendUExpr rep x) (extendUExpr rep y)
1658       MO_Ne rep -> condIntReg NE   (extendUExpr rep x) (extendUExpr rep y)
1659
1660       MO_S_Gt rep -> condIntReg GTT  (extendSExpr rep x) (extendSExpr rep y)
1661       MO_S_Ge rep -> condIntReg GE   (extendSExpr rep x) (extendSExpr rep y)
1662       MO_S_Lt rep -> condIntReg LTT  (extendSExpr rep x) (extendSExpr rep y)
1663       MO_S_Le rep -> condIntReg LE   (extendSExpr rep x) (extendSExpr rep y)
1664
1665       MO_U_Gt rep -> condIntReg GU   (extendUExpr rep x) (extendUExpr rep y)
1666       MO_U_Ge rep -> condIntReg GEU  (extendUExpr rep x) (extendUExpr rep y)
1667       MO_U_Lt rep -> condIntReg LU   (extendUExpr rep x) (extendUExpr rep y)
1668       MO_U_Le rep -> condIntReg LEU  (extendUExpr rep x) (extendUExpr rep y)
1669
1670       MO_Add F32   -> trivialCodeNoImm F32 (FADD F32) x y
1671       MO_Sub F32   -> trivialCodeNoImm F32 (FSUB F32) x y
1672       MO_Mul F32   -> trivialCodeNoImm F32 (FMUL F32) x y
1673       MO_S_Quot F32   -> trivialCodeNoImm F32 (FDIV F32) x y
1674       
1675       MO_Add F64   -> trivialCodeNoImm F64 (FADD F64) x y
1676       MO_Sub F64   -> trivialCodeNoImm F64 (FSUB F64) x y
1677       MO_Mul F64   -> trivialCodeNoImm F64 (FMUL F64) x y
1678       MO_S_Quot F64   -> trivialCodeNoImm F64 (FDIV F64) x y
1679
1680          -- optimize addition with 32-bit immediate
1681          -- (needed for PIC)
1682       MO_Add I32 ->
1683         case y of
1684           CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate I32 True (-imm)
1685             -> trivialCode I32 True ADD x (CmmLit $ CmmInt imm immrep)
1686           CmmLit lit
1687             -> do
1688                 (src, srcCode) <- getSomeReg x
1689                 let imm = litToImm lit
1690                     code dst = srcCode `appOL` toOL [
1691                                     ADDIS dst src (HA imm),
1692                                     ADD dst dst (RIImm (LO imm))
1693                                 ]
1694                 return (Any I32 code)
1695           _ -> trivialCode I32 True ADD x y
1696
1697       MO_Add rep -> trivialCode rep True ADD x y
1698       MO_Sub rep ->
1699         case y of    -- subfi ('substract from' with immediate) doesn't exist
1700           CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm)
1701             -> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep)
1702           _ -> trivialCodeNoImm rep SUBF y x
1703
1704       MO_Mul rep -> trivialCode rep True MULLW x y
1705
1706       MO_S_MulMayOflo I32 -> trivialCodeNoImm I32 MULLW_MayOflo x y
1707       
1708       MO_S_MulMayOflo rep -> panic "S_MulMayOflo (rep /= I32): not implemented"
1709       MO_U_MulMayOflo rep -> panic "U_MulMayOflo: not implemented"
1710
1711       MO_S_Quot rep -> trivialCodeNoImm rep DIVW (extendSExpr rep x) (extendSExpr rep y)
1712       MO_U_Quot rep -> trivialCodeNoImm rep DIVWU (extendUExpr rep x) (extendUExpr rep y)
1713       
1714       MO_S_Rem rep -> remainderCode rep DIVW (extendSExpr rep x) (extendSExpr rep y)
1715       MO_U_Rem rep -> remainderCode rep DIVWU (extendUExpr rep x) (extendUExpr rep y)
1716       
1717       MO_And rep   -> trivialCode rep False AND x y
1718       MO_Or rep    -> trivialCode rep False OR x y
1719       MO_Xor rep   -> trivialCode rep False XOR x y
1720
1721       MO_Shl rep   -> trivialCode rep False SLW x y
1722       MO_S_Shr rep -> trivialCode rep False SRAW (extendSExpr rep x) y
1723       MO_U_Shr rep -> trivialCode rep False SRW (extendUExpr rep x) y
1724
1725 getRegister (CmmLit (CmmInt i rep))
1726   | Just imm <- makeImmediate rep True i
1727   = let
1728         code dst = unitOL (LI dst imm)
1729     in
1730         return (Any rep code)
1731
1732 getRegister (CmmLit (CmmFloat f frep)) = do
1733     lbl <- getNewLabelNat
1734     dynRef <- cmmMakeDynamicReference addImportNat False lbl
1735     Amode addr addr_code <- getAmode dynRef
1736     let code dst = 
1737             LDATA ReadOnlyData  [CmmDataLabel lbl,
1738                                  CmmStaticLit (CmmFloat f frep)]
1739             `consOL` (addr_code `snocOL` LD frep dst addr)
1740     return (Any frep code)
1741
1742 getRegister (CmmLit lit)
1743   = let rep = cmmLitRep lit
1744         imm = litToImm lit
1745         code dst = toOL [
1746               LIS dst (HI imm),
1747               OR dst dst (RIImm (LO imm))
1748           ]
1749     in return (Any rep code)
1750
1751 getRegister other = pprPanic "getRegister(ppc)" (pprExpr other)
1752     
1753     -- extend?Rep: wrap integer expression of type rep
1754     -- in a conversion to I32
1755 extendSExpr I32 x = x
1756 extendSExpr rep x = CmmMachOp (MO_S_Conv rep I32) [x]
1757 extendUExpr I32 x = x
1758 extendUExpr rep x = CmmMachOp (MO_U_Conv rep I32) [x]
1759
1760 #endif /* powerpc_TARGET_ARCH */
1761
1762
1763 -- -----------------------------------------------------------------------------
1764 --  The 'Amode' type: Memory addressing modes passed up the tree.
1765
1766 data Amode = Amode AddrMode InstrBlock
1767
1768 {-
1769 Now, given a tree (the argument to an CmmLoad) that references memory,
1770 produce a suitable addressing mode.
1771
1772 A Rule of the Game (tm) for Amodes: use of the addr bit must
1773 immediately follow use of the code part, since the code part puts
1774 values in registers which the addr then refers to.  So you can't put
1775 anything in between, lest it overwrite some of those registers.  If
1776 you need to do some other computation between the code part and use of
1777 the addr bit, first store the effective address from the amode in a
1778 temporary, then do the other computation, and then use the temporary:
1779
1780     code
1781     LEA amode, tmp
1782     ... other computation ...
1783     ... (tmp) ...
1784 -}
1785
1786 getAmode :: CmmExpr -> NatM Amode
1787 getAmode tree@(CmmRegOff _ _) = getAmode (mangleIndexTree tree)
1788
1789 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1790
1791 #if alpha_TARGET_ARCH
1792
1793 getAmode (StPrim IntSubOp [x, StInt i])
1794   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1795     getRegister x               `thenNat` \ register ->
1796     let
1797         code = registerCode register tmp
1798         reg  = registerName register tmp
1799         off  = ImmInt (-(fromInteger i))
1800     in
1801     return (Amode (AddrRegImm reg off) code)
1802
1803 getAmode (StPrim IntAddOp [x, StInt i])
1804   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1805     getRegister x               `thenNat` \ register ->
1806     let
1807         code = registerCode register tmp
1808         reg  = registerName register tmp
1809         off  = ImmInt (fromInteger i)
1810     in
1811     return (Amode (AddrRegImm reg off) code)
1812
1813 getAmode leaf
1814   | isJust imm
1815   = return (Amode (AddrImm imm__2) id)
1816   where
1817     imm = maybeImm leaf
1818     imm__2 = case imm of Just x -> x
1819
1820 getAmode other
1821   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1822     getRegister other           `thenNat` \ register ->
1823     let
1824         code = registerCode register tmp
1825         reg  = registerName register tmp
1826     in
1827     return (Amode (AddrReg reg) code)
1828
1829 #endif /* alpha_TARGET_ARCH */
1830
1831 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1832
1833 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
1834
1835 -- This is all just ridiculous, since it carefully undoes 
1836 -- what mangleIndexTree has just done.
1837 getAmode (CmmMachOp (MO_Sub rep) [x, CmmLit lit@(CmmInt i _)])
1838   | not (is64BitLit lit)
1839   -- ASSERT(rep == I32)???
1840   = do (x_reg, x_code) <- getSomeReg x
1841        let off = ImmInt (-(fromInteger i))
1842        return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
1843   
1844 getAmode (CmmMachOp (MO_Add rep) [x, CmmLit lit@(CmmInt i _)])
1845   | not (is64BitLit lit)
1846   -- ASSERT(rep == I32)???
1847   = do (x_reg, x_code) <- getSomeReg x
1848        let off = ImmInt (fromInteger i)
1849        return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
1850
1851 -- Turn (lit1 << n  + lit2) into  (lit2 + lit1 << n) so it will be 
1852 -- recognised by the next rule.
1853 getAmode (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
1854                                   b@(CmmLit _)])
1855   = getAmode (CmmMachOp (MO_Add rep) [b,a])
1856
1857 getAmode (CmmMachOp (MO_Add rep) [x, CmmMachOp (MO_Shl _) 
1858                                         [y, CmmLit (CmmInt shift _)]])
1859   | shift == 0 || shift == 1 || shift == 2 || shift == 3
1860   = do (x_reg, x_code) <- getNonClobberedReg x
1861         -- x must be in a temp, because it has to stay live over y_code
1862         -- we could compre x_reg and y_reg and do something better here...
1863        (y_reg, y_code) <- getSomeReg y
1864        let
1865            code = x_code `appOL` y_code
1866            base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8
1867        return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt 0))
1868                code)
1869
1870 getAmode (CmmLit lit) | not (is64BitLit lit)
1871   = return (Amode (ImmAddr (litToImm lit) 0) nilOL)
1872
1873 getAmode expr = do
1874   (reg,code) <- getSomeReg expr
1875   return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)
1876
1877 #endif /* i386_TARGET_ARCH || x86_64_TARGET_ARCH */
1878
1879 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1880
1881 #if sparc_TARGET_ARCH
1882
1883 getAmode (CmmMachOp MO_Nat_Sub [x, StInt i])
1884   | fits13Bits (-i)
1885   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1886     getRegister x               `thenNat` \ register ->
1887     let
1888         code = registerCode register tmp
1889         reg  = registerName register tmp
1890         off  = ImmInt (-(fromInteger i))
1891     in
1892     return (Amode (AddrRegImm reg off) code)
1893
1894
1895 getAmode (CmmMachOp MO_Nat_Add [x, StInt i])
1896   | fits13Bits i
1897   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1898     getRegister x               `thenNat` \ register ->
1899     let
1900         code = registerCode register tmp
1901         reg  = registerName register tmp
1902         off  = ImmInt (fromInteger i)
1903     in
1904     return (Amode (AddrRegImm reg off) code)
1905
1906 getAmode (CmmMachOp MO_Nat_Add [x, y])
1907   = getNewRegNat PtrRep         `thenNat` \ tmp1 ->
1908     getNewRegNat IntRep         `thenNat` \ tmp2 ->
1909     getRegister x               `thenNat` \ register1 ->
1910     getRegister y               `thenNat` \ register2 ->
1911     let
1912         code1 = registerCode register1 tmp1
1913         reg1  = registerName register1 tmp1
1914         code2 = registerCode register2 tmp2
1915         reg2  = registerName register2 tmp2
1916         code__2 = code1 `appOL` code2
1917     in
1918     return (Amode (AddrRegReg reg1 reg2) code__2)
1919
1920 getAmode leaf
1921   | isJust imm
1922   = getNewRegNat PtrRep             `thenNat` \ tmp ->
1923     let
1924         code = unitOL (SETHI (HI imm__2) tmp)
1925     in
1926     return (Amode (AddrRegImm tmp (LO imm__2)) code)
1927   where
1928     imm    = maybeImm leaf
1929     imm__2 = case imm of Just x -> x
1930
1931 getAmode other
1932   = getNewRegNat PtrRep         `thenNat` \ tmp ->
1933     getRegister other           `thenNat` \ register ->
1934     let
1935         code = registerCode register tmp
1936         reg  = registerName register tmp
1937         off  = ImmInt 0
1938     in
1939     return (Amode (AddrRegImm reg off) code)
1940
1941 #endif /* sparc_TARGET_ARCH */
1942
1943 #ifdef powerpc_TARGET_ARCH
1944 getAmode (CmmMachOp (MO_Sub I32) [x, CmmLit (CmmInt i _)])
1945   | Just off <- makeImmediate I32 True (-i)
1946   = do
1947         (reg, code) <- getSomeReg x
1948         return (Amode (AddrRegImm reg off) code)
1949
1950
1951 getAmode (CmmMachOp (MO_Add I32) [x, CmmLit (CmmInt i _)])
1952   | Just off <- makeImmediate I32 True i
1953   = do
1954         (reg, code) <- getSomeReg x
1955         return (Amode (AddrRegImm reg off) code)
1956
1957    -- optimize addition with 32-bit immediate
1958    -- (needed for PIC)
1959 getAmode (CmmMachOp (MO_Add I32) [x, CmmLit lit])
1960   = do
1961         tmp <- getNewRegNat I32
1962         (src, srcCode) <- getSomeReg x
1963         let imm = litToImm lit
1964             code = srcCode `snocOL` ADDIS tmp src (HA imm)
1965         return (Amode (AddrRegImm tmp (LO imm)) code)
1966
1967 getAmode (CmmLit lit)
1968   = do
1969         tmp <- getNewRegNat I32
1970         let imm = litToImm lit
1971             code = unitOL (LIS tmp (HA imm))
1972         return (Amode (AddrRegImm tmp (LO imm)) code)
1973     
1974 getAmode (CmmMachOp (MO_Add I32) [x, y])
1975   = do
1976         (regX, codeX) <- getSomeReg x
1977         (regY, codeY) <- getSomeReg y
1978         return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY))
1979     
1980 getAmode other
1981   = do
1982         (reg, code) <- getSomeReg other
1983         let
1984             off  = ImmInt 0
1985         return (Amode (AddrRegImm reg off) code)
1986 #endif /* powerpc_TARGET_ARCH */
1987
1988 -- -----------------------------------------------------------------------------
1989 -- getOperand: sometimes any operand will do.
1990
1991 -- getNonClobberedOperand: the value of the operand will remain valid across
1992 -- the computation of an arbitrary expression, unless the expression
1993 -- is computed directly into a register which the operand refers to
1994 -- (see trivialCode where this function is used for an example).
1995
1996 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
1997
1998 getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
1999 getNonClobberedOperand (CmmLit lit)
2000   | not (is64BitLit lit) && not (isFloatingRep (cmmLitRep lit)) =
2001     return (OpImm (litToImm lit), nilOL)
2002 getNonClobberedOperand (CmmLoad mem pk) 
2003   | IF_ARCH_i386(not (isFloatingRep pk) && pk /= I64, True) = do
2004     Amode src mem_code <- getAmode mem
2005     (src',save_code) <- 
2006         if (amodeCouldBeClobbered src) 
2007                 then do
2008                    tmp <- getNewRegNat wordRep
2009                    return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
2010                            unitOL (LEA I32 (OpAddr src) (OpReg tmp)))
2011                 else
2012                    return (src, nilOL)
2013     return (OpAddr src', save_code `appOL` mem_code)
2014 getNonClobberedOperand e = do
2015     (reg, code) <- getNonClobberedReg e
2016     return (OpReg reg, code)
2017
2018 amodeCouldBeClobbered :: AddrMode -> Bool
2019 amodeCouldBeClobbered amode = any regClobbered (addrModeRegs amode)
2020
2021 regClobbered (RealReg rr) = isFastTrue (freeReg rr)
2022 regClobbered _ = False
2023
2024 -- getOperand: the operand is not required to remain valid across the
2025 -- computation of an arbitrary expression.
2026 getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
2027 getOperand (CmmLit lit)
2028   | not (is64BitLit lit) && not (isFloatingRep (cmmLitRep lit)) =
2029     return (OpImm (litToImm lit), nilOL)
2030 getOperand (CmmLoad mem pk)
2031   | IF_ARCH_i386(not (isFloatingRep pk) && pk /= I64, True) = do
2032     Amode src mem_code <- getAmode mem
2033     return (OpAddr src, mem_code)
2034 getOperand e = do
2035     (reg, code) <- getNonClobberedReg e
2036     return (OpReg reg, code)
2037
2038 isOperand :: CmmExpr -> Bool
2039 isOperand (CmmLoad _ _) = True
2040 isOperand (CmmLit lit)  = not (is64BitLit lit) && 
2041                           not (isFloatingRep (cmmLitRep lit))
2042 isOperand _             = False
2043
2044 getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
2045 getRegOrMem (CmmLoad mem pk)
2046   | IF_ARCH_i386(not (isFloatingRep pk) && pk /= I64, True) = do
2047     Amode src mem_code <- getAmode mem
2048     return (OpAddr src, mem_code)
2049 getRegOrMem e = do
2050     (reg, code) <- getNonClobberedReg e
2051     return (OpReg reg, code)
2052
2053 #if x86_64_TARGET_ARCH
2054 is64BitLit (CmmInt i I64) = i > 0x7fffffff || i < -0x80000000
2055    -- assume that labels are in the range 0-2^31-1: this assumes the
2056    -- small memory model (see gcc docs, -mcmodel=small).
2057 #endif
2058 is64BitLit x = False
2059 #endif
2060
2061 -- -----------------------------------------------------------------------------
2062 --  The 'CondCode' type:  Condition codes passed up the tree.
2063
2064 data CondCode = CondCode Bool Cond InstrBlock
2065
2066 -- Set up a condition code for a conditional branch.
2067
2068 getCondCode :: CmmExpr -> NatM CondCode
2069
2070 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2071
2072 #if alpha_TARGET_ARCH
2073 getCondCode = panic "MachCode.getCondCode: not on Alphas"
2074 #endif /* alpha_TARGET_ARCH */
2075
2076 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2077
2078 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH || sparc_TARGET_ARCH
2079 -- yes, they really do seem to want exactly the same!
2080
2081 getCondCode (CmmMachOp mop [x, y])
2082   = ASSERT (cmmExprRep x /= I8) -- tmp, not set up to handle 8-bit comparisons
2083     case mop of
2084       MO_Eq F32 -> condFltCode EQQ x y
2085       MO_Ne F32 -> condFltCode NE  x y
2086
2087       MO_S_Gt F32 -> condFltCode GTT x y
2088       MO_S_Ge F32 -> condFltCode GE  x y
2089       MO_S_Lt F32 -> condFltCode LTT x y
2090       MO_S_Le F32 -> condFltCode LE  x y
2091
2092       MO_Eq F64 -> condFltCode EQQ x y
2093       MO_Ne F64 -> condFltCode NE  x y
2094
2095       MO_S_Gt F64 -> condFltCode GTT x y
2096       MO_S_Ge F64 -> condFltCode GE  x y
2097       MO_S_Lt F64 -> condFltCode LTT x y
2098       MO_S_Le F64 -> condFltCode LE  x y
2099
2100       MO_Eq rep -> condIntCode EQQ  x y
2101       MO_Ne rep -> condIntCode NE   x y
2102
2103       MO_S_Gt rep -> condIntCode GTT  x y
2104       MO_S_Ge rep -> condIntCode GE   x y
2105       MO_S_Lt rep -> condIntCode LTT  x y
2106       MO_S_Le rep -> condIntCode LE   x y
2107
2108       MO_U_Gt rep -> condIntCode GU   x y
2109       MO_U_Ge rep -> condIntCode GEU  x y
2110       MO_U_Lt rep -> condIntCode LU   x y
2111       MO_U_Le rep -> condIntCode LEU  x y
2112
2113       other -> pprPanic "getCondCode(x86,sparc)" (pprMachOp mop)
2114
2115 getCondCode other =  pprPanic "getCondCode(2)(x86,sparc)" (ppr other)
2116
2117 #elif powerpc_TARGET_ARCH
2118
2119 -- almost the same as everywhere else - but we need to
2120 -- extend small integers to 32 bit first
2121
2122 getCondCode (CmmMachOp mop [x, y])
2123   = case mop of
2124       MO_Eq F32 -> condFltCode EQQ x y
2125       MO_Ne F32 -> condFltCode NE  x y
2126
2127       MO_S_Gt F32 -> condFltCode GTT x y
2128       MO_S_Ge F32 -> condFltCode GE  x y
2129       MO_S_Lt F32 -> condFltCode LTT x y
2130       MO_S_Le F32 -> condFltCode LE  x y
2131
2132       MO_Eq F64 -> condFltCode EQQ x y
2133       MO_Ne F64 -> condFltCode NE  x y
2134
2135       MO_S_Gt F64 -> condFltCode GTT x y
2136       MO_S_Ge F64 -> condFltCode GE  x y
2137       MO_S_Lt F64 -> condFltCode LTT x y
2138       MO_S_Le F64 -> condFltCode LE  x y
2139
2140       MO_Eq rep -> condIntCode EQQ  (extendUExpr rep x) (extendUExpr rep y)
2141       MO_Ne rep -> condIntCode NE   (extendUExpr rep x) (extendUExpr rep y)
2142
2143       MO_S_Gt rep -> condIntCode GTT  (extendSExpr rep x) (extendSExpr rep y)
2144       MO_S_Ge rep -> condIntCode GE   (extendSExpr rep x) (extendSExpr rep y)
2145       MO_S_Lt rep -> condIntCode LTT  (extendSExpr rep x) (extendSExpr rep y)
2146       MO_S_Le rep -> condIntCode LE   (extendSExpr rep x) (extendSExpr rep y)
2147
2148       MO_U_Gt rep -> condIntCode GU   (extendUExpr rep x) (extendUExpr rep y)
2149       MO_U_Ge rep -> condIntCode GEU  (extendUExpr rep x) (extendUExpr rep y)
2150       MO_U_Lt rep -> condIntCode LU   (extendUExpr rep x) (extendUExpr rep y)
2151       MO_U_Le rep -> condIntCode LEU  (extendUExpr rep x) (extendUExpr rep y)
2152
2153       other -> pprPanic "getCondCode(powerpc)" (pprMachOp mop)
2154
2155 getCondCode other =  panic "getCondCode(2)(powerpc)"
2156
2157
2158 #endif
2159
2160
2161 -- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
2162 -- passed back up the tree.
2163
2164 condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
2165
2166 #if alpha_TARGET_ARCH
2167 condIntCode = panic "MachCode.condIntCode: not on Alphas"
2168 condFltCode = panic "MachCode.condFltCode: not on Alphas"
2169 #endif /* alpha_TARGET_ARCH */
2170
2171 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2172 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2173
2174 -- memory vs immediate
2175 condIntCode cond (CmmLoad x pk) (CmmLit lit) | not (is64BitLit lit) = do
2176     Amode x_addr x_code <- getAmode x
2177     let
2178         imm  = litToImm lit
2179         code = x_code `snocOL`
2180                   CMP pk (OpImm imm) (OpAddr x_addr)
2181     --
2182     return (CondCode False cond code)
2183
2184 -- anything vs zero
2185 condIntCode cond x (CmmLit (CmmInt 0 pk)) = do
2186     (x_reg, x_code) <- getSomeReg x
2187     let
2188         code = x_code `snocOL`
2189                   TEST pk (OpReg x_reg) (OpReg x_reg)
2190     --
2191     return (CondCode False cond code)
2192
2193 -- anything vs operand
2194 condIntCode cond x y | isOperand y = do
2195     (x_reg, x_code) <- getNonClobberedReg x
2196     (y_op,  y_code) <- getOperand y    
2197     let
2198         code = x_code `appOL` y_code `snocOL`
2199                   CMP (cmmExprRep x) y_op (OpReg x_reg)
2200     -- in
2201     return (CondCode False cond code)
2202
2203 -- anything vs anything
2204 condIntCode cond x y = do
2205   (y_reg, y_code) <- getNonClobberedReg y
2206   (x_op, x_code) <- getRegOrMem x
2207   let
2208         code = y_code `appOL`
2209                x_code `snocOL`
2210                   CMP (cmmExprRep x) (OpReg y_reg) x_op
2211   -- in
2212   return (CondCode False cond code)
2213 #endif
2214
2215 #if i386_TARGET_ARCH
2216 condFltCode cond x y 
2217   = ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do
2218   (x_reg, x_code) <- getNonClobberedReg x
2219   (y_reg, y_code) <- getSomeReg y
2220   let
2221         code = x_code `appOL` y_code `snocOL`
2222                 GCMP cond x_reg y_reg
2223   -- The GCMP insn does the test and sets the zero flag if comparable
2224   -- and true.  Hence we always supply EQQ as the condition to test.
2225   return (CondCode True EQQ code)
2226 #endif /* i386_TARGET_ARCH */
2227
2228 #if x86_64_TARGET_ARCH
2229 -- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
2230 -- an operand, but the right must be a reg.  We can probably do better
2231 -- than this general case...
2232 condFltCode cond x y = do
2233   (x_reg, x_code) <- getNonClobberedReg x
2234   (y_op, y_code) <- getOperand y
2235   let
2236         code = x_code `appOL`
2237                y_code `snocOL`
2238                   CMP (cmmExprRep x) y_op (OpReg x_reg)
2239         -- NB(1): we need to use the unsigned comparison operators on the
2240         -- result of this comparison.
2241   -- in
2242   return (CondCode True (condToUnsigned cond) code)
2243 #endif
2244
2245 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2246
2247 #if sparc_TARGET_ARCH
2248
2249 condIntCode cond x (StInt y)
2250   | fits13Bits y
2251   = getRegister x               `thenNat` \ register ->
2252     getNewRegNat IntRep         `thenNat` \ tmp ->
2253     let
2254         code = registerCode register tmp
2255         src1 = registerName register tmp
2256         src2 = ImmInt (fromInteger y)
2257         code__2 = code `snocOL` SUB False True src1 (RIImm src2) g0
2258     in
2259     return (CondCode False cond code__2)
2260
2261 condIntCode cond x y
2262   = getRegister x               `thenNat` \ register1 ->
2263     getRegister y               `thenNat` \ register2 ->
2264     getNewRegNat IntRep         `thenNat` \ tmp1 ->
2265     getNewRegNat IntRep         `thenNat` \ tmp2 ->
2266     let
2267         code1 = registerCode register1 tmp1
2268         src1  = registerName register1 tmp1
2269         code2 = registerCode register2 tmp2
2270         src2  = registerName register2 tmp2
2271         code__2 = code1 `appOL` code2 `snocOL`
2272                   SUB False True src1 (RIReg src2) g0
2273     in
2274     return (CondCode False cond code__2)
2275
2276 -----------
2277 condFltCode cond x y
2278   = getRegister x               `thenNat` \ register1 ->
2279     getRegister y               `thenNat` \ register2 ->
2280     getNewRegNat (registerRep register1)
2281                                 `thenNat` \ tmp1 ->
2282     getNewRegNat (registerRep register2)
2283                                 `thenNat` \ tmp2 ->
2284     getNewRegNat F64    `thenNat` \ tmp ->
2285     let
2286         promote x = FxTOy F DF x tmp
2287
2288         pk1   = registerRep register1
2289         code1 = registerCode register1 tmp1
2290         src1  = registerName register1 tmp1
2291
2292         pk2   = registerRep register2
2293         code2 = registerCode register2 tmp2
2294         src2  = registerName register2 tmp2
2295
2296         code__2 =
2297                 if pk1 == pk2 then
2298                     code1 `appOL` code2 `snocOL`
2299                     FCMP True (primRepToSize pk1) src1 src2
2300                 else if pk1 == F32 then
2301                     code1 `snocOL` promote src1 `appOL` code2 `snocOL`
2302                     FCMP True DF tmp src2
2303                 else
2304                     code1 `appOL` code2 `snocOL` promote src2 `snocOL`
2305                     FCMP True DF src1 tmp
2306     in
2307     return (CondCode True cond code__2)
2308
2309 #endif /* sparc_TARGET_ARCH */
2310
2311 #if powerpc_TARGET_ARCH
2312 --  ###FIXME: I16 and I8!
2313 condIntCode cond x (CmmLit (CmmInt y rep))
2314   | Just src2 <- makeImmediate rep (not $ condUnsigned cond) y
2315   = do
2316         (src1, code) <- getSomeReg x
2317         let
2318             code' = code `snocOL` 
2319                 (if condUnsigned cond then CMPL else CMP) I32 src1 (RIImm src2)
2320         return (CondCode False cond code')
2321
2322 condIntCode cond x y = do
2323     (src1, code1) <- getSomeReg x
2324     (src2, code2) <- getSomeReg y
2325     let
2326         code' = code1 `appOL` code2 `snocOL`
2327                   (if condUnsigned cond then CMPL else CMP) I32 src1 (RIReg src2)
2328     return (CondCode False cond code')
2329
2330 condFltCode cond x y = do
2331     (src1, code1) <- getSomeReg x
2332     (src2, code2) <- getSomeReg y
2333     let
2334         code'  = code1 `appOL` code2 `snocOL` FCMP src1 src2
2335         code'' = case cond of -- twiddle CR to handle unordered case
2336                     GE -> code' `snocOL` CRNOR ltbit eqbit gtbit
2337                     LE -> code' `snocOL` CRNOR gtbit eqbit ltbit
2338                     _ -> code'
2339                  where
2340                     ltbit = 0 ; eqbit = 2 ; gtbit = 1
2341     return (CondCode True cond code'')
2342
2343 #endif /* powerpc_TARGET_ARCH */
2344
2345 -- -----------------------------------------------------------------------------
2346 -- Generating assignments
2347
2348 -- Assignments are really at the heart of the whole code generation
2349 -- business.  Almost all top-level nodes of any real importance are
2350 -- assignments, which correspond to loads, stores, or register
2351 -- transfers.  If we're really lucky, some of the register transfers
2352 -- will go away, because we can use the destination register to
2353 -- complete the code generation for the right hand side.  This only
2354 -- fails when the right hand side is forced into a fixed register
2355 -- (e.g. the result of a call).
2356
2357 assignMem_IntCode :: MachRep -> CmmExpr -> CmmExpr -> NatM InstrBlock
2358 assignReg_IntCode :: MachRep -> CmmReg  -> CmmExpr -> NatM InstrBlock
2359
2360 assignMem_FltCode :: MachRep -> CmmExpr -> CmmExpr -> NatM InstrBlock
2361 assignReg_FltCode :: MachRep -> CmmReg  -> CmmExpr -> NatM InstrBlock
2362
2363 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2364
2365 #if alpha_TARGET_ARCH
2366
2367 assignIntCode pk (CmmLoad dst _) src
2368   = getNewRegNat IntRep             `thenNat` \ tmp ->
2369     getAmode dst                    `thenNat` \ amode ->
2370     getRegister src                 `thenNat` \ register ->
2371     let
2372         code1   = amodeCode amode []
2373         dst__2  = amodeAddr amode
2374         code2   = registerCode register tmp []
2375         src__2  = registerName register tmp
2376         sz      = primRepToSize pk
2377         code__2 = asmSeqThen [code1, code2] . mkSeqInstr (ST sz src__2 dst__2)
2378     in
2379     return code__2
2380
2381 assignIntCode pk dst src
2382   = getRegister dst                         `thenNat` \ register1 ->
2383     getRegister src                         `thenNat` \ register2 ->
2384     let
2385         dst__2  = registerName register1 zeroh
2386         code    = registerCode register2 dst__2
2387         src__2  = registerName register2 dst__2
2388         code__2 = if isFixed register2
2389                   then code . mkSeqInstr (OR src__2 (RIReg src__2) dst__2)
2390                   else code
2391     in
2392     return code__2
2393
2394 #endif /* alpha_TARGET_ARCH */
2395
2396 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2397
2398 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2399
2400 -- integer assignment to memory
2401 assignMem_IntCode pk addr src = do
2402     Amode addr code_addr <- getAmode addr
2403     (code_src, op_src)   <- get_op_RI src
2404     let
2405         code = code_src `appOL`
2406                code_addr `snocOL`
2407                   MOV pk op_src (OpAddr addr)
2408         -- NOTE: op_src is stable, so it will still be valid
2409         -- after code_addr.  This may involve the introduction 
2410         -- of an extra MOV to a temporary register, but we hope
2411         -- the register allocator will get rid of it.
2412     --
2413     return code
2414   where
2415     get_op_RI :: CmmExpr -> NatM (InstrBlock,Operand)   -- code, operator
2416     get_op_RI (CmmLit lit) | not (is64BitLit lit)
2417       = return (nilOL, OpImm (litToImm lit))
2418     get_op_RI op
2419       = do (reg,code) <- getNonClobberedReg op
2420            return (code, OpReg reg)
2421
2422
2423 -- Assign; dst is a reg, rhs is mem
2424 assignReg_IntCode pk reg (CmmLoad src _) = do
2425   load_code <- intLoadCode (MOV pk) src
2426   return (load_code (getRegisterReg reg))
2427
2428 -- dst is a reg, but src could be anything
2429 assignReg_IntCode pk reg src = do
2430   code <- getAnyReg src
2431   return (code (getRegisterReg reg))
2432
2433 #endif /* i386_TARGET_ARCH */
2434
2435 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2436
2437 #if sparc_TARGET_ARCH
2438
2439 assignMem_IntCode pk addr src
2440   = getNewRegNat IntRep                     `thenNat` \ tmp ->
2441     getAmode addr                           `thenNat` \ amode ->
2442     getRegister src                         `thenNat` \ register ->
2443     let
2444         code1   = amodeCode amode
2445         dst__2  = amodeAddr amode
2446         code2   = registerCode register tmp
2447         src__2  = registerName register tmp
2448         sz      = primRepToSize pk
2449         code__2 = code1 `appOL` code2 `snocOL` ST sz src__2 dst__2
2450     in
2451     return code__2
2452
2453 assignReg_IntCode pk reg src
2454   = getRegister src                         `thenNat` \ register2 ->
2455     getRegisterReg reg                      `thenNat` \ register1 ->
2456     getNewRegNat IntRep                     `thenNat` \ tmp ->
2457     let
2458         dst__2  = registerName register1 tmp
2459         code    = registerCode register2 dst__2
2460         src__2  = registerName register2 dst__2
2461         code__2 = if isFixed register2
2462                   then code `snocOL` OR False g0 (RIReg src__2) dst__2
2463                   else code
2464     in
2465     return code__2
2466
2467 #endif /* sparc_TARGET_ARCH */
2468
2469 #if powerpc_TARGET_ARCH
2470
2471 assignMem_IntCode pk addr src = do
2472     (srcReg, code) <- getSomeReg src
2473     Amode dstAddr addr_code <- getAmode addr
2474     return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr
2475
2476 -- dst is a reg, but src could be anything
2477 assignReg_IntCode pk reg src
2478     = do
2479         r <- getRegister src
2480         return $ case r of
2481             Any _ code         -> code dst
2482             Fixed _ freg fcode -> fcode `snocOL` MR dst freg
2483     where
2484         dst = getRegisterReg reg
2485
2486 #endif /* powerpc_TARGET_ARCH */
2487
2488
2489 -- -----------------------------------------------------------------------------
2490 -- Floating-point assignments
2491
2492 #if alpha_TARGET_ARCH
2493
2494 assignFltCode pk (CmmLoad dst _) src
2495   = getNewRegNat pk                 `thenNat` \ tmp ->
2496     getAmode dst                    `thenNat` \ amode ->
2497     getRegister src                         `thenNat` \ register ->
2498     let
2499         code1   = amodeCode amode []
2500         dst__2  = amodeAddr amode
2501         code2   = registerCode register tmp []
2502         src__2  = registerName register tmp
2503         sz      = primRepToSize pk
2504         code__2 = asmSeqThen [code1, code2] . mkSeqInstr (ST sz src__2 dst__2)
2505     in
2506     return code__2
2507
2508 assignFltCode pk dst src
2509   = getRegister dst                         `thenNat` \ register1 ->
2510     getRegister src                         `thenNat` \ register2 ->
2511     let
2512         dst__2  = registerName register1 zeroh
2513         code    = registerCode register2 dst__2
2514         src__2  = registerName register2 dst__2
2515         code__2 = if isFixed register2
2516                   then code . mkSeqInstr (FMOV src__2 dst__2)
2517                   else code
2518     in
2519     return code__2
2520
2521 #endif /* alpha_TARGET_ARCH */
2522
2523 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2524
2525 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2526
2527 -- Floating point assignment to memory
2528 assignMem_FltCode pk addr src = do
2529   (src_reg, src_code) <- getNonClobberedReg src
2530   Amode addr addr_code <- getAmode addr
2531   let
2532         code = src_code `appOL`
2533                addr_code `snocOL`
2534                 IF_ARCH_i386(GST pk src_reg addr,
2535                              MOV pk (OpReg src_reg) (OpAddr addr))
2536   return code
2537
2538 -- Floating point assignment to a register/temporary
2539 assignReg_FltCode pk reg src = do
2540   src_code <- getAnyReg src
2541   return (src_code (getRegisterReg reg))
2542
2543 #endif /* i386_TARGET_ARCH */
2544
2545 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2546
2547 #if sparc_TARGET_ARCH
2548
2549 -- Floating point assignment to memory
2550 assignMem_FltCode pk addr src
2551   = getNewRegNat pk                 `thenNat` \ tmp1 ->
2552     getAmode addr                   `thenNat` \ amode ->
2553     getRegister src                 `thenNat` \ register ->
2554     let
2555         sz      = primRepToSize pk
2556         dst__2  = amodeAddr amode
2557
2558         code1   = amodeCode amode
2559         code2   = registerCode register tmp1
2560
2561         src__2  = registerName register tmp1
2562         pk__2   = registerRep register
2563         sz__2   = primRepToSize pk__2
2564
2565         code__2 = code1 `appOL` code2 `appOL`
2566             if   pk == pk__2 
2567             then unitOL (ST sz src__2 dst__2)
2568             else toOL [FxTOy sz__2 sz src__2 tmp1, ST sz tmp1 dst__2]
2569     in
2570     return code__2
2571
2572 -- Floating point assignment to a register/temporary
2573 -- Why is this so bizarrely ugly?
2574 assignReg_FltCode pk reg src
2575   = getRegisterReg reg                      `thenNat` \ register1 ->
2576     getRegister src                         `thenNat` \ register2 ->
2577     let 
2578         pk__2   = registerRep register2 
2579         sz__2   = primRepToSize pk__2
2580     in
2581     getNewRegNat pk__2                      `thenNat` \ tmp ->
2582     let
2583         sz      = primRepToSize pk
2584         dst__2  = registerName register1 g0    -- must be Fixed
2585         reg__2  = if pk /= pk__2 then tmp else dst__2
2586         code    = registerCode register2 reg__2
2587         src__2  = registerName register2 reg__2
2588         code__2 = 
2589                 if pk /= pk__2 then
2590                      code `snocOL` FxTOy sz__2 sz src__2 dst__2
2591                 else if isFixed register2 then
2592                      code `snocOL` FMOV sz src__2 dst__2
2593                 else
2594                      code
2595     in
2596     return code__2
2597
2598 #endif /* sparc_TARGET_ARCH */
2599
2600 #if powerpc_TARGET_ARCH
2601
2602 -- Easy, isn't it?
2603 assignMem_FltCode = assignMem_IntCode
2604 assignReg_FltCode = assignReg_IntCode
2605
2606 #endif /* powerpc_TARGET_ARCH */
2607
2608
2609 -- -----------------------------------------------------------------------------
2610 -- Generating an non-local jump
2611
2612 -- (If applicable) Do not fill the delay slots here; you will confuse the
2613 -- register allocator.
2614
2615 genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock
2616
2617 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2618
2619 #if alpha_TARGET_ARCH
2620
2621 genJump (CmmLabel lbl)
2622   | isAsmTemp lbl = returnInstr (BR target)
2623   | otherwise     = returnInstrs [LDA pv (AddrImm target), JMP zeroh (AddrReg pv) 0]
2624   where
2625     target = ImmCLbl lbl
2626
2627 genJump tree
2628   = getRegister tree                `thenNat` \ register ->
2629     getNewRegNat PtrRep             `thenNat` \ tmp ->
2630     let
2631         dst    = registerName register pv
2632         code   = registerCode register pv
2633         target = registerName register pv
2634     in
2635     if isFixed register then
2636         returnSeq code [OR dst (RIReg dst) pv, JMP zeroh (AddrReg pv) 0]
2637     else
2638     return (code . mkSeqInstr (JMP zeroh (AddrReg pv) 0))
2639
2640 #endif /* alpha_TARGET_ARCH */
2641
2642 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2643
2644 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2645
2646 genJump (CmmLoad mem pk) = do
2647   Amode target code <- getAmode mem
2648   return (code `snocOL` JMP (OpAddr target))
2649
2650 genJump (CmmLit lit) = do
2651   return (unitOL (JMP (OpImm (litToImm lit))))
2652
2653 genJump expr = do
2654   (reg,code) <- getSomeReg expr
2655   return (code `snocOL` JMP (OpReg reg))
2656
2657 #endif /* i386_TARGET_ARCH */
2658
2659 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2660
2661 #if sparc_TARGET_ARCH
2662
2663 genJump (CmmLabel lbl)
2664   = return (toOL [CALL (Left target) 0 True, NOP])
2665   where
2666     target = ImmCLbl lbl
2667
2668 genJump tree
2669   = getRegister tree                        `thenNat` \ register ->
2670     getNewRegNat PtrRep             `thenNat` \ tmp ->
2671     let
2672         code   = registerCode register tmp
2673         target = registerName register tmp
2674     in
2675     return (code `snocOL` JMP dsts (AddrRegReg target g0) `snocOL` NOP)
2676
2677 #endif /* sparc_TARGET_ARCH */
2678
2679 #if powerpc_TARGET_ARCH
2680 genJump (CmmLit (CmmLabel lbl))
2681   = return (unitOL $ JMP lbl)
2682
2683 genJump tree
2684   = do
2685         (target,code) <- getSomeReg tree
2686         return (code `snocOL` MTCTR target `snocOL` BCTR [])
2687 #endif /* powerpc_TARGET_ARCH */
2688
2689
2690 -- -----------------------------------------------------------------------------
2691 --  Unconditional branches
2692
2693 genBranch :: BlockId -> NatM InstrBlock
2694
2695 #if alpha_TARGET_ARCH
2696 genBranch id = return (unitOL (BR id))
2697 #endif
2698
2699 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
2700 genBranch id = return (unitOL (JXX ALWAYS id))
2701 #endif
2702
2703 #if sparc_TARGET_ARCH
2704 genBranch id = return (toOL [BI ALWAYS False id, NOP])
2705 #endif
2706
2707 #if powerpc_TARGET_ARCH
2708 genBranch id = return (unitOL (BCC ALWAYS id))
2709 #endif
2710
2711
2712 -- -----------------------------------------------------------------------------
2713 --  Conditional jumps
2714
2715 {-
2716 Conditional jumps are always to local labels, so we can use branch
2717 instructions.  We peek at the arguments to decide what kind of
2718 comparison to do.
2719
2720 ALPHA: For comparisons with 0, we're laughing, because we can just do
2721 the desired conditional branch.
2722
2723 I386: First, we have to ensure that the condition
2724 codes are set according to the supplied comparison operation.
2725
2726 SPARC: First, we have to ensure that the condition codes are set
2727 according to the supplied comparison operation.  We generate slightly
2728 different code for floating point comparisons, because a floating
2729 point operation cannot directly precede a @BF@.  We assume the worst
2730 and fill that slot with a @NOP@.
2731
2732 SPARC: Do not fill the delay slots here; you will confuse the register
2733 allocator.
2734 -}
2735
2736
2737 genCondJump
2738     :: BlockId      -- the branch target
2739     -> CmmExpr      -- the condition on which to branch
2740     -> NatM InstrBlock
2741
2742 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2743
2744 #if alpha_TARGET_ARCH
2745
2746 genCondJump id (StPrim op [x, StInt 0])
2747   = getRegister x                           `thenNat` \ register ->
2748     getNewRegNat (registerRep register)
2749                                     `thenNat` \ tmp ->
2750     let
2751         code   = registerCode register tmp
2752         value  = registerName register tmp
2753         pk     = registerRep register
2754         target = ImmCLbl lbl
2755     in
2756     returnSeq code [BI (cmpOp op) value target]
2757   where
2758     cmpOp CharGtOp = GTT
2759     cmpOp CharGeOp = GE
2760     cmpOp CharEqOp = EQQ
2761     cmpOp CharNeOp = NE
2762     cmpOp CharLtOp = LTT
2763     cmpOp CharLeOp = LE
2764     cmpOp IntGtOp = GTT
2765     cmpOp IntGeOp = GE
2766     cmpOp IntEqOp = EQQ
2767     cmpOp IntNeOp = NE
2768     cmpOp IntLtOp = LTT
2769     cmpOp IntLeOp = LE
2770     cmpOp WordGtOp = NE
2771     cmpOp WordGeOp = ALWAYS
2772     cmpOp WordEqOp = EQQ
2773     cmpOp WordNeOp = NE
2774     cmpOp WordLtOp = NEVER
2775     cmpOp WordLeOp = EQQ
2776     cmpOp AddrGtOp = NE
2777     cmpOp AddrGeOp = ALWAYS
2778     cmpOp AddrEqOp = EQQ
2779     cmpOp AddrNeOp = NE
2780     cmpOp AddrLtOp = NEVER
2781     cmpOp AddrLeOp = EQQ
2782
2783 genCondJump lbl (StPrim op [x, StDouble 0.0])
2784   = getRegister x                           `thenNat` \ register ->
2785     getNewRegNat (registerRep register)
2786                                     `thenNat` \ tmp ->
2787     let
2788         code   = registerCode register tmp
2789         value  = registerName register tmp
2790         pk     = registerRep register
2791         target = ImmCLbl lbl
2792     in
2793     return (code . mkSeqInstr (BF (cmpOp op) value target))
2794   where
2795     cmpOp FloatGtOp = GTT
2796     cmpOp FloatGeOp = GE
2797     cmpOp FloatEqOp = EQQ
2798     cmpOp FloatNeOp = NE
2799     cmpOp FloatLtOp = LTT
2800     cmpOp FloatLeOp = LE
2801     cmpOp DoubleGtOp = GTT
2802     cmpOp DoubleGeOp = GE
2803     cmpOp DoubleEqOp = EQQ
2804     cmpOp DoubleNeOp = NE
2805     cmpOp DoubleLtOp = LTT
2806     cmpOp DoubleLeOp = LE
2807
2808 genCondJump lbl (StPrim op [x, y])
2809   | fltCmpOp op
2810   = trivialFCode pr instr x y       `thenNat` \ register ->
2811     getNewRegNat F64                `thenNat` \ tmp ->
2812     let
2813         code   = registerCode register tmp
2814         result = registerName register tmp
2815         target = ImmCLbl lbl
2816     in
2817     return (code . mkSeqInstr (BF cond result target))
2818   where
2819     pr = panic "trivialU?FCode: does not use PrimRep on Alpha"
2820
2821     fltCmpOp op = case op of
2822         FloatGtOp -> True
2823         FloatGeOp -> True
2824         FloatEqOp -> True
2825         FloatNeOp -> True
2826         FloatLtOp -> True
2827         FloatLeOp -> True
2828         DoubleGtOp -> True
2829         DoubleGeOp -> True
2830         DoubleEqOp -> True
2831         DoubleNeOp -> True
2832         DoubleLtOp -> True
2833         DoubleLeOp -> True
2834         _ -> False
2835     (instr, cond) = case op of
2836         FloatGtOp -> (FCMP TF LE, EQQ)
2837         FloatGeOp -> (FCMP TF LTT, EQQ)
2838         FloatEqOp -> (FCMP TF EQQ, NE)
2839         FloatNeOp -> (FCMP TF EQQ, EQQ)
2840         FloatLtOp -> (FCMP TF LTT, NE)
2841         FloatLeOp -> (FCMP TF LE, NE)
2842         DoubleGtOp -> (FCMP TF LE, EQQ)
2843         DoubleGeOp -> (FCMP TF LTT, EQQ)
2844         DoubleEqOp -> (FCMP TF EQQ, NE)
2845         DoubleNeOp -> (FCMP TF EQQ, EQQ)
2846         DoubleLtOp -> (FCMP TF LTT, NE)
2847         DoubleLeOp -> (FCMP TF LE, NE)
2848
2849 genCondJump lbl (StPrim op [x, y])
2850   = trivialCode instr x y           `thenNat` \ register ->
2851     getNewRegNat IntRep             `thenNat` \ tmp ->
2852     let
2853         code   = registerCode register tmp
2854         result = registerName register tmp
2855         target = ImmCLbl lbl
2856     in
2857     return (code . mkSeqInstr (BI cond result target))
2858   where
2859     (instr, cond) = case op of
2860         CharGtOp -> (CMP LE, EQQ)
2861         CharGeOp -> (CMP LTT, EQQ)
2862         CharEqOp -> (CMP EQQ, NE)
2863         CharNeOp -> (CMP EQQ, EQQ)
2864         CharLtOp -> (CMP LTT, NE)
2865         CharLeOp -> (CMP LE, NE)
2866         IntGtOp -> (CMP LE, EQQ)
2867         IntGeOp -> (CMP LTT, EQQ)
2868         IntEqOp -> (CMP EQQ, NE)
2869         IntNeOp -> (CMP EQQ, EQQ)
2870         IntLtOp -> (CMP LTT, NE)
2871         IntLeOp -> (CMP LE, NE)
2872         WordGtOp -> (CMP ULE, EQQ)
2873         WordGeOp -> (CMP ULT, EQQ)
2874         WordEqOp -> (CMP EQQ, NE)
2875         WordNeOp -> (CMP EQQ, EQQ)
2876         WordLtOp -> (CMP ULT, NE)
2877         WordLeOp -> (CMP ULE, NE)
2878         AddrGtOp -> (CMP ULE, EQQ)
2879         AddrGeOp -> (CMP ULT, EQQ)
2880         AddrEqOp -> (CMP EQQ, NE)
2881         AddrNeOp -> (CMP EQQ, EQQ)
2882         AddrLtOp -> (CMP ULT, NE)
2883         AddrLeOp -> (CMP ULE, NE)
2884
2885 #endif /* alpha_TARGET_ARCH */
2886
2887 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2888
2889 #if i386_TARGET_ARCH
2890
2891 genCondJump id bool = do
2892   CondCode _ cond code <- getCondCode bool
2893   return (code `snocOL` JXX cond id)
2894
2895 #endif
2896
2897 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2898
2899 #if x86_64_TARGET_ARCH
2900
2901 genCondJump id bool = do
2902   CondCode is_float cond cond_code <- getCondCode bool
2903   if not is_float
2904     then
2905         return (cond_code `snocOL` JXX cond id)
2906     else do
2907         lbl <- getBlockIdNat
2908
2909         -- see comment with condFltReg
2910         let code = case cond of
2911                         NE  -> or_unordered
2912                         GU  -> plain_test
2913                         GEU -> plain_test
2914                         _   -> and_ordered
2915
2916             plain_test = unitOL (
2917                   JXX cond id
2918                 )
2919             or_unordered = toOL [
2920                   JXX cond id,
2921                   JXX PARITY id
2922                 ]
2923             and_ordered = toOL [
2924                   JXX PARITY lbl,
2925                   JXX cond id,
2926                   JXX ALWAYS lbl,
2927                   NEWBLOCK lbl
2928                 ]
2929         return (cond_code `appOL` code)
2930
2931 #endif
2932
2933 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2934
2935 #if sparc_TARGET_ARCH
2936
2937 genCondJump id bool = do
2938   CondCode is_float cond code <- getCondCode bool
2939   return (
2940        code `appOL` 
2941        toOL (
2942          if   is_float
2943          then [NOP, BF cond False id, NOP]
2944          else [BI cond False id, NOP]
2945        )
2946     )
2947
2948 #endif /* sparc_TARGET_ARCH */
2949
2950
2951 #if powerpc_TARGET_ARCH
2952
2953 genCondJump id bool = do
2954   CondCode is_float cond code <- getCondCode bool
2955   return (code `snocOL` BCC cond id)
2956
2957 #endif /* powerpc_TARGET_ARCH */
2958
2959
2960 -- -----------------------------------------------------------------------------
2961 --  Generating C calls
2962
2963 -- Now the biggest nightmare---calls.  Most of the nastiness is buried in
2964 -- @get_arg@, which moves the arguments to the correct registers/stack
2965 -- locations.  Apart from that, the code is easy.
2966 -- 
2967 -- (If applicable) Do not fill the delay slots here; you will confuse the
2968 -- register allocator.
2969
2970 genCCall
2971     :: CmmCallTarget            -- function to call
2972     -> [(CmmReg,MachHint)]      -- where to put the result
2973     -> [(CmmExpr,MachHint)]     -- arguments (of mixed type)
2974     -> Maybe [GlobalReg]        -- volatile regs to save
2975     -> NatM InstrBlock
2976
2977 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2978
2979 #if alpha_TARGET_ARCH
2980
2981 ccallResultRegs = 
2982
2983 genCCall fn cconv result_regs args
2984   = mapAccumLNat get_arg (allArgRegs, eXTRA_STK_ARGS_HERE) args
2985                           `thenNat` \ ((unused,_), argCode) ->
2986     let
2987         nRegs = length allArgRegs - length unused
2988         code = asmSeqThen (map ($ []) argCode)
2989     in
2990         returnSeq code [
2991             LDA pv (AddrImm (ImmLab (ptext fn))),
2992             JSR ra (AddrReg pv) nRegs,
2993             LDGP gp (AddrReg ra)]
2994   where
2995     ------------------------
2996     {-  Try to get a value into a specific register (or registers) for
2997         a call.  The first 6 arguments go into the appropriate
2998         argument register (separate registers for integer and floating
2999         point arguments, but used in lock-step), and the remaining
3000         arguments are dumped to the stack, beginning at 0(sp).  Our
3001         first argument is a pair of the list of remaining argument
3002         registers to be assigned for this call and the next stack
3003         offset to use for overflowing arguments.  This way,
3004         @get_Arg@ can be applied to all of a call's arguments using
3005         @mapAccumLNat@.
3006     -}
3007     get_arg
3008         :: ([(Reg,Reg)], Int)   -- Argument registers and stack offset (accumulator)
3009         -> StixTree             -- Current argument
3010         -> NatM (([(Reg,Reg)],Int), InstrBlock) -- Updated accumulator and code
3011
3012     -- We have to use up all of our argument registers first...
3013
3014     get_arg ((iDst,fDst):dsts, offset) arg
3015       = getRegister arg                     `thenNat` \ register ->
3016         let
3017             reg  = if isFloatingRep pk then fDst else iDst
3018             code = registerCode register reg
3019             src  = registerName register reg
3020             pk   = registerRep register
3021         in
3022         return (
3023             if isFloatingRep pk then
3024                 ((dsts, offset), if isFixed register then
3025                     code . mkSeqInstr (FMOV src fDst)
3026                     else code)
3027             else
3028                 ((dsts, offset), if isFixed register then
3029                     code . mkSeqInstr (OR src (RIReg src) iDst)
3030                     else code))
3031
3032     -- Once we have run out of argument registers, we move to the
3033     -- stack...
3034
3035     get_arg ([], offset) arg
3036       = getRegister arg                 `thenNat` \ register ->
3037         getNewRegNat (registerRep register)
3038                                         `thenNat` \ tmp ->
3039         let
3040             code = registerCode register tmp
3041             src  = registerName register tmp
3042             pk   = registerRep register
3043             sz   = primRepToSize pk
3044         in
3045         return (([], offset + 1), code . mkSeqInstr (ST sz src (spRel offset)))
3046
3047 #endif /* alpha_TARGET_ARCH */
3048
3049 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3050
3051 #if i386_TARGET_ARCH
3052
3053 -- we only cope with a single result for foreign calls
3054 genCCall (CmmPrim op) [(r,_)] args vols = do
3055   case op of
3056         MO_F32_Sqrt -> actuallyInlineFloatOp F32  (GSQRT F32) args
3057         MO_F64_Sqrt -> actuallyInlineFloatOp F64 (GSQRT F64) args
3058         
3059         MO_F32_Sin  -> actuallyInlineFloatOp F32  (GSIN F32) args
3060         MO_F64_Sin  -> actuallyInlineFloatOp F64 (GSIN F64) args
3061         
3062         MO_F32_Cos  -> actuallyInlineFloatOp F32  (GCOS F32) args
3063         MO_F64_Cos  -> actuallyInlineFloatOp F64 (GCOS F64) args
3064         
3065         MO_F32_Tan  -> actuallyInlineFloatOp F32  (GTAN F32) args
3066         MO_F64_Tan  -> actuallyInlineFloatOp F64 (GTAN F64) args
3067         
3068         other_op    -> outOfLineFloatOp op r args vols
3069  where
3070   actuallyInlineFloatOp rep instr [(x,_)]
3071         = do res <- trivialUFCode rep instr x
3072              any <- anyReg res
3073              return (any (getRegisterReg r))
3074
3075 genCCall target dest_regs args vols = do
3076     sizes_n_codes <- mapM push_arg (reverse args)
3077     delta <- getDeltaNat
3078     let 
3079         (sizes, push_codes) = unzip sizes_n_codes
3080         tot_arg_size        = sum sizes
3081     -- in
3082     -- deal with static vs dynamic call targets
3083     (callinsns,cconv) <-
3084       case target of
3085         -- CmmPrim -> ...
3086         CmmForeignCall (CmmLit (CmmLabel lbl)) conv
3087            -> -- ToDo: stdcall arg sizes
3088               return (unitOL (CALL (Left fn_imm)), conv)
3089            where fn_imm = ImmCLbl lbl
3090         CmmForeignCall expr conv
3091            -> do (dyn_c, dyn_r, dyn_rep) <- get_op expr
3092                  ASSERT(dyn_rep == I32)
3093                   return (dyn_c `snocOL` CALL (Right dyn_r), conv)
3094
3095     let push_code = concatOL push_codes
3096         call = callinsns `appOL`
3097                toOL (
3098                         -- Deallocate parameters after call for ccall;
3099                         -- but not for stdcall (callee does it)
3100                   (if cconv == StdCallConv || tot_arg_size==0 then [] else 
3101                    [ADD I32 (OpImm (ImmInt tot_arg_size)) (OpReg esp)])
3102                   ++
3103                   [DELTA (delta + tot_arg_size)]
3104                )
3105     -- in
3106     setDeltaNat (delta + tot_arg_size)
3107
3108     let
3109         -- assign the results, if necessary
3110         assign_code []     = nilOL
3111         assign_code [(dest,_hint)] = 
3112           case rep of
3113                 I64 -> toOL [MOV I32 (OpReg eax) (OpReg r_dest),
3114                              MOV I32 (OpReg edx) (OpReg r_dest_hi)]
3115                 F32 -> unitOL (GMOV fake0 r_dest)
3116                 F64 -> unitOL (GMOV fake0 r_dest)
3117                 rep -> unitOL (MOV rep (OpReg eax) (OpReg r_dest))
3118           where 
3119                 r_dest_hi = getHiVRegFromLo r_dest
3120                 rep = cmmRegRep dest
3121                 r_dest = getRegisterReg dest
3122         assign_code many = panic "genCCall.assign_code many"
3123
3124     return (push_code `appOL` 
3125             call `appOL` 
3126             assign_code dest_regs)
3127
3128   where
3129     arg_size F64 = 8
3130     arg_size F32 = 4
3131     arg_size _   = 4
3132
3133     push_arg :: (CmmExpr,MachHint){-current argument-}
3134                     -> NatM (Int, InstrBlock)  -- argsz, code
3135
3136     push_arg (arg,_hint) -- we don't need the hints on x86
3137       | arg_rep == I64 = do
3138         ChildCode64 code r_lo <- iselExpr64 arg
3139         delta <- getDeltaNat
3140         setDeltaNat (delta - 8)
3141         let 
3142             r_hi = getHiVRegFromLo r_lo
3143         -- in
3144         return (8,     code `appOL`
3145                        toOL [PUSH I32 (OpReg r_hi), DELTA (delta - 4),
3146                              PUSH I32 (OpReg r_lo), DELTA (delta - 8),
3147                              DELTA (delta-8)]
3148             )
3149
3150       | otherwise = do
3151         (code, reg, sz) <- get_op arg
3152         delta <- getDeltaNat
3153         let size = arg_size sz
3154         setDeltaNat (delta-size)
3155         if (case sz of F64 -> True; F32 -> True; _ -> False)
3156            then return (size,
3157                         code `appOL`
3158                         toOL [SUB I32 (OpImm (ImmInt size)) (OpReg esp),
3159                               DELTA (delta-size),
3160                               GST sz reg (AddrBaseIndex (Just esp) 
3161                                                         Nothing 
3162                                                         (ImmInt 0))]
3163                        )
3164            else return (size,
3165                         code `snocOL`
3166                         PUSH I32 (OpReg reg) `snocOL`
3167                         DELTA (delta-size)
3168                        )
3169       where
3170          arg_rep = cmmExprRep arg
3171
3172     ------------
3173     get_op :: CmmExpr -> NatM (InstrBlock, Reg, MachRep) -- code, reg, size
3174     get_op op = do
3175         (reg,code) <- getSomeReg op
3176         return (code, reg, cmmExprRep op)
3177
3178 #endif /* i386_TARGET_ARCH */
3179
3180 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
3181
3182 outOfLineFloatOp :: CallishMachOp -> CmmReg -> [(CmmExpr,MachHint)]
3183   -> Maybe [GlobalReg] -> NatM InstrBlock
3184 outOfLineFloatOp mop res args vols
3185   | cmmRegRep res == F64
3186   = stmtToInstrs (CmmCall target [(res,FloatHint)] args vols)
3187
3188   | otherwise
3189   = do uq <- getUniqueNat
3190        let 
3191          tmp = CmmLocal (LocalReg uq F64)
3192        -- in
3193        code1 <- stmtToInstrs (CmmCall target [(tmp,FloatHint)] (map promote args) vols)
3194        code2 <- stmtToInstrs (CmmAssign res (demote (CmmReg tmp)))
3195        return (code1 `appOL` code2)
3196   where
3197         promote (x,hint) = (CmmMachOp (MO_S_Conv F32 F64) [x], hint)
3198         demote  x = CmmMachOp (MO_S_Conv F64 F32) [x]
3199
3200         target = CmmForeignCall (CmmLit lbl) CCallConv
3201         lbl = CmmLabel (mkForeignLabel fn Nothing False)
3202
3203         fn = case mop of
3204               MO_F32_Sqrt  -> FSLIT("sqrt")
3205               MO_F32_Sin   -> FSLIT("sin")
3206               MO_F32_Cos   -> FSLIT("cos")
3207               MO_F32_Tan   -> FSLIT("tan")
3208               MO_F32_Exp   -> FSLIT("exp")
3209               MO_F32_Log   -> FSLIT("log")
3210
3211               MO_F32_Asin  -> FSLIT("asin")
3212               MO_F32_Acos  -> FSLIT("acos")
3213               MO_F32_Atan  -> FSLIT("atan")
3214
3215               MO_F32_Sinh  -> FSLIT("sinh")
3216               MO_F32_Cosh  -> FSLIT("cosh")
3217               MO_F32_Tanh  -> FSLIT("tanh")
3218               MO_F32_Pwr   -> FSLIT("pow")
3219
3220               MO_F64_Sqrt  -> FSLIT("sqrt")
3221               MO_F64_Sin   -> FSLIT("sin")
3222               MO_F64_Cos   -> FSLIT("cos")
3223               MO_F64_Tan   -> FSLIT("tan")
3224               MO_F64_Exp   -> FSLIT("exp")
3225               MO_F64_Log   -> FSLIT("log")
3226
3227               MO_F64_Asin  -> FSLIT("asin")
3228               MO_F64_Acos  -> FSLIT("acos")
3229               MO_F64_Atan  -> FSLIT("atan")
3230
3231               MO_F64_Sinh  -> FSLIT("sinh")
3232               MO_F64_Cosh  -> FSLIT("cosh")
3233               MO_F64_Tanh  -> FSLIT("tanh")
3234               MO_F64_Pwr   -> FSLIT("pow")
3235
3236               other -> pprPanic "outOfLineFloatOp" (pprCallishMachOp mop)
3237
3238 #endif /* i386_TARGET_ARCH || x86_64_TARGET_ARCH */
3239
3240 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3241
3242 #if x86_64_TARGET_ARCH
3243
3244 genCCall (CmmPrim op) [(r,_)] args vols = 
3245   outOfLineFloatOp op r args vols
3246
3247 genCCall target dest_regs args vols = do
3248
3249         -- load up the register arguments
3250     (stack_args, sse_regs, load_args_code)
3251          <- load_args args allArgRegs allFPArgRegs 0 nilOL
3252
3253     let
3254         tot_arg_size = arg_size * length stack_args
3255
3256         -- On entry to the called function, %rsp should be aligned
3257         -- on a 16-byte boundary +8 (i.e. the first stack arg after
3258         -- the return address is 16-byte aligned).  In STG land
3259         -- %rsp is kept 16-byte aligned (see StgCRun.c), so we just
3260         -- need to make sure we push a multiple of 16-bytes of args,
3261         -- plus the return address, to get the correct alignment.
3262         -- Urg, this is hard.  We need to feed the delta back into
3263         -- the arg pushing code.
3264     (real_size, adjust_rsp) <-
3265         if tot_arg_size `rem` 16 == 0
3266             then return (tot_arg_size, nilOL)
3267             else do -- we need to adjust...
3268                 delta <- getDeltaNat
3269                 setDeltaNat (delta-8)
3270                 return (tot_arg_size+8, toOL [
3271                                 SUB I64 (OpImm (ImmInt 8)) (OpReg rsp),
3272                                 DELTA (delta-8)
3273                         ])
3274
3275         -- push the stack args, right to left
3276     push_code <- push_args (reverse stack_args) nilOL
3277     delta <- getDeltaNat
3278
3279     -- deal with static vs dynamic call targets
3280     (callinsns,cconv) <-
3281       case target of
3282         -- CmmPrim -> ...
3283         CmmForeignCall (CmmLit (CmmLabel lbl)) conv
3284            -> -- ToDo: stdcall arg sizes
3285               return (unitOL (CALL (Left fn_imm)), conv)
3286            where fn_imm = ImmCLbl lbl
3287         CmmForeignCall expr conv
3288            -> do (dyn_r, dyn_c) <- getSomeReg expr
3289                  return (dyn_c `snocOL` CALL (Right dyn_r), conv)
3290
3291     let
3292         -- The x86_64 ABI requires us to set %al to the number of SSE
3293         -- registers that contain arguments, if the called routine
3294         -- is a varargs function.  We don't know whether it's a
3295         -- varargs function or not, so we have to assume it is.
3296         --
3297         -- It's not safe to omit this assignment, even if the number
3298         -- of SSE regs in use is zero.  If %al is larger than 8
3299         -- on entry to a varargs function, seg faults ensue.
3300         assign_eax n = unitOL (MOV I32 (OpImm (ImmInt n)) (OpReg eax))
3301
3302     let call = callinsns `appOL`
3303                toOL (
3304                         -- Deallocate parameters after call for ccall;
3305                         -- but not for stdcall (callee does it)
3306                   (if cconv == StdCallConv || real_size==0 then [] else 
3307                    [ADD wordRep (OpImm (ImmInt real_size)) (OpReg esp)])
3308                   ++
3309                   [DELTA (delta + real_size)]
3310                )
3311     -- in
3312     setDeltaNat (delta + real_size)
3313
3314     let
3315         -- assign the results, if necessary
3316         assign_code []     = nilOL
3317         assign_code [(dest,_hint)] = 
3318           case rep of
3319                 F32 -> unitOL (MOV rep (OpReg xmm0) (OpReg r_dest))
3320                 F64 -> unitOL (MOV rep (OpReg xmm0) (OpReg r_dest))
3321                 rep -> unitOL (MOV rep (OpReg rax) (OpReg r_dest))
3322           where 
3323                 rep = cmmRegRep dest
3324                 r_dest = getRegisterReg dest
3325         assign_code many = panic "genCCall.assign_code many"
3326
3327     return (load_args_code      `appOL` 
3328             adjust_rsp          `appOL`
3329             push_code           `appOL`
3330             assign_eax sse_regs `appOL`
3331             call                `appOL` 
3332             assign_code dest_regs)
3333
3334   where
3335     arg_size = 8 -- always, at the mo
3336
3337     load_args :: [(CmmExpr,MachHint)]
3338               -> [Reg]                  -- int regs avail for args
3339               -> [Reg]                  -- FP regs avail for args
3340               -> Int -> InstrBlock
3341               -> NatM ([(CmmExpr,MachHint)],Int,InstrBlock)
3342     load_args args [] [] sse_regs code = return (args, sse_regs, code)
3343         -- no more regs to use
3344     load_args [] aregs fregs sse_regs code = return ([],sse_regs,code)
3345         -- no more args to push
3346     load_args ((arg,hint) : rest) aregs fregs sse_regs code
3347         | isFloatingRep arg_rep = 
3348         case fregs of
3349           [] -> push_this_arg
3350           (r:rs) -> do
3351              arg_code <- getAnyReg arg
3352              load_args rest aregs rs (sse_regs+1) (code `appOL` arg_code r)
3353         | otherwise =
3354         case aregs of
3355           [] -> push_this_arg
3356           (r:rs) -> do
3357              arg_code <- getAnyReg arg
3358              load_args rest rs fregs sse_regs (code `appOL` arg_code r)
3359         where
3360           arg_rep = cmmExprRep arg
3361
3362           push_this_arg = do
3363             (args',sse',code') <- load_args rest aregs fregs sse_regs code
3364             return ((arg,hint):args', sse', code')
3365
3366     push_args [] code = return code
3367     push_args ((arg,hint):rest) code
3368        | isFloatingRep arg_rep = do
3369          (arg_reg, arg_code) <- getSomeReg arg
3370          delta <- getDeltaNat
3371          setDeltaNat (delta-arg_size)
3372          let code' = code `appOL` toOL [
3373                         MOV arg_rep (OpReg arg_reg) (OpAddr  (spRel 0)),
3374                         SUB wordRep (OpImm (ImmInt arg_size)) (OpReg rsp) ,
3375                         DELTA (delta-arg_size)]
3376          push_args rest code'
3377
3378        | otherwise = do
3379        -- we only ever generate word-sized function arguments.  Promotion
3380        -- has already happened: our Int8# type is kept sign-extended
3381        -- in an Int#, for example.
3382          ASSERT(arg_rep == I64) return ()
3383          (arg_op, arg_code) <- getOperand arg
3384          delta <- getDeltaNat
3385          setDeltaNat (delta-arg_size)
3386          let code' = code `appOL` toOL [PUSH I64 arg_op, 
3387                                         DELTA (delta-arg_size)]
3388          push_args rest code'
3389         where
3390           arg_rep = cmmExprRep arg
3391 #endif
3392
3393 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3394
3395 #if sparc_TARGET_ARCH
3396 {- 
3397    The SPARC calling convention is an absolute
3398    nightmare.  The first 6x32 bits of arguments are mapped into
3399    %o0 through %o5, and the remaining arguments are dumped to the
3400    stack, beginning at [%sp+92].  (Note that %o6 == %sp.)
3401
3402    If we have to put args on the stack, move %o6==%sp down by
3403    the number of words to go on the stack, to ensure there's enough space.
3404
3405    According to Fraser and Hanson's lcc book, page 478, fig 17.2,
3406    16 words above the stack pointer is a word for the address of
3407    a structure return value.  I use this as a temporary location
3408    for moving values from float to int regs.  Certainly it isn't
3409    safe to put anything in the 16 words starting at %sp, since
3410    this area can get trashed at any time due to window overflows
3411    caused by signal handlers.
3412
3413    A final complication (if the above isn't enough) is that 
3414    we can't blithely calculate the arguments one by one into
3415    %o0 .. %o5.  Consider the following nested calls:
3416
3417        fff a (fff b c)
3418
3419    Naive code moves a into %o0, and (fff b c) into %o1.  Unfortunately
3420    the inner call will itself use %o0, which trashes the value put there
3421    in preparation for the outer call.  Upshot: we need to calculate the
3422    args into temporary regs, and move those to arg regs or onto the
3423    stack only immediately prior to the call proper.  Sigh.
3424 -}
3425
3426 genCCall fn cconv kind args
3427   = mapNat arg_to_int_vregs args `thenNat` \ argcode_and_vregs ->
3428     let 
3429         (argcodes, vregss) = unzip argcode_and_vregs
3430         n_argRegs          = length allArgRegs
3431         n_argRegs_used     = min (length vregs) n_argRegs
3432         vregs              = concat vregss
3433     in
3434     -- deal with static vs dynamic call targets
3435     (case fn of
3436         Left t_static
3437            -> return (unitOL (CALL (Left fn__2) n_argRegs_used False))
3438         Right dyn
3439            -> arg_to_int_vregs dyn `thenNat` \ (dyn_c, [dyn_r]) ->
3440               return (dyn_c `snocOL` CALL (Right dyn_r) n_argRegs_used False)
3441     )
3442                                 `thenNat` \ callinsns ->
3443     let
3444         argcode = concatOL argcodes
3445         (move_sp_down, move_sp_up)
3446            = let diff = length vregs - n_argRegs
3447                  nn   = if odd diff then diff + 1 else diff -- keep 8-byte alignment
3448              in  if   nn <= 0
3449                  then (nilOL, nilOL)
3450                  else (unitOL (moveSp (-1*nn)), unitOL (moveSp (1*nn)))
3451         transfer_code
3452            = toOL (move_final vregs allArgRegs eXTRA_STK_ARGS_HERE)
3453     in
3454         return (argcode       `appOL`
3455                    move_sp_down  `appOL`
3456                    transfer_code `appOL`
3457                    callinsns     `appOL`
3458                    unitOL NOP    `appOL`
3459                    move_sp_up)
3460   where
3461      -- function names that begin with '.' are assumed to be special
3462      -- internally generated names like '.mul,' which don't get an
3463      -- underscore prefix
3464      -- ToDo:needed (WDP 96/03) ???
3465      fn_static = unLeft fn
3466      fn__2 = case (headFS fn_static) of
3467                 '.' -> ImmLit (ftext fn_static)
3468                 _   -> ImmCLbl (mkForeignLabel fn_static False)
3469
3470      -- move args from the integer vregs into which they have been 
3471      -- marshalled, into %o0 .. %o5, and the rest onto the stack.
3472      move_final :: [Reg] -> [Reg] -> Int -> [Instr]
3473
3474      move_final [] _ offset          -- all args done
3475         = []
3476
3477      move_final (v:vs) [] offset     -- out of aregs; move to stack
3478         = ST W v (spRel offset)
3479           : move_final vs [] (offset+1)
3480
3481      move_final (v:vs) (a:az) offset -- move into an arg (%o[0..5]) reg
3482         = OR False g0 (RIReg v) a
3483           : move_final vs az offset
3484
3485      -- generate code to calculate an argument, and move it into one
3486      -- or two integer vregs.
3487      arg_to_int_vregs :: CmmExpr -> NatM (OrdList Instr, [Reg])
3488      arg_to_int_vregs arg
3489         | is64BitRep (repOfCmmExpr arg)
3490         = iselExpr64 arg                `thenNat` \ (ChildCode64 code vr_lo) ->
3491           let r_lo = VirtualRegI vr_lo
3492               r_hi = getHiVRegFromLo r_lo
3493           in  return (code, [r_hi, r_lo])
3494         | otherwise
3495         = getRegister arg                     `thenNat` \ register ->
3496           getNewRegNat (registerRep register) `thenNat` \ tmp ->
3497           let code = registerCode register tmp
3498               src  = registerName register tmp
3499               pk   = registerRep register
3500           in
3501           -- the value is in src.  Get it into 1 or 2 int vregs.
3502           case pk of
3503              F64 -> 
3504                 getNewRegNat WordRep  `thenNat` \ v1 ->
3505                 getNewRegNat WordRep  `thenNat` \ v2 ->
3506                 return (
3507                    code                          `snocOL`
3508                    FMOV DF src f0                `snocOL`
3509                    ST   F  f0 (spRel 16)         `snocOL`
3510                    LD   W  (spRel 16) v1         `snocOL`
3511                    ST   F  (fPair f0) (spRel 16) `snocOL`
3512                    LD   W  (spRel 16) v2
3513                    ,
3514                    [v1,v2]
3515                 )
3516              F32 -> 
3517                 getNewRegNat WordRep  `thenNat` \ v1 ->
3518                 return (
3519                    code                    `snocOL`
3520                    ST   F  src (spRel 16)  `snocOL`
3521                    LD   W  (spRel 16) v1
3522                    ,
3523                    [v1]
3524                 )
3525              other ->
3526                 getNewRegNat WordRep  `thenNat` \ v1 ->
3527                 return (
3528                    code `snocOL` OR False g0 (RIReg src) v1
3529                    , 
3530                    [v1]
3531                 )
3532 #endif /* sparc_TARGET_ARCH */
3533
3534 #if powerpc_TARGET_ARCH
3535
3536 #if darwin_TARGET_OS || linux_TARGET_OS
3537 {-
3538     The PowerPC calling convention for Darwin/Mac OS X
3539     is described in Apple's document
3540     "Inside Mac OS X - Mach-O Runtime Architecture".
3541     
3542     PowerPC Linux uses the System V Release 4 Calling Convention
3543     for PowerPC. It is described in the
3544     "System V Application Binary Interface PowerPC Processor Supplement".
3545
3546     Both conventions are similar:
3547     Parameters may be passed in general-purpose registers starting at r3, in
3548     floating point registers starting at f1, or on the stack. 
3549     
3550     But there are substantial differences:
3551     * The number of registers used for parameter passing and the exact set of
3552       nonvolatile registers differs (see MachRegs.lhs).
3553     * On Darwin, stack space is always reserved for parameters, even if they are
3554       passed in registers. The called routine may choose to save parameters from
3555       registers to the corresponding space on the stack.
3556     * On Darwin, a corresponding amount of GPRs is skipped when a floating point
3557       parameter is passed in an FPR.
3558     * SysV insists on either passing I64 arguments on the stack, or in two GPRs,
3559       starting with an odd-numbered GPR. It may skip a GPR to achieve this.
3560       Darwin just treats an I64 like two separate I32s (high word first).
3561     * I64 and F64 arguments are 8-byte aligned on the stack for SysV, but only
3562       4-byte aligned like everything else on Darwin.
3563     * The SysV spec claims that F32 is represented as F64 on the stack. GCC on
3564       PowerPC Linux does not agree, so neither do we.
3565       
3566     According to both conventions, The parameter area should be part of the
3567     caller's stack frame, allocated in the caller's prologue code (large enough
3568     to hold the parameter lists for all called routines). The NCG already
3569     uses the stack for register spilling, leaving 64 bytes free at the top.
3570     If we need a larger parameter area than that, we just allocate a new stack
3571     frame just before ccalling.
3572 -}
3573
3574 genCCall target dest_regs argsAndHints vols
3575   = ASSERT (not $ any (`elem` [I8,I16]) argReps)
3576         -- we rely on argument promotion in the codeGen
3577     do
3578         (finalStack,passArgumentsCode,usedRegs) <- passArguments
3579                                                         (zip args argReps)
3580                                                         allArgRegs allFPArgRegs
3581                                                         initialStackOffset
3582                                                         (toOL []) []
3583                                                 
3584         (labelOrExpr, reduceToF32) <- case target of
3585             CmmForeignCall (CmmLit (CmmLabel lbl)) conv -> return (Left lbl, False)
3586             CmmForeignCall expr conv -> return  (Right expr, False)
3587             CmmPrim mop -> outOfLineFloatOp mop
3588                                                         
3589         let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode
3590             codeAfter = move_sp_up finalStack `appOL` moveResult reduceToF32
3591
3592         case labelOrExpr of
3593             Left lbl -> do
3594                 return (         codeBefore
3595                         `snocOL` BL lbl usedRegs
3596                         `appOL`  codeAfter)
3597             Right dyn -> do
3598                 (dynReg, dynCode) <- getSomeReg dyn
3599                 return (         dynCode
3600                         `snocOL` MTCTR dynReg
3601                         `appOL`  codeBefore
3602                         `snocOL` BCTRL usedRegs
3603                         `appOL`  codeAfter)
3604     where
3605 #if darwin_TARGET_OS
3606         initialStackOffset = 24
3607             -- size of linkage area + size of arguments, in bytes       
3608         stackDelta _finalStack = roundTo 16 $ (24 +) $ max 32 $ sum $
3609                                        map machRepByteWidth argReps
3610 #elif linux_TARGET_OS
3611         initialStackOffset = 8
3612         stackDelta finalStack = roundTo 16 finalStack
3613 #endif
3614         args = map fst argsAndHints
3615         argReps = map cmmExprRep args
3616
3617         roundTo a x | x `mod` a == 0 = x
3618                     | otherwise = x + a - (x `mod` a)
3619
3620         move_sp_down finalStack
3621                | delta > 64 =
3622                         toOL [STU I32 sp (AddrRegImm sp (ImmInt (-delta))),
3623                               DELTA (-delta)]
3624                | otherwise = nilOL
3625                where delta = stackDelta finalStack
3626         move_sp_up finalStack
3627                | delta > 64 =
3628                         toOL [ADD sp sp (RIImm (ImmInt delta)),
3629                               DELTA 0]
3630                | otherwise = nilOL
3631                where delta = stackDelta finalStack
3632                
3633
3634         passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed)
3635         passArguments ((arg,I64):args) gprs fprs stackOffset
3636                accumCode accumUsed =
3637             do
3638                 ChildCode64 code vr_lo <- iselExpr64 arg
3639                 let vr_hi = getHiVRegFromLo vr_lo
3640
3641 #if darwin_TARGET_OS                
3642                 passArguments args
3643                               (drop 2 gprs)
3644                               fprs
3645                               (stackOffset+8)
3646                               (accumCode `appOL` code
3647                                     `snocOL` storeWord vr_hi gprs stackOffset
3648                                     `snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4))
3649                               ((take 2 gprs) ++ accumUsed)
3650             where
3651                 storeWord vr (gpr:_) offset = MR gpr vr
3652                 storeWord vr [] offset = ST I32 vr (AddrRegImm sp (ImmInt offset))
3653                 
3654 #elif linux_TARGET_OS
3655                 let stackOffset' = roundTo 8 stackOffset
3656                     stackCode = accumCode `appOL` code
3657                         `snocOL` ST I32 vr_hi (AddrRegImm sp (ImmInt stackOffset'))
3658                         `snocOL` ST I32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4)))
3659                     regCode hireg loreg =
3660                         accumCode `appOL` code
3661                             `snocOL` MR hireg vr_hi
3662                             `snocOL` MR loreg vr_lo
3663                                         
3664                 case gprs of
3665                     hireg : loreg : regs | even (length gprs) ->
3666                         passArguments args regs fprs stackOffset
3667                                       (regCode hireg loreg) (hireg : loreg : accumUsed)
3668                     _skipped : hireg : loreg : regs ->
3669                         passArguments args regs fprs stackOffset
3670                                       (regCode hireg loreg) (hireg : loreg : accumUsed)
3671                     _ -> -- only one or no regs left
3672                         passArguments args [] fprs (stackOffset'+8)
3673                                       stackCode accumUsed
3674 #endif
3675         
3676         passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed
3677             | reg : _ <- regs = do
3678                 register <- getRegister arg
3679                 let code = case register of
3680                             Fixed _ freg fcode -> fcode `snocOL` MR reg freg
3681                             Any _ acode -> acode reg
3682                 passArguments args
3683                               (drop nGprs gprs)
3684                               (drop nFprs fprs)
3685 #if darwin_TARGET_OS
3686         -- The Darwin ABI requires that we reserve stack slots for register parameters
3687                               (stackOffset + stackBytes)
3688 #elif linux_TARGET_OS
3689         -- ... the SysV ABI doesn't.
3690                               stackOffset
3691 #endif
3692                               (accumCode `appOL` code)
3693                               (reg : accumUsed)
3694             | otherwise = do
3695                 (vr, code) <- getSomeReg arg
3696                 passArguments args
3697                               (drop nGprs gprs)
3698                               (drop nFprs fprs)
3699                               (stackOffset' + stackBytes)
3700                               (accumCode `appOL` code `snocOL` ST rep vr stackSlot)
3701                               accumUsed
3702             where
3703 #if darwin_TARGET_OS
3704         -- stackOffset is at least 4-byte aligned
3705         -- The Darwin ABI is happy with that.
3706                 stackOffset' = stackOffset
3707 #else
3708         -- ... the SysV ABI requires 8-byte alignment for doubles.
3709                 stackOffset' | rep == F64 = roundTo 8 stackOffset
3710                              | otherwise  =           stackOffset
3711 #endif
3712                 stackSlot = AddrRegImm sp (ImmInt stackOffset')
3713                 (nGprs, nFprs, stackBytes, regs) = case rep of
3714                     I32 -> (1, 0, 4, gprs)
3715 #if darwin_TARGET_OS
3716         -- The Darwin ABI requires that we skip a corresponding number of GPRs when
3717         -- we use the FPRs.
3718                     F32 -> (1, 1, 4, fprs)
3719                     F64 -> (2, 1, 8, fprs)
3720 #elif linux_TARGET_OS
3721         -- ... the SysV ABI doesn't.
3722                     F32 -> (0, 1, 4, fprs)
3723                     F64 -> (0, 1, 8, fprs)
3724 #endif
3725         
3726         moveResult reduceToF32 =
3727             case dest_regs of
3728                 [] -> nilOL
3729                 [(dest, _hint)]
3730                     | reduceToF32 && rep == F32 -> unitOL (FRSP r_dest f1)
3731                     | rep == F32 || rep == F64 -> unitOL (MR r_dest f1)
3732                     | rep == I64 -> toOL [MR (getHiVRegFromLo r_dest) r3,
3733                                           MR r_dest r4]
3734                     | otherwise -> unitOL (MR r_dest r3)
3735                     where rep = cmmRegRep dest
3736                           r_dest = getRegisterReg dest
3737                           
3738         outOfLineFloatOp mop =
3739             do
3740                 mopExpr <- cmmMakeDynamicReference addImportNat True $
3741                               mkForeignLabel functionName Nothing True
3742                 let mopLabelOrExpr = case mopExpr of
3743                         CmmLit (CmmLabel lbl) -> Left lbl
3744                         _ -> Right mopExpr
3745                 return (mopLabelOrExpr, reduce)
3746             where
3747                 (functionName, reduce) = case mop of
3748                     MO_F32_Exp   -> (FSLIT("exp"), True)
3749                     MO_F32_Log   -> (FSLIT("log"), True)
3750                     MO_F32_Sqrt  -> (FSLIT("sqrt"), True)
3751                         
3752                     MO_F32_Sin   -> (FSLIT("sin"), True)
3753                     MO_F32_Cos   -> (FSLIT("cos"), True)
3754                     MO_F32_Tan   -> (FSLIT("tan"), True)
3755                     
3756                     MO_F32_Asin  -> (FSLIT("asin"), True)
3757                     MO_F32_Acos  -> (FSLIT("acos"), True)
3758                     MO_F32_Atan  -> (FSLIT("atan"), True)
3759                     
3760                     MO_F32_Sinh  -> (FSLIT("sinh"), True)
3761                     MO_F32_Cosh  -> (FSLIT("cosh"), True)
3762                     MO_F32_Tanh  -> (FSLIT("tanh"), True)
3763                     MO_F32_Pwr   -> (FSLIT("pow"), True)
3764                         
3765                     MO_F64_Exp   -> (FSLIT("exp"), False)
3766                     MO_F64_Log   -> (FSLIT("log"), False)
3767                     MO_F64_Sqrt  -> (FSLIT("sqrt"), False)
3768                         
3769                     MO_F64_Sin   -> (FSLIT("sin"), False)
3770                     MO_F64_Cos   -> (FSLIT("cos"), False)
3771                     MO_F64_Tan   -> (FSLIT("tan"), False)
3772                      
3773                     MO_F64_Asin  -> (FSLIT("asin"), False)
3774                     MO_F64_Acos  -> (FSLIT("acos"), False)
3775                     MO_F64_Atan  -> (FSLIT("atan"), False)
3776                     
3777                     MO_F64_Sinh  -> (FSLIT("sinh"), False)
3778                     MO_F64_Cosh  -> (FSLIT("cosh"), False)
3779                     MO_F64_Tanh  -> (FSLIT("tanh"), False)
3780                     MO_F64_Pwr   -> (FSLIT("pow"), False)
3781                     other -> pprPanic "genCCall(ppc): unknown callish op"
3782                                     (pprCallishMachOp other)
3783
3784 #endif /* darwin_TARGET_OS || linux_TARGET_OS */
3785                 
3786 #endif /* powerpc_TARGET_ARCH */
3787
3788
3789 -- -----------------------------------------------------------------------------
3790 -- Generating a table-branch
3791
3792 genSwitch :: CmmExpr -> [Maybe BlockId] -> NatM InstrBlock
3793
3794 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
3795 genSwitch expr ids = do
3796   (reg,e_code) <- getSomeReg expr
3797   lbl <- getNewLabelNat
3798   let
3799         jumpTable = map jumpTableEntry ids
3800         op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg wORD_SIZE) (ImmCLbl lbl))
3801         code = e_code `appOL` toOL [
3802                 LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3803                 JMP_TBL op [ id | Just id <- ids ]
3804              ]
3805   -- in
3806   return code
3807 #elif powerpc_TARGET_ARCH
3808 genSwitch expr ids 
3809   | opt_PIC
3810   = do
3811         (reg,e_code) <- getSomeReg expr
3812         tmp <- getNewRegNat I32
3813         lbl <- getNewLabelNat
3814         dynRef <- cmmMakeDynamicReference addImportNat False lbl
3815         (tableReg,t_code) <- getSomeReg $ dynRef
3816         let
3817             jumpTable = map jumpTableEntryRel ids
3818             
3819             jumpTableEntryRel Nothing
3820                 = CmmStaticLit (CmmInt 0 wordRep)
3821             jumpTableEntryRel (Just (BlockId id))
3822                 = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
3823                 where blockLabel = mkAsmTempLabel id
3824
3825             code = e_code `appOL` t_code `appOL` toOL [
3826                             LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3827                             SLW tmp reg (RIImm (ImmInt 2)),
3828                             LD I32 tmp (AddrRegReg tableReg tmp),
3829                             ADD tmp tmp (RIReg tableReg),
3830                             MTCTR tmp,
3831                             BCTR [ id | Just id <- ids ]
3832                     ]
3833         return code
3834   | otherwise
3835   = do
3836         (reg,e_code) <- getSomeReg expr
3837         tmp <- getNewRegNat I32
3838         lbl <- getNewLabelNat
3839         let
3840             jumpTable = map jumpTableEntry ids
3841         
3842             code = e_code `appOL` toOL [
3843                             LDATA ReadOnlyData (CmmDataLabel lbl : jumpTable),
3844                             SLW tmp reg (RIImm (ImmInt 2)),
3845                             ADDIS tmp tmp (HA (ImmCLbl lbl)),
3846                             LD I32 tmp (AddrRegImm tmp (LO (ImmCLbl lbl))),
3847                             MTCTR tmp,
3848                             BCTR [ id | Just id <- ids ]
3849                     ]
3850         return code
3851 #else
3852 genSwitch expr ids = panic "ToDo: genSwitch"
3853 #endif
3854
3855 jumpTableEntry Nothing = CmmStaticLit (CmmInt 0 wordRep)
3856 jumpTableEntry (Just (BlockId id)) = CmmStaticLit (CmmLabel blockLabel)
3857     where blockLabel = mkAsmTempLabel id
3858
3859 -- -----------------------------------------------------------------------------
3860 -- Support bits
3861 -- -----------------------------------------------------------------------------
3862
3863
3864 -- -----------------------------------------------------------------------------
3865 -- 'condIntReg' and 'condFltReg': condition codes into registers
3866
3867 -- Turn those condition codes into integers now (when they appear on
3868 -- the right hand side of an assignment).
3869 -- 
3870 -- (If applicable) Do not fill the delay slots here; you will confuse the
3871 -- register allocator.
3872
3873 condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
3874
3875 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3876
3877 #if alpha_TARGET_ARCH
3878 condIntReg = panic "MachCode.condIntReg (not on Alpha)"
3879 condFltReg = panic "MachCode.condFltReg (not on Alpha)"
3880 #endif /* alpha_TARGET_ARCH */
3881
3882 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3883
3884 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
3885
3886 condIntReg cond x y = do
3887   CondCode _ cond cond_code <- condIntCode cond x y
3888   tmp <- getNewRegNat I8
3889   let 
3890         code dst = cond_code `appOL` toOL [
3891                     SETCC cond (OpReg tmp),
3892                     MOVZxL I8 (OpReg tmp) (OpReg dst)
3893                   ]
3894   -- in
3895   return (Any I32 code)
3896
3897 condFltReg cond x y = do
3898   CondCode _ cond cond_code <- condFltCode cond x y
3899   tmp1 <- getNewRegNat wordRep
3900   tmp2 <- getNewRegNat wordRep
3901   let 
3902         -- We have to worry about unordered operands (eg. comparisons
3903         -- against NaN).  If the operands are unordered, the comparison
3904         -- sets the parity flag, carry flag and zero flag.
3905         -- All comparisons are supposed to return false for unordered
3906         -- operands except for !=, which returns true.
3907         --
3908         -- Optimisation: we don't have to test the parity flag if we
3909         -- know the test has already excluded the unordered case: eg >
3910         -- and >= test for a zero carry flag, which can only occur for
3911         -- ordered operands.
3912         --
3913         -- ToDo: by reversing comparisons we could avoid testing the
3914         -- parity flag in more cases.
3915
3916         code dst = 
3917            cond_code `appOL` 
3918              (case cond of
3919                 NE  -> or_unordered dst
3920                 GU  -> plain_test   dst
3921                 GEU -> plain_test   dst
3922                 _   -> and_ordered  dst)
3923
3924         plain_test dst = toOL [
3925                     SETCC cond (OpReg tmp1),
3926                     MOVZxL I8 (OpReg tmp1) (OpReg dst)
3927                  ]
3928         or_unordered dst = toOL [
3929                     SETCC cond (OpReg tmp1),
3930                     SETCC PARITY (OpReg tmp2),
3931                     OR I8 (OpReg tmp1) (OpReg tmp2),
3932                     MOVZxL I8 (OpReg tmp2) (OpReg dst)
3933                   ]
3934         and_ordered dst = toOL [
3935                     SETCC cond (OpReg tmp1),
3936                     SETCC NOTPARITY (OpReg tmp2),
3937                     AND I8 (OpReg tmp1) (OpReg tmp2),
3938                     MOVZxL I8 (OpReg tmp2) (OpReg dst)
3939                   ]
3940   -- in
3941   return (Any I32 code)
3942 #endif
3943
3944 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3945
3946 #if sparc_TARGET_ARCH
3947
3948 condIntReg EQQ x (StInt 0)
3949   = getRegister x               `thenNat` \ register ->
3950     getNewRegNat IntRep         `thenNat` \ tmp ->
3951     let
3952         code = registerCode register tmp
3953         src  = registerName register tmp
3954         code__2 dst = code `appOL` toOL [
3955             SUB False True g0 (RIReg src) g0,
3956             SUB True False g0 (RIImm (ImmInt (-1))) dst]
3957     in
3958     return (Any IntRep code__2)
3959
3960 condIntReg EQQ x y
3961   = getRegister x               `thenNat` \ register1 ->
3962     getRegister y               `thenNat` \ register2 ->
3963     getNewRegNat IntRep         `thenNat` \ tmp1 ->
3964     getNewRegNat IntRep         `thenNat` \ tmp2 ->
3965     let
3966         code1 = registerCode register1 tmp1
3967         src1  = registerName register1 tmp1
3968         code2 = registerCode register2 tmp2
3969         src2  = registerName register2 tmp2
3970         code__2 dst = code1 `appOL` code2 `appOL` toOL [
3971             XOR False src1 (RIReg src2) dst,
3972             SUB False True g0 (RIReg dst) g0,
3973             SUB True False g0 (RIImm (ImmInt (-1))) dst]
3974     in
3975     return (Any IntRep code__2)
3976
3977 condIntReg NE x (StInt 0)
3978   = getRegister x               `thenNat` \ register ->
3979     getNewRegNat IntRep         `thenNat` \ tmp ->
3980     let
3981         code = registerCode register tmp
3982         src  = registerName register tmp
3983         code__2 dst = code `appOL` toOL [
3984             SUB False True g0 (RIReg src) g0,
3985             ADD True False g0 (RIImm (ImmInt 0)) dst]
3986     in
3987     return (Any IntRep code__2)
3988
3989 condIntReg NE x y
3990   = getRegister x               `thenNat` \ register1 ->
3991     getRegister y               `thenNat` \ register2 ->
3992     getNewRegNat IntRep         `thenNat` \ tmp1 ->
3993     getNewRegNat IntRep         `thenNat` \ tmp2 ->
3994     let
3995         code1 = registerCode register1 tmp1
3996         src1  = registerName register1 tmp1
3997         code2 = registerCode register2 tmp2
3998         src2  = registerName register2 tmp2
3999         code__2 dst = code1 `appOL` code2 `appOL` toOL [
4000             XOR False src1 (RIReg src2) dst,
4001             SUB False True g0 (RIReg dst) g0,
4002             ADD True False g0 (RIImm (ImmInt 0)) dst]
4003     in
4004     return (Any IntRep code__2)
4005
4006 condIntReg cond x y
4007   = getBlockIdNat               `thenNat` \ lbl1 ->
4008     getBlockIdNat               `thenNat` \ lbl2 ->
4009     condIntCode cond x y        `thenNat` \ condition ->
4010     let
4011         code = condCode condition
4012         cond = condName condition
4013         code__2 dst = code `appOL` toOL [
4014             BI cond False (ImmCLbl lbl1), NOP,
4015             OR False g0 (RIImm (ImmInt 0)) dst,
4016             BI ALWAYS False (ImmCLbl lbl2), NOP,
4017             NEWBLOCK lbl1,
4018             OR False g0 (RIImm (ImmInt 1)) dst,
4019             NEWBLOCK lbl2]
4020     in
4021     return (Any IntRep code__2)
4022
4023 condFltReg cond x y
4024   = getBlockIdNat               `thenNat` \ lbl1 ->
4025     getBlockIdNat               `thenNat` \ lbl2 ->
4026     condFltCode cond x y        `thenNat` \ condition ->
4027     let
4028         code = condCode condition
4029         cond = condName condition
4030         code__2 dst = code `appOL` toOL [
4031             NOP,
4032             BF cond False (ImmCLbl lbl1), NOP,
4033             OR False g0 (RIImm (ImmInt 0)) dst,
4034             BI ALWAYS False (ImmCLbl lbl2), NOP,
4035             NEWBLOCK lbl1,
4036             OR False g0 (RIImm (ImmInt 1)) dst,
4037             NEWBLOCK lbl2]
4038     in
4039     return (Any IntRep code__2)
4040
4041 #endif /* sparc_TARGET_ARCH */
4042
4043 #if powerpc_TARGET_ARCH
4044 condReg getCond = do
4045     lbl1 <- getBlockIdNat
4046     lbl2 <- getBlockIdNat
4047     CondCode _ cond cond_code <- getCond
4048     let
4049 {-        code dst = cond_code `appOL` toOL [
4050                 BCC cond lbl1,
4051                 LI dst (ImmInt 0),
4052                 BCC ALWAYS lbl2,
4053                 NEWBLOCK lbl1,
4054                 LI dst (ImmInt 1),
4055                 BCC ALWAYS lbl2,
4056                 NEWBLOCK lbl2
4057             ]-}
4058         code dst = cond_code
4059             `appOL` negate_code
4060             `appOL` toOL [
4061                 MFCR dst,
4062                 RLWINM dst dst (bit + 1) 31 31
4063             ]
4064         
4065         negate_code | do_negate = unitOL (CRNOR bit bit bit)
4066                     | otherwise = nilOL
4067                     
4068         (bit, do_negate) = case cond of
4069             LTT -> (0, False)
4070             LE  -> (1, True)
4071             EQQ -> (2, False)
4072             GE  -> (0, True)
4073             GTT -> (1, False)
4074             
4075             NE  -> (2, True)
4076             
4077             LU  -> (0, False)
4078             LEU -> (1, True)
4079             GEU -> (0, True)
4080             GU  -> (1, False)
4081                 
4082     return (Any I32 code)
4083     
4084 condIntReg cond x y = condReg (condIntCode cond x y)
4085 condFltReg cond x y = condReg (condFltCode cond x y)
4086 #endif /* powerpc_TARGET_ARCH */
4087
4088
4089 -- -----------------------------------------------------------------------------
4090 -- 'trivial*Code': deal with trivial instructions
4091
4092 -- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
4093 -- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
4094 -- Only look for constants on the right hand side, because that's
4095 -- where the generic optimizer will have put them.
4096
4097 -- Similarly, for unary instructions, we don't have to worry about
4098 -- matching an StInt as the argument, because genericOpt will already
4099 -- have handled the constant-folding.
4100
4101 trivialCode
4102     :: MachRep 
4103     -> IF_ARCH_alpha((Reg -> RI -> Reg -> Instr)
4104       ,IF_ARCH_i386 ((Operand -> Operand -> Instr) 
4105                      -> Maybe (Operand -> Operand -> Instr)
4106       ,IF_ARCH_x86_64 ((Operand -> Operand -> Instr) 
4107                      -> Maybe (Operand -> Operand -> Instr)
4108       ,IF_ARCH_sparc((Reg -> RI -> Reg -> Instr)
4109       ,IF_ARCH_powerpc(Bool -> (Reg -> Reg -> RI -> Instr)
4110       ,)))))
4111     -> CmmExpr -> CmmExpr -- the two arguments
4112     -> NatM Register
4113
4114 #ifndef powerpc_TARGET_ARCH
4115 trivialFCode
4116     :: MachRep
4117     -> IF_ARCH_alpha((Reg -> Reg -> Reg -> Instr)
4118       ,IF_ARCH_sparc((Size -> Reg -> Reg -> Reg -> Instr)
4119       ,IF_ARCH_i386 ((MachRep -> Reg -> Reg -> Reg -> Instr)
4120       ,IF_ARCH_x86_64 ((MachRep -> Operand -> Operand -> Instr)
4121       ,))))
4122     -> CmmExpr -> CmmExpr -- the two arguments
4123     -> NatM Register
4124 #endif
4125
4126 trivialUCode
4127     :: MachRep 
4128     -> IF_ARCH_alpha((RI -> Reg -> Instr)
4129       ,IF_ARCH_i386 ((Operand -> Instr)
4130       ,IF_ARCH_x86_64 ((Operand -> Instr)
4131       ,IF_ARCH_sparc((RI -> Reg -> Instr)
4132       ,IF_ARCH_powerpc((Reg -> Reg -> Instr)
4133       ,)))))
4134     -> CmmExpr  -- the one argument
4135     -> NatM Register
4136
4137 #ifndef powerpc_TARGET_ARCH
4138 trivialUFCode
4139     :: MachRep
4140     -> IF_ARCH_alpha((Reg -> Reg -> Instr)
4141       ,IF_ARCH_i386 ((Reg -> Reg -> Instr)
4142       ,IF_ARCH_x86_64 ((Reg -> Reg -> Instr)
4143       ,IF_ARCH_sparc((Reg -> Reg -> Instr)
4144       ,))))
4145     -> CmmExpr -- the one argument
4146     -> NatM Register
4147 #endif
4148
4149 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4150
4151 #if alpha_TARGET_ARCH
4152
4153 trivialCode instr x (StInt y)
4154   | fits8Bits y
4155   = getRegister x               `thenNat` \ register ->
4156     getNewRegNat IntRep         `thenNat` \ tmp ->
4157     let
4158         code = registerCode register tmp
4159         src1 = registerName register tmp
4160         src2 = ImmInt (fromInteger y)
4161         code__2 dst = code . mkSeqInstr (instr src1 (RIImm src2) dst)
4162     in
4163     return (Any IntRep code__2)
4164
4165 trivialCode instr x y
4166   = getRegister x               `thenNat` \ register1 ->
4167     getRegister y               `thenNat` \ register2 ->
4168     getNewRegNat IntRep         `thenNat` \ tmp1 ->
4169     getNewRegNat IntRep         `thenNat` \ tmp2 ->
4170     let
4171         code1 = registerCode register1 tmp1 []
4172         src1  = registerName register1 tmp1
4173         code2 = registerCode register2 tmp2 []
4174         src2  = registerName register2 tmp2
4175         code__2 dst = asmSeqThen [code1, code2] .
4176                      mkSeqInstr (instr src1 (RIReg src2) dst)
4177     in
4178     return (Any IntRep code__2)
4179
4180 ------------
4181 trivialUCode instr x
4182   = getRegister x               `thenNat` \ register ->
4183     getNewRegNat IntRep         `thenNat` \ tmp ->
4184     let
4185         code = registerCode register tmp
4186         src  = registerName register tmp
4187         code__2 dst = code . mkSeqInstr (instr (RIReg src) dst)
4188     in
4189     return (Any IntRep code__2)
4190
4191 ------------
4192 trivialFCode _ instr x y
4193   = getRegister x               `thenNat` \ register1 ->
4194     getRegister y               `thenNat` \ register2 ->
4195     getNewRegNat F64    `thenNat` \ tmp1 ->
4196     getNewRegNat F64    `thenNat` \ tmp2 ->
4197     let
4198         code1 = registerCode register1 tmp1
4199         src1  = registerName register1 tmp1
4200
4201         code2 = registerCode register2 tmp2
4202         src2  = registerName register2 tmp2
4203
4204         code__2 dst = asmSeqThen [code1 [], code2 []] .
4205                       mkSeqInstr (instr src1 src2 dst)
4206     in
4207     return (Any F64 code__2)
4208
4209 trivialUFCode _ instr x
4210   = getRegister x               `thenNat` \ register ->
4211     getNewRegNat F64    `thenNat` \ tmp ->
4212     let
4213         code = registerCode register tmp
4214         src  = registerName register tmp
4215         code__2 dst = code . mkSeqInstr (instr src dst)
4216     in
4217     return (Any F64 code__2)
4218
4219 #endif /* alpha_TARGET_ARCH */
4220
4221 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4222
4223 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
4224
4225 {-
4226 The Rules of the Game are:
4227
4228 * You cannot assume anything about the destination register dst;
4229   it may be anything, including a fixed reg.
4230
4231 * You may compute an operand into a fixed reg, but you may not 
4232   subsequently change the contents of that fixed reg.  If you
4233   want to do so, first copy the value either to a temporary
4234   or into dst.  You are free to modify dst even if it happens
4235   to be a fixed reg -- that's not your problem.
4236
4237 * You cannot assume that a fixed reg will stay live over an
4238   arbitrary computation.  The same applies to the dst reg.
4239
4240 * Temporary regs obtained from getNewRegNat are distinct from 
4241   each other and from all other regs, and stay live over 
4242   arbitrary computations.
4243
4244 --------------------
4245
4246 SDM's version of The Rules:
4247
4248 * If getRegister returns Any, that means it can generate correct
4249   code which places the result in any register, period.  Even if that
4250   register happens to be read during the computation.
4251
4252   Corollary #1: this means that if you are generating code for an
4253   operation with two arbitrary operands, you cannot assign the result
4254   of the first operand into the destination register before computing
4255   the second operand.  The second operand might require the old value
4256   of the destination register.
4257
4258   Corollary #2: A function might be able to generate more efficient
4259   code if it knows the destination register is a new temporary (and
4260   therefore not read by any of the sub-computations).
4261
4262 * If getRegister returns Any, then the code it generates may modify only:
4263         (a) fresh temporaries
4264         (b) the destination register
4265         (c) known registers (eg. %ecx is used by shifts)
4266   In particular, it may *not* modify global registers, unless the global
4267   register happens to be the destination register.
4268 -}
4269
4270 trivialCode rep instr (Just revinstr) (CmmLit lit_a) b
4271   | not (is64BitLit lit_a) = do
4272   b_code <- getAnyReg b
4273   let
4274        code dst 
4275          = b_code dst `snocOL`
4276            revinstr (OpImm (litToImm lit_a)) (OpReg dst)
4277   -- in
4278   return (Any rep code)
4279
4280 trivialCode rep instr maybe_revinstr a b = do
4281   (b_op, b_code) <- getNonClobberedOperand b
4282   a_code <- getAnyReg a
4283   tmp <- getNewRegNat rep
4284   let
4285      -- We want the value of b to stay alive across the computation of a.
4286      -- But, we want to calculate a straight into the destination register,
4287      -- because the instruction only has two operands (dst := dst `op` src).
4288      -- The troublesome case is when the result of b is in the same register
4289      -- as the destination reg.  In this case, we have to save b in a
4290      -- new temporary across the computation of a.
4291      code dst
4292         | dst `clashesWith` b_op =
4293                 b_code `appOL`
4294                 unitOL (MOV rep b_op (OpReg tmp)) `appOL`
4295                 a_code dst `snocOL`
4296                 instr (OpReg tmp) (OpReg dst)
4297         | otherwise =
4298                 b_code `appOL`
4299                 a_code dst `snocOL`
4300                 instr b_op (OpReg dst)
4301   -- in
4302   return (Any rep code)
4303  where
4304   reg `clashesWith` OpReg reg2   = reg == reg2
4305   reg `clashesWith` OpAddr amode = any (==reg) (addrModeRegs amode)
4306   reg `clashesWith` _            = False
4307
4308 -----------
4309
4310 trivialUCode rep instr x = do
4311   x_code <- getAnyReg x
4312   let
4313      code dst =
4314         x_code dst `snocOL`
4315         instr (OpReg dst)
4316   -- in
4317   return (Any rep code)
4318
4319 -----------
4320
4321 #if i386_TARGET_ARCH
4322
4323 trivialFCode pk instr x y = do
4324   (x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too
4325   (y_reg, y_code) <- getSomeReg y
4326   let
4327      code dst =
4328         x_code `appOL`
4329         y_code `snocOL`
4330         instr pk x_reg y_reg dst
4331   -- in
4332   return (Any pk code)
4333
4334 #endif
4335
4336 #if x86_64_TARGET_ARCH
4337
4338 -- We use the 2-operand SSE2 floating pt instructions.  ToDo: improve on
4339 -- this by using some of the special cases in trivialCode above.
4340 trivialFCode pk instr x y = do
4341   (y_reg, y_code) <- getNonClobberedReg y -- these work for float regs too
4342   x_code <- getAnyReg x
4343   let
4344      code dst =
4345         y_code `appOL`
4346         x_code dst `snocOL`
4347         instr pk (IF_ARCH_x86_64(OpReg,) y_reg)
4348                  (IF_ARCH_x86_64(OpReg,) dst)
4349   -- in
4350   return (Any pk code)
4351
4352 #endif
4353
4354 -------------
4355
4356 trivialUFCode rep instr x = do
4357   (x_reg, x_code) <- getSomeReg x
4358   let
4359      code dst =
4360         x_code `snocOL`
4361         instr x_reg dst
4362   -- in
4363   return (Any rep code)
4364
4365 #endif /* i386_TARGET_ARCH */
4366
4367 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4368
4369 #if sparc_TARGET_ARCH
4370
4371 trivialCode instr x (StInt y)
4372   | fits13Bits y
4373   = getRegister x               `thenNat` \ register ->
4374     getNewRegNat IntRep         `thenNat` \ tmp ->
4375     let
4376         code = registerCode register tmp
4377         src1 = registerName register tmp
4378         src2 = ImmInt (fromInteger y)
4379         code__2 dst = code `snocOL` instr src1 (RIImm src2) dst
4380     in
4381     return (Any IntRep code__2)
4382
4383 trivialCode instr x y
4384   = getRegister x               `thenNat` \ register1 ->
4385     getRegister y               `thenNat` \ register2 ->
4386     getNewRegNat IntRep         `thenNat` \ tmp1 ->
4387     getNewRegNat IntRep         `thenNat` \ tmp2 ->
4388     let
4389         code1 = registerCode register1 tmp1
4390         src1  = registerName register1 tmp1
4391         code2 = registerCode register2 tmp2
4392         src2  = registerName register2 tmp2
4393         code__2 dst = code1 `appOL` code2 `snocOL`
4394                       instr src1 (RIReg src2) dst
4395     in
4396     return (Any IntRep code__2)
4397
4398 ------------
4399 trivialFCode pk instr x y
4400   = getRegister x               `thenNat` \ register1 ->
4401     getRegister y               `thenNat` \ register2 ->
4402     getNewRegNat (registerRep register1)
4403                                 `thenNat` \ tmp1 ->
4404     getNewRegNat (registerRep register2)
4405                                 `thenNat` \ tmp2 ->
4406     getNewRegNat F64    `thenNat` \ tmp ->
4407     let
4408         promote x = FxTOy F DF x tmp
4409
4410         pk1   = registerRep register1
4411         code1 = registerCode register1 tmp1
4412         src1  = registerName register1 tmp1
4413
4414         pk2   = registerRep register2
4415         code2 = registerCode register2 tmp2
4416         src2  = registerName register2 tmp2
4417
4418         code__2 dst =
4419                 if pk1 == pk2 then
4420                     code1 `appOL` code2 `snocOL`
4421                     instr (primRepToSize pk) src1 src2 dst
4422                 else if pk1 == F32 then
4423                     code1 `snocOL` promote src1 `appOL` code2 `snocOL`
4424                     instr DF tmp src2 dst
4425                 else
4426                     code1 `appOL` code2 `snocOL` promote src2 `snocOL`
4427                     instr DF src1 tmp dst
4428     in
4429     return (Any (if pk1 == pk2 then pk1 else F64) code__2)
4430
4431 ------------
4432 trivialUCode instr x
4433   = getRegister x               `thenNat` \ register ->
4434     getNewRegNat IntRep         `thenNat` \ tmp ->
4435     let
4436         code = registerCode register tmp
4437         src  = registerName register tmp
4438         code__2 dst = code `snocOL` instr (RIReg src) dst
4439     in
4440     return (Any IntRep code__2)
4441
4442 -------------
4443 trivialUFCode pk instr x
4444   = getRegister x               `thenNat` \ register ->
4445     getNewRegNat pk             `thenNat` \ tmp ->
4446     let
4447         code = registerCode register tmp
4448         src  = registerName register tmp
4449         code__2 dst = code `snocOL` instr src dst
4450     in
4451     return (Any pk code__2)
4452
4453 #endif /* sparc_TARGET_ARCH */
4454
4455 #if powerpc_TARGET_ARCH
4456
4457 {-
4458 Wolfgang's PowerPC version of The Rules:
4459
4460 A slightly modified version of The Rules to take advantage of the fact
4461 that PowerPC instructions work on all registers and don't implicitly
4462 clobber any fixed registers.
4463
4464 * The only expression for which getRegister returns Fixed is (CmmReg reg).
4465
4466 * If getRegister returns Any, then the code it generates may modify only:
4467         (a) fresh temporaries
4468         (b) the destination register
4469   It may *not* modify global registers, unless the global
4470   register happens to be the destination register.
4471   It may not clobber any other registers. In fact, only ccalls clobber any
4472   fixed registers.
4473   Also, it may not modify the counter register (used by genCCall).
4474   
4475   Corollary: If a getRegister for a subexpression returns Fixed, you need
4476   not move it to a fresh temporary before evaluating the next subexpression.
4477   The Fixed register won't be modified.
4478   Therefore, we don't need a counterpart for the x86's getStableReg on PPC.
4479   
4480 * SDM's First Rule is valid for PowerPC, too: subexpressions can depend on
4481   the value of the destination register.
4482 -}
4483
4484 trivialCode rep signed instr x (CmmLit (CmmInt y _))
4485     | Just imm <- makeImmediate rep signed y 
4486     = do
4487         (src1, code1) <- getSomeReg x
4488         let code dst = code1 `snocOL` instr dst src1 (RIImm imm)
4489         return (Any rep code)
4490   
4491 trivialCode rep signed instr x y = do
4492     (src1, code1) <- getSomeReg x
4493     (src2, code2) <- getSomeReg y
4494     let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2)
4495     return (Any rep code)
4496
4497 trivialCodeNoImm :: MachRep -> (Reg -> Reg -> Reg -> Instr)
4498     -> CmmExpr -> CmmExpr -> NatM Register
4499 trivialCodeNoImm rep instr x y = do
4500     (src1, code1) <- getSomeReg x
4501     (src2, code2) <- getSomeReg y
4502     let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2
4503     return (Any rep code)
4504     
4505 trivialUCode rep instr x = do
4506     (src, code) <- getSomeReg x
4507     let code' dst = code `snocOL` instr dst src
4508     return (Any rep code')
4509     
4510 -- There is no "remainder" instruction on the PPC, so we have to do
4511 -- it the hard way.
4512 -- The "div" parameter is the division instruction to use (DIVW or DIVWU)
4513
4514 remainderCode :: MachRep -> (Reg -> Reg -> Reg -> Instr)
4515     -> CmmExpr -> CmmExpr -> NatM Register
4516 remainderCode rep div x y = do
4517     (src1, code1) <- getSomeReg x
4518     (src2, code2) <- getSomeReg y
4519     let code dst = code1 `appOL` code2 `appOL` toOL [
4520                 div dst src1 src2,
4521                 MULLW dst dst (RIReg src2),
4522                 SUBF dst dst src1
4523             ]
4524     return (Any rep code)
4525
4526 #endif /* powerpc_TARGET_ARCH */
4527
4528
4529 -- -----------------------------------------------------------------------------
4530 --  Coercing to/from integer/floating-point...
4531
4532 -- @coerce(Int2FP|FP2Int)@ are more complicated integer/float
4533 -- conversions.  We have to store temporaries in memory to move
4534 -- between the integer and the floating point register sets.
4535
4536 -- @coerceDbl2Flt@ and @coerceFlt2Dbl@ are done this way because we
4537 -- pretend, on sparc at least, that double and float regs are seperate
4538 -- kinds, so the value has to be computed into one kind before being
4539 -- explicitly "converted" to live in the other kind.
4540
4541 coerceInt2FP :: MachRep -> MachRep -> CmmExpr -> NatM Register
4542 coerceFP2Int :: MachRep -> MachRep -> CmmExpr -> NatM Register
4543
4544 #if sparc_TARGET_ARCH
4545 coerceDbl2Flt :: CmmExpr -> NatM Register
4546 coerceFlt2Dbl :: CmmExpr -> NatM Register
4547 #endif
4548
4549 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4550
4551 #if alpha_TARGET_ARCH
4552
4553 coerceInt2FP _ x
4554   = getRegister x               `thenNat` \ register ->
4555     getNewRegNat IntRep         `thenNat` \ reg ->
4556     let
4557         code = registerCode register reg
4558         src  = registerName register reg
4559
4560         code__2 dst = code . mkSeqInstrs [
4561             ST Q src (spRel 0),
4562             LD TF dst (spRel 0),
4563             CVTxy Q TF dst dst]
4564     in
4565     return (Any F64 code__2)
4566
4567 -------------
4568 coerceFP2Int x
4569   = getRegister x               `thenNat` \ register ->
4570     getNewRegNat F64    `thenNat` \ tmp ->
4571     let
4572         code = registerCode register tmp
4573         src  = registerName register tmp
4574
4575         code__2 dst = code . mkSeqInstrs [
4576             CVTxy TF Q src tmp,
4577             ST TF tmp (spRel 0),
4578             LD Q dst (spRel 0)]
4579     in
4580     return (Any IntRep code__2)
4581
4582 #endif /* alpha_TARGET_ARCH */
4583
4584 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4585
4586 #if i386_TARGET_ARCH
4587
4588 coerceInt2FP from to x = do
4589   (x_reg, x_code) <- getSomeReg x
4590   let
4591         opc  = case to of F32 -> GITOF; F64 -> GITOD
4592         code dst = x_code `snocOL` opc x_reg dst
4593         -- ToDo: works for non-I32 reps?
4594   -- in
4595   return (Any to code)
4596
4597 ------------
4598
4599 coerceFP2Int from to x = do
4600   (x_reg, x_code) <- getSomeReg x
4601   let
4602         opc  = case from of F32 -> GFTOI; F64 -> GDTOI
4603         code dst = x_code `snocOL` opc x_reg dst
4604         -- ToDo: works for non-I32 reps?
4605   -- in
4606   return (Any to code)
4607
4608 #endif /* i386_TARGET_ARCH */
4609
4610 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4611
4612 #if x86_64_TARGET_ARCH
4613
4614 coerceFP2Int from to x = do
4615   (x_op, x_code) <- getOperand x  -- ToDo: could be a safe operand
4616   let
4617         opc  = case from of F32 -> CVTSS2SI; F64 -> CVTSD2SI
4618         code dst = x_code `snocOL` opc x_op dst
4619   -- in
4620   return (Any to code) -- works even if the destination rep is <I32
4621
4622 coerceInt2FP from to x = do
4623   (x_op, x_code) <- getOperand x  -- ToDo: could be a safe operand
4624   let
4625         opc  = case to of F32 -> CVTSI2SS; F64 -> CVTSI2SD
4626         code dst = x_code `snocOL` opc x_op dst
4627   -- in
4628   return (Any to code) -- works even if the destination rep is <I32
4629
4630 coerceFP2FP :: MachRep -> CmmExpr -> NatM Register
4631 coerceFP2FP to x = do
4632   (x_reg, x_code) <- getSomeReg x
4633   let
4634         opc  = case to of F32 -> CVTSD2SS; F64 -> CVTSS2SD
4635         code dst = x_code `snocOL` opc x_reg dst
4636   -- in
4637   return (Any to code)
4638
4639 #endif
4640
4641 -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4642
4643 #if sparc_TARGET_ARCH
4644
4645 coerceInt2FP pk x
4646   = getRegister x               `thenNat` \ register ->
4647     getNewRegNat IntRep         `thenNat` \ reg ->
4648     let
4649         code = registerCode register reg
4650         src  = registerName register reg
4651
4652         code__2 dst = code `appOL` toOL [
4653             ST W src (spRel (-2)),
4654             LD W (spRel (-2)) dst,
4655             FxTOy W (primRepToSize pk) dst dst]
4656     in
4657     return (Any pk code__2)
4658
4659 ------------
4660 coerceFP2Int fprep x
4661   = ASSERT(fprep == F64 || fprep == F32)
4662     getRegister x               `thenNat` \ register ->
4663     getNewRegNat fprep          `thenNat` \ reg ->
4664     getNewRegNat F32    `thenNat` \ tmp ->
4665     let
4666         code = registerCode register reg
4667         src  = registerName register reg
4668         code__2 dst = code `appOL` toOL [
4669             FxTOy (primRepToSize fprep) W src tmp,
4670             ST W tmp (spRel (-2)),
4671             LD W (spRel (-2)) dst]
4672     in
4673     return (Any IntRep code__2)
4674
4675 ------------
4676 coerceDbl2Flt x
4677   = getRegister x               `thenNat` \ register ->
4678     getNewRegNat F64    `thenNat` \ tmp ->
4679     let code = registerCode register tmp
4680         src  = registerName register tmp
4681     in
4682         return (Any F32 
4683                        (\dst -> code `snocOL` FxTOy DF F src dst)) 
4684
4685 ------------
4686 coerceFlt2Dbl x
4687   = getRegister x               `thenNat` \ register ->
4688     getNewRegNat F32    `thenNat` \ tmp ->
4689     let code = registerCode register tmp
4690         src  = registerName register tmp
4691     in
4692         return (Any F64
4693                        (\dst -> code `snocOL` FxTOy F DF src dst)) 
4694
4695 #endif /* sparc_TARGET_ARCH */
4696
4697 #if powerpc_TARGET_ARCH
4698 coerceInt2FP fromRep toRep x = do
4699     (src, code) <- getSomeReg x
4700     lbl <- getNewLabelNat
4701     itmp <- getNewRegNat I32
4702     ftmp <- getNewRegNat F64
4703     dynRef <- cmmMakeDynamicReference addImportNat False lbl
4704     Amode addr addr_code <- getAmode dynRef
4705     let
4706         code' dst = code `appOL` maybe_exts `appOL` toOL [
4707                 LDATA ReadOnlyData
4708                                 [CmmDataLabel lbl,
4709                                  CmmStaticLit (CmmInt 0x43300000 I32),
4710                                  CmmStaticLit (CmmInt 0x80000000 I32)],
4711                 XORIS itmp src (ImmInt 0x8000),
4712                 ST I32 itmp (spRel 3),
4713                 LIS itmp (ImmInt 0x4330),
4714                 ST I32 itmp (spRel 2),
4715                 LD F64 ftmp (spRel 2)
4716             ] `appOL` addr_code `appOL` toOL [
4717                 LD F64 dst addr,
4718                 FSUB F64 dst ftmp dst
4719             ] `appOL` maybe_frsp dst
4720             
4721         maybe_exts = case fromRep of
4722                         I8 ->  unitOL $ EXTS I8 src src
4723                         I16 -> unitOL $ EXTS I16 src src
4724                         I32 -> nilOL
4725         maybe_frsp dst = case toRep of
4726                         F32 -> unitOL $ FRSP dst dst
4727                         F64 -> nilOL
4728     return (Any toRep code')
4729
4730 coerceFP2Int fromRep toRep x = do
4731     -- the reps don't really matter: F*->F64 and I32->I* are no-ops
4732     (src, code) <- getSomeReg x
4733     tmp <- getNewRegNat F64
4734     let
4735         code' dst = code `appOL` toOL [
4736                 -- convert to int in FP reg
4737             FCTIWZ tmp src,
4738                 -- store value (64bit) from FP to stack
4739             ST F64 tmp (spRel 2),
4740                 -- read low word of value (high word is undefined)
4741             LD I32 dst (spRel 3)]       
4742     return (Any toRep code')
4743 #endif /* powerpc_TARGET_ARCH */
4744
4745
4746 -- -----------------------------------------------------------------------------
4747 -- eXTRA_STK_ARGS_HERE
4748
4749 -- We (allegedly) put the first six C-call arguments in registers;
4750 -- where do we start putting the rest of them?
4751
4752 -- Moved from MachInstrs (SDM):
4753
4754 #if alpha_TARGET_ARCH || sparc_TARGET_ARCH
4755 eXTRA_STK_ARGS_HERE :: Int
4756 eXTRA_STK_ARGS_HERE
4757   = IF_ARCH_alpha(0, IF_ARCH_sparc(23, ???))
4758 #endif
4759