Instr.hs 31.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
-----------------------------------------------------------------------------
--
-- Machine-dependent assembly language
--
-- (c) The University of Glasgow 1993-2004
--
-----------------------------------------------------------------------------

#include "HsVersions.h"
#include "nativeGen/NCG.h"

12 13 14 15
module X86.Instr (Instr(..), Operand(..),
                  getJumpDestBlockId, canShortcut, shortcutStatics,
                  shortcutJump, i386_insert_ffrees,
                  maxSpillSlots, archWordSize)
16 17
where

18
import X86.Cond
19
import X86.Regs
20 21 22 23
import Instruction
import Size
import RegClass
import Reg
24
import TargetReg
25 26

import BlockId
27
import OldCmm
28
import FastString
29
import FastBool
30
import Outputable
31
import Platform
Ian Lynagh's avatar
Ian Lynagh committed
32
import Constants        (rESERVED_C_STACK_BYTES)
33

34
import BasicTypes       (Alignment)
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
35
import CLabel
36 37
import UniqSet
import Unique
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
38

Ian Lynagh's avatar
Ian Lynagh committed
39
-- Size of an x86/x86_64 memory address, in bytes.
40
--
Ian Lynagh's avatar
Ian Lynagh committed
41 42 43 44
archWordSize :: Bool -> Size
archWordSize is32Bit
 | is32Bit   = II32
 | otherwise = II64
45 46 47

-- | Instruction instance for x86 instruction set.
instance Instruction Instr where
Ian Lynagh's avatar
Ian Lynagh committed
48 49 50 51 52 53 54 55 56 57 58 59
        regUsageOfInstr         = x86_regUsageOfInstr
        patchRegsOfInstr        = x86_patchRegsOfInstr
        isJumpishInstr          = x86_isJumpishInstr
        jumpDestsOfInstr        = x86_jumpDestsOfInstr
        patchJumpInstr          = x86_patchJumpInstr
        mkSpillInstr            = x86_mkSpillInstr
        mkLoadInstr             = x86_mkLoadInstr
        takeDeltaInstr          = x86_takeDeltaInstr
        isMetaInstr             = x86_isMetaInstr
        mkRegRegMoveInstr       = x86_mkRegRegMoveInstr
        takeRegRegMoveInstr     = x86_takeRegRegMoveInstr
        mkJumpInstr             = x86_mkJumpInstr
60 61 62 63 64 65 66 67 68 69 70 71 72 73


-- -----------------------------------------------------------------------------
-- Intel x86 instructions

{-
Intel, in their infinite wisdom, selected a stack model for floating
point registers on x86.  That might have made sense back in 1979 --
nowadays we can see it for the nonsense it really is.  A stack model
fits poorly with the existing nativeGen infrastructure, which assumes
flat integer and FP register sets.  Prior to this commit, nativeGen
could not generate correct x86 FP code -- to do so would have meant
somehow working the register-stack paradigm into the register
allocator and spiller, which sounds very difficult.
Ian Lynagh's avatar
Ian Lynagh committed
74

75 76 77 78 79 80 81 82 83
We have decided to cheat, and go for a simple fix which requires no
infrastructure modifications, at the expense of generating ropey but
correct FP code.  All notions of the x86 FP stack and its insns have
been removed.  Instead, we pretend (to the instruction selector and
register allocator) that x86 has six floating point registers, %fake0
.. %fake5, which can be used in the usual flat manner.  We further
claim that x86 has floating point instructions very similar to SPARC
and Alpha, that is, a simple 3-operand register-register arrangement.
Code generation and register allocation proceed on this basis.
Ian Lynagh's avatar
Ian Lynagh committed
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
When we come to print out the final assembly, our convenient fiction
is converted to dismal reality.  Each fake instruction is
independently converted to a series of real x86 instructions.
%fake0 .. %fake5 are mapped to %st(0) .. %st(5).  To do reg-reg
arithmetic operations, the two operands are pushed onto the top of the
FP stack, the operation done, and the result copied back into the
relevant register.  There are only six %fake registers because 2 are
needed for the translation, and x86 has 8 in total.

The translation is inefficient but is simple and it works.  A cleverer
translation would handle a sequence of insns, simulating the FP stack
contents, would not impose a fixed mapping from %fake to %st regs, and
hopefully could avoid most of the redundant reg-reg moves of the
current translation.

We might as well make use of whatever unique FP facilities Intel have
chosen to bless us with (let's not be churlish, after all).
Hence GLDZ and GLD1.  Bwahahahahahahaha!
-}

{-
Simon Marlow's avatar
Simon Marlow committed
106
Note [x86 Floating point precision]
107 108 109 110 111 112 113 114 115 116 117 118 119

Intel's internal floating point registers are by default 80 bit
extended precision.  This means that all operations done on values in
registers are done at 80 bits, and unless the intermediate values are
truncated to the appropriate size (32 or 64 bits) by storing in
memory, calculations in registers will give different results from
calculations which pass intermediate values in memory (eg. via
function calls).

One solution is to set the FPU into 64 bit precision mode.  Some OSs
do this (eg. FreeBSD) and some don't (eg. Linux).  The problem here is
that this will only affect 64-bit precision arithmetic; 32-bit
calculations will still be done at 64-bit precision in registers.  So
Ian Lynagh's avatar
Ian Lynagh committed
120
it doesn't solve the whole problem.
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

There's also the issue of what the C library is expecting in terms of
precision.  It seems to be the case that glibc on Linux expects the
FPU to be set to 80 bit precision, so setting it to 64 bit could have
unexpected effects.  Changing the default could have undesirable
effects on other 3rd-party library code too, so the right thing would
be to save/restore the FPU control word across Haskell code if we were
to do this.

gcc's -ffloat-store gives consistent results by always storing the
results of floating-point calculations in memory, which works for both
32 and 64-bit precision.  However, it only affects the values of
user-declared floating point variables in C, not intermediate results.
GHC in -fvia-C mode uses -ffloat-store (see the -fexcess-precision
flag).

Another problem is how to spill floating point registers in the
register allocator.  Should we spill the whole 80 bits, or just 64?
On an OS which is set to 64 bit precision, spilling 64 is fine.  On
Linux, spilling 64 bits will round the results of some operations.
This is what gcc does.  Spilling at 80 bits requires taking up a full
128 bit slot (so we get alignment).  We spill at 80-bits and ignore
the alignment problems.

Simon Marlow's avatar
Simon Marlow committed
145 146 147 148 149 150
In the future [edit: now available in GHC 7.0.1, with the -msse2
flag], we'll use the SSE registers for floating point.  This requires
a CPU that supports SSE2 (ordinary SSE only supports 32 bit precision
float ops), which means P4 or Xeon and above.  Using SSE will solve
all these problems, because the SSE registers use fixed 32 bit or 64
bit precision.
151 152 153 154 155

--SDM 1/2003
-}

data Instr
Ian Lynagh's avatar
Ian Lynagh committed
156 157
        -- comment pseudo-op
        = COMMENT FastString
158

Ian Lynagh's avatar
Ian Lynagh committed
159 160 161 162
        -- some static data spat out during code
        -- generation.  Will be extracted before
        -- pretty-printing.
        | LDATA   Section (Alignment, CmmStatics)
163

Ian Lynagh's avatar
Ian Lynagh committed
164 165 166 167 168
        -- start a new basic block.  Useful during
        -- codegen, removed later.  Preceding
        -- instruction should be a jump, as per the
        -- invariants for a BasicBlock (see Cmm).
        | NEWBLOCK BlockId
169

Ian Lynagh's avatar
Ian Lynagh committed
170
        -- specify current stack offset for
171
        -- benefit of subsequent passes
Ian Lynagh's avatar
Ian Lynagh committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        | DELTA   Int

        -- Moves.
        | MOV         Size Operand Operand
        | MOVZxL      Size Operand Operand -- size is the size of operand 1
        | MOVSxL      Size Operand Operand -- size is the size of operand 1
        -- x86_64 note: plain mov into a 32-bit register always zero-extends
        -- into the 64-bit reg, in contrast to the 8 and 16-bit movs which
        -- don't affect the high bits of the register.

        -- Load effective address (also a very useful three-operand add instruction :-)
        | LEA         Size Operand Operand

        -- Int Arithmetic.
        | ADD         Size Operand Operand
        | ADC         Size Operand Operand
        | SUB         Size Operand Operand

        | MUL         Size Operand Operand
191
        | MUL2        Size Operand              -- %edx:%eax = operand * %rax
Ian Lynagh's avatar
Ian Lynagh committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        | IMUL        Size Operand Operand      -- signed int mul
        | IMUL2       Size Operand              -- %edx:%eax = operand * %eax

        | DIV         Size Operand              -- eax := eax:edx/op, edx := eax:edx%op
        | IDIV        Size Operand              -- ditto, but signed

        -- Simple bit-twiddling.
        | AND         Size Operand Operand
        | OR          Size Operand Operand
        | XOR         Size Operand Operand
        | NOT         Size Operand
        | NEGI        Size Operand              -- NEG instruction (name clash with Cond)

        -- Shifts (amount may be immediate or %cl only)
        | SHL         Size Operand{-amount-} Operand
        | SAR         Size Operand{-amount-} Operand
        | SHR         Size Operand{-amount-} Operand
209 210

        | BT          Size Imm Operand
Ian Lynagh's avatar
Ian Lynagh committed
211
        | NOP
212

Ian Lynagh's avatar
Ian Lynagh committed
213 214 215
        -- x86 Float Arithmetic.
        -- Note that we cheat by treating G{ABS,MOV,NEG} of doubles
        -- as single instructions right up until we spit them out.
216 217 218
        -- all the 3-operand fake fp insns are src1 src2 dst
        -- and furthermore are constrained to be fp regs only.
        -- IMPORTANT: keep is_G_insn up to date with any changes here
Ian Lynagh's avatar
Ian Lynagh committed
219
        | GMOV        Reg Reg -- src(fpreg), dst(fpreg)
220 221
        | GLD         Size AddrMode Reg -- src, dst(fpreg)
        | GST         Size Reg AddrMode -- src(fpreg), dst
Ian Lynagh's avatar
Ian Lynagh committed
222

223 224
        | GLDZ        Reg -- dst(fpreg)
        | GLD1        Reg -- dst(fpreg)
Ian Lynagh's avatar
Ian Lynagh committed
225

226 227
        | GFTOI       Reg Reg -- src(fpreg), dst(intreg)
        | GDTOI       Reg Reg -- src(fpreg), dst(intreg)
Ian Lynagh's avatar
Ian Lynagh committed
228

229 230
        | GITOF       Reg Reg -- src(intreg), dst(fpreg)
        | GITOD       Reg Reg -- src(intreg), dst(fpreg)
Ian Lynagh's avatar
Ian Lynagh committed
231

232 233
        | GDTOF       Reg Reg -- src(fpreg), dst(fpreg)

Ian Lynagh's avatar
Ian Lynagh committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        | GADD        Size Reg Reg Reg -- src1, src2, dst
        | GDIV        Size Reg Reg Reg -- src1, src2, dst
        | GSUB        Size Reg Reg Reg -- src1, src2, dst
        | GMUL        Size Reg Reg Reg -- src1, src2, dst

                -- FP compare.  Cond must be `elem` [EQQ, NE, LE, LTT, GE, GTT]
                -- Compare src1 with src2; set the Zero flag iff the numbers are
                -- comparable and the comparison is True.  Subsequent code must
                -- test the %eflags zero flag regardless of the supplied Cond.
        | GCMP        Cond Reg Reg -- src1, src2

        | GABS        Size Reg Reg -- src, dst
        | GNEG        Size Reg Reg -- src, dst
        | GSQRT       Size Reg Reg -- src, dst
        | GSIN        Size CLabel CLabel Reg Reg -- src, dst
        | GCOS        Size CLabel CLabel Reg Reg -- src, dst
        | GTAN        Size CLabel CLabel Reg Reg -- src, dst

252 253 254
        | GFREE         -- do ffree on all x86 regs; an ugly hack


Ian Lynagh's avatar
Ian Lynagh committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        -- SSE2 floating point: we use a restricted set of the available SSE2
        -- instructions for floating-point.
        -- use MOV for moving (either movss or movsd (movlpd better?))
        | CVTSS2SD      Reg Reg         -- F32 to F64
        | CVTSD2SS      Reg Reg         -- F64 to F32
        | CVTTSS2SIQ    Size Operand Reg -- F32 to I32/I64 (with truncation)
        | CVTTSD2SIQ    Size Operand Reg -- F64 to I32/I64 (with truncation)
        | CVTSI2SS      Size Operand Reg -- I32/I64 to F32
        | CVTSI2SD      Size Operand Reg -- I32/I64 to F64

        -- use ADD & SUB for arithmetic.  In both cases, operands
        -- are  Operand Reg.

        -- SSE2 floating-point division:
        | FDIV          Size Operand Operand   -- divisor, dividend(dst)

        -- use CMP for comparisons.  ucomiss and ucomisd instructions
        -- compare single/double prec floating point respectively.

        | SQRT          Size Operand Reg        -- src, dst


        -- Comparison
        | TEST          Size Operand Operand
        | CMP           Size Operand Operand
        | SETCC         Cond Operand

        -- Stack Operations.
        | PUSH          Size Operand
        | POP           Size Operand
        -- both unused (SDM):
        --  | PUSHA
        --  | POPA

        -- Jumping around.
        | JMP         Operand
        | JXX         Cond BlockId  -- includes unconditional branches
        | JXX_GBL     Cond Imm      -- non-local version of JXX
        -- Table jump
        | JMP_TBL     Operand   -- Address to jump to
                      [Maybe BlockId] -- Blocks in the jump table
                      Section   -- Data section jump table should be put in
                      CLabel    -- Label of jump table
        | CALL        (Either Imm Reg) [Reg]

        -- Other things.
        | CLTD Size              -- sign extend %eax into %edx:%eax

        | FETCHGOT    Reg        -- pseudo-insn for ELF position-independent code
                                 -- pretty-prints as
                                 --       call 1f
                                 -- 1:    popl %reg
                                 --       addl __GLOBAL_OFFSET_TABLE__+.-1b, %reg
        | FETCHPC     Reg        -- pseudo-insn for Darwin position-independent code
                                 -- pretty-prints as
                                 --       call 1f
                                 -- 1:    popl %reg

tibbe's avatar
tibbe committed
313 314
    -- SSE4.2
    | POPCNT      Size Operand Reg -- src, dst
315 316

data Operand
Ian Lynagh's avatar
Ian Lynagh committed
317 318 319
        = OpReg  Reg            -- register
        | OpImm  Imm            -- immediate value
        | OpAddr AddrMode       -- memory reference
320 321


322

323
x86_regUsageOfInstr :: Instr -> RegUsage
Ian Lynagh's avatar
Ian Lynagh committed
324
x86_regUsageOfInstr instr
325
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
326 327 328 329 330 331 332 333
    MOV    _ src dst    -> usageRW src dst
    MOVZxL _ src dst    -> usageRW src dst
    MOVSxL _ src dst    -> usageRW src dst
    LEA    _ src dst    -> usageRW src dst
    ADD    _ src dst    -> usageRM src dst
    ADC    _ src dst    -> usageRM src dst
    SUB    _ src dst    -> usageRM src dst
    IMUL   _ src dst    -> usageRM src dst
Simon Marlow's avatar
Simon Marlow committed
334
    IMUL2  _ src       -> mkRU (eax:use_R src []) [eax,edx]
Ian Lynagh's avatar
Ian Lynagh committed
335
    MUL    _ src dst    -> usageRM src dst
336
    MUL2   _ src        -> mkRU (eax:use_R src []) [eax,edx]
Simon Marlow's avatar
Simon Marlow committed
337 338
    DIV    _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
    IDIV   _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
Ian Lynagh's avatar
Ian Lynagh committed
339 340
    AND    _ src dst    -> usageRM src dst
    OR     _ src dst    -> usageRM src dst
341 342 343 344

    XOR    _ (OpReg src) (OpReg dst)
        | src == dst    -> mkRU [] [dst]

Ian Lynagh's avatar
Ian Lynagh committed
345 346 347 348 349 350
    XOR    _ src dst    -> usageRM src dst
    NOT    _ op         -> usageM op
    NEGI   _ op         -> usageM op
    SHL    _ imm dst    -> usageRM imm dst
    SAR    _ imm dst    -> usageRM imm dst
    SHR    _ imm dst    -> usageRM imm dst
Simon Marlow's avatar
Simon Marlow committed
351
    BT     _ _   src    -> mkRUR (use_R src [])
Ian Lynagh's avatar
Ian Lynagh committed
352

Simon Marlow's avatar
Simon Marlow committed
353
    PUSH   _ op         -> mkRUR (use_R op [])
Ian Lynagh's avatar
Ian Lynagh committed
354
    POP    _ op         -> mkRU [] (def_W op)
Simon Marlow's avatar
Simon Marlow committed
355 356
    TEST   _ src dst    -> mkRUR (use_R src $! use_R dst [])
    CMP    _ src dst    -> mkRUR (use_R src $! use_R dst [])
Ian Lynagh's avatar
Ian Lynagh committed
357 358 359
    SETCC  _ op         -> mkRU [] (def_W op)
    JXX    _ _          -> mkRU [] []
    JXX_GBL _ _         -> mkRU [] []
Simon Marlow's avatar
Simon Marlow committed
360 361
    JMP     op          -> mkRUR (use_R op [])
    JMP_TBL op _ _ _    -> mkRUR (use_R op [])
362 363
    CALL (Left _)  params   -> mkRU params callClobberedRegs
    CALL (Right reg) params -> mkRU (reg:params) callClobberedRegs
Ian Lynagh's avatar
Ian Lynagh committed
364 365
    CLTD   _            -> mkRU [eax] [edx]
    NOP                 -> mkRU [] []
366

Ian Lynagh's avatar
Ian Lynagh committed
367
    GMOV   src dst      -> mkRU [src] [dst]
Simon Marlow's avatar
Simon Marlow committed
368 369
    GLD    _ src dst    -> mkRU (use_EA src []) [dst]
    GST    _ src dst    -> mkRUR (src : use_EA dst [])
370

Ian Lynagh's avatar
Ian Lynagh committed
371 372
    GLDZ   dst          -> mkRU [] [dst]
    GLD1   dst          -> mkRU [] [dst]
373

Ian Lynagh's avatar
Ian Lynagh committed
374 375
    GFTOI  src dst      -> mkRU [src] [dst]
    GDTOI  src dst      -> mkRU [src] [dst]
376

Ian Lynagh's avatar
Ian Lynagh committed
377 378
    GITOF  src dst      -> mkRU [src] [dst]
    GITOD  src dst      -> mkRU [src] [dst]
379

Ian Lynagh's avatar
Ian Lynagh committed
380
    GDTOF  src dst      -> mkRU [src] [dst]
381

Ian Lynagh's avatar
Ian Lynagh committed
382 383 384 385
    GADD   _ s1 s2 dst  -> mkRU [s1,s2] [dst]
    GSUB   _ s1 s2 dst  -> mkRU [s1,s2] [dst]
    GMUL   _ s1 s2 dst  -> mkRU [s1,s2] [dst]
    GDIV   _ s1 s2 dst  -> mkRU [s1,s2] [dst]
386 387 388 389 390 391 392 393 394

    GCMP   _ src1 src2   -> mkRUR [src1,src2]
    GABS   _ src dst     -> mkRU [src] [dst]
    GNEG   _ src dst     -> mkRU [src] [dst]
    GSQRT  _ src dst     -> mkRU [src] [dst]
    GSIN   _ _ _ src dst -> mkRU [src] [dst]
    GCOS   _ _ _ src dst -> mkRU [src] [dst]
    GTAN   _ _ _ src dst -> mkRU [src] [dst]

Ian Lynagh's avatar
Ian Lynagh committed
395 396
    CVTSS2SD   src dst  -> mkRU [src] [dst]
    CVTSD2SS   src dst  -> mkRU [src] [dst]
Simon Marlow's avatar
Simon Marlow committed
397 398 399 400
    CVTTSS2SIQ _ src dst -> mkRU (use_R src []) [dst]
    CVTTSD2SIQ _ src dst -> mkRU (use_R src []) [dst]
    CVTSI2SS   _ src dst -> mkRU (use_R src []) [dst]
    CVTSI2SD   _ src dst -> mkRU (use_R src []) [dst]
Ian Lynagh's avatar
Ian Lynagh committed
401
    FDIV _     src dst  -> usageRM src dst
402 403 404 405

    FETCHGOT reg        -> mkRU [] [reg]
    FETCHPC  reg        -> mkRU [] [reg]

Ian Lynagh's avatar
Ian Lynagh committed
406
    COMMENT _           -> noUsage
407 408
    DELTA   _           -> noUsage

Simon Marlow's avatar
Simon Marlow committed
409
    POPCNT _ src dst -> mkRU (use_R src []) [dst]
tibbe's avatar
tibbe committed
410

Ian Lynagh's avatar
Ian Lynagh committed
411
    _other              -> panic "regUsage: unrecognised instr"
412 413 414 415

 where
    -- 2 operand form; first operand Read; second Written
    usageRW :: Operand -> Operand -> RegUsage
Simon Marlow's avatar
Simon Marlow committed
416 417
    usageRW op (OpReg reg)      = mkRU (use_R op []) [reg]
    usageRW op (OpAddr ea)      = mkRUR (use_R op $! use_EA ea [])
Ian Lynagh's avatar
Ian Lynagh committed
418
    usageRW _ _                 = panic "X86.RegInfo.usageRW: no match"
419 420 421

    -- 2 operand form; first operand Read; second Modified
    usageRM :: Operand -> Operand -> RegUsage
Simon Marlow's avatar
Simon Marlow committed
422 423
    usageRM op (OpReg reg)      = mkRU (use_R op [reg]) [reg]
    usageRM op (OpAddr ea)      = mkRUR (use_R op $! use_EA ea [])
Ian Lynagh's avatar
Ian Lynagh committed
424
    usageRM _ _                 = panic "X86.RegInfo.usageRM: no match"
425 426 427

    -- 1 operand form; operand Modified
    usageM :: Operand -> RegUsage
Ian Lynagh's avatar
Ian Lynagh committed
428
    usageM (OpReg reg)          = mkRU [reg] [reg]
Simon Marlow's avatar
Simon Marlow committed
429
    usageM (OpAddr ea)          = mkRUR (use_EA ea [])
Ian Lynagh's avatar
Ian Lynagh committed
430
    usageM _                    = panic "X86.RegInfo.usageM: no match"
431 432

    -- Registers defd when an operand is written.
Ian Lynagh's avatar
Ian Lynagh committed
433 434 435
    def_W (OpReg reg)           = [reg]
    def_W (OpAddr _ )           = []
    def_W _                     = panic "X86.RegInfo.def_W: no match"
436 437

    -- Registers used when an operand is read.
Simon Marlow's avatar
Simon Marlow committed
438 439 440
    use_R (OpReg reg)  tl = reg : tl
    use_R (OpImm _)    tl = tl
    use_R (OpAddr ea)  tl = use_EA ea tl
441 442

    -- Registers used to compute an effective address.
Simon Marlow's avatar
Simon Marlow committed
443 444 445 446 447 448 449
    use_EA (ImmAddr _ _) tl = tl
    use_EA (AddrBaseIndex base index _) tl =
        use_base base $! use_index index tl
        where use_base (EABaseReg r)  tl = r : tl
              use_base _              tl = tl
              use_index EAIndexNone   tl = tl
              use_index (EAIndex i _) tl = i : tl
450 451

    mkRUR src = src' `seq` RU src' []
Ian Lynagh's avatar
Ian Lynagh committed
452
        where src' = filter interesting src
453 454

    mkRU src dst = src' `seq` dst' `seq` RU src' dst'
Ian Lynagh's avatar
Ian Lynagh committed
455 456
        where src' = filter interesting src
              dst' = filter interesting dst
457 458

interesting :: Reg -> Bool
Ian Lynagh's avatar
Ian Lynagh committed
459 460 461
interesting (RegVirtual _)              = True
interesting (RegReal (RealRegSingle i)) = isFastTrue (freeReg i)
interesting (RegReal (RealRegPair{}))   = panic "X86.interesting: no reg pairs on this arch"
462 463 464 465



x86_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr
Ian Lynagh's avatar
Ian Lynagh committed
466
x86_patchRegsOfInstr instr env
467
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
468 469 470 471 472 473 474 475
    MOV  sz src dst     -> patch2 (MOV  sz) src dst
    MOVZxL sz src dst   -> patch2 (MOVZxL sz) src dst
    MOVSxL sz src dst   -> patch2 (MOVSxL sz) src dst
    LEA  sz src dst     -> patch2 (LEA  sz) src dst
    ADD  sz src dst     -> patch2 (ADD  sz) src dst
    ADC  sz src dst     -> patch2 (ADC  sz) src dst
    SUB  sz src dst     -> patch2 (SUB  sz) src dst
    IMUL sz src dst     -> patch2 (IMUL sz) src dst
476
    IMUL2 sz src        -> patch1 (IMUL2 sz) src
Ian Lynagh's avatar
Ian Lynagh committed
477
    MUL sz src dst      -> patch2 (MUL sz) src dst
478
    MUL2 sz src         -> patch1 (MUL2 sz) src
Ian Lynagh's avatar
Ian Lynagh committed
479 480 481 482 483 484 485 486 487 488
    IDIV sz op          -> patch1 (IDIV sz) op
    DIV sz op           -> patch1 (DIV sz) op
    AND  sz src dst     -> patch2 (AND  sz) src dst
    OR   sz src dst     -> patch2 (OR   sz) src dst
    XOR  sz src dst     -> patch2 (XOR  sz) src dst
    NOT  sz op          -> patch1 (NOT  sz) op
    NEGI sz op          -> patch1 (NEGI sz) op
    SHL  sz imm dst     -> patch1 (SHL sz imm) dst
    SAR  sz imm dst     -> patch1 (SAR sz imm) dst
    SHR  sz imm dst     -> patch1 (SHR sz imm) dst
489
    BT   sz imm src     -> patch1 (BT  sz imm) src
Ian Lynagh's avatar
Ian Lynagh committed
490 491 492 493 494 495
    TEST sz src dst     -> patch2 (TEST sz) src dst
    CMP  sz src dst     -> patch2 (CMP  sz) src dst
    PUSH sz op          -> patch1 (PUSH sz) op
    POP  sz op          -> patch1 (POP  sz) op
    SETCC cond op       -> patch1 (SETCC cond) op
    JMP op              -> patch1 JMP op
496
    JMP_TBL op ids s lbl-> JMP_TBL (patchOp op) ids s lbl
497

Ian Lynagh's avatar
Ian Lynagh committed
498 499 500
    GMOV src dst        -> GMOV (env src) (env dst)
    GLD  sz src dst     -> GLD sz (lookupAddr src) (env dst)
    GST  sz src dst     -> GST sz (env src) (lookupAddr dst)
501

Ian Lynagh's avatar
Ian Lynagh committed
502 503
    GLDZ dst            -> GLDZ (env dst)
    GLD1 dst            -> GLD1 (env dst)
504

Ian Lynagh's avatar
Ian Lynagh committed
505 506
    GFTOI src dst       -> GFTOI (env src) (env dst)
    GDTOI src dst       -> GDTOI (env src) (env dst)
507

Ian Lynagh's avatar
Ian Lynagh committed
508 509
    GITOF src dst       -> GITOF (env src) (env dst)
    GITOD src dst       -> GITOD (env src) (env dst)
510

Ian Lynagh's avatar
Ian Lynagh committed
511
    GDTOF src dst       -> GDTOF (env src) (env dst)
512

Ian Lynagh's avatar
Ian Lynagh committed
513 514 515 516
    GADD sz s1 s2 dst   -> GADD sz (env s1) (env s2) (env dst)
    GSUB sz s1 s2 dst   -> GSUB sz (env s1) (env s2) (env dst)
    GMUL sz s1 s2 dst   -> GMUL sz (env s1) (env s2) (env dst)
    GDIV sz s1 s2 dst   -> GDIV sz (env s1) (env s2) (env dst)
517

Ian Lynagh's avatar
Ian Lynagh committed
518 519 520 521 522 523 524
    GCMP sz src1 src2   -> GCMP sz (env src1) (env src2)
    GABS sz src dst     -> GABS sz (env src) (env dst)
    GNEG sz src dst     -> GNEG sz (env src) (env dst)
    GSQRT sz src dst    -> GSQRT sz (env src) (env dst)
    GSIN sz l1 l2 src dst       -> GSIN sz l1 l2 (env src) (env dst)
    GCOS sz l1 l2 src dst       -> GCOS sz l1 l2 (env src) (env dst)
    GTAN sz l1 l2 src dst       -> GTAN sz l1 l2 (env src) (env dst)
525

Ian Lynagh's avatar
Ian Lynagh committed
526 527
    CVTSS2SD src dst    -> CVTSS2SD (env src) (env dst)
    CVTSD2SS src dst    -> CVTSD2SS (env src) (env dst)
528 529
    CVTTSS2SIQ sz src dst -> CVTTSS2SIQ sz (patchOp src) (env dst)
    CVTTSD2SIQ sz src dst -> CVTTSD2SIQ sz (patchOp src) (env dst)
Ian Lynagh's avatar
Ian Lynagh committed
530 531 532 533 534 535
    CVTSI2SS sz src dst -> CVTSI2SS sz (patchOp src) (env dst)
    CVTSI2SD sz src dst -> CVTSI2SD sz (patchOp src) (env dst)
    FDIV sz src dst     -> FDIV sz (patchOp src) (patchOp dst)

    CALL (Left _)  _    -> instr
    CALL (Right reg) p  -> CALL (Right (env reg)) p
536 537 538 539

    FETCHGOT reg        -> FETCHGOT (env reg)
    FETCHPC  reg        -> FETCHPC  (env reg)

Ian Lynagh's avatar
Ian Lynagh committed
540 541 542 543 544 545 546
    NOP                 -> instr
    COMMENT _           -> instr
    DELTA _             -> instr

    JXX _ _             -> instr
    JXX_GBL _ _         -> instr
    CLTD _              -> instr
547

tibbe's avatar
tibbe committed
548 549
    POPCNT sz src dst -> POPCNT sz (patchOp src) (env dst)

Ian Lynagh's avatar
Ian Lynagh committed
550
    _other              -> panic "patchRegs: unrecognised instr"
551 552

  where
553
    patch1 :: (Operand -> a) -> Operand -> a
554
    patch1 insn op      = insn $! patchOp op
555
    patch2 :: (Operand -> Operand -> a) -> Operand -> Operand -> a
556 557 558 559 560 561 562 563 564 565
    patch2 insn src dst = (insn $! patchOp src) $! patchOp dst

    patchOp (OpReg  reg) = OpReg $! env reg
    patchOp (OpImm  imm) = OpImm imm
    patchOp (OpAddr ea)  = OpAddr $! lookupAddr ea

    lookupAddr (ImmAddr imm off) = ImmAddr imm off
    lookupAddr (AddrBaseIndex base index disp)
      = ((AddrBaseIndex $! lookupBase base) $! lookupIndex index) disp
      where
Ian Lynagh's avatar
Ian Lynagh committed
566 567
        lookupBase EABaseNone       = EABaseNone
        lookupBase EABaseRip        = EABaseRip
Simon Marlow's avatar
Simon Marlow committed
568
        lookupBase (EABaseReg r)    = EABaseReg $! env r
Ian Lynagh's avatar
Ian Lynagh committed
569 570

        lookupIndex EAIndexNone     = EAIndexNone
Simon Marlow's avatar
Simon Marlow committed
571
        lookupIndex (EAIndex r i)   = (EAIndex $! env r) i
572 573 574


--------------------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
575 576
x86_isJumpishInstr
        :: Instr -> Bool
577 578 579

x86_isJumpishInstr instr
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
580 581 582 583 584 585
        JMP{}           -> True
        JXX{}           -> True
        JXX_GBL{}       -> True
        JMP_TBL{}       -> True
        CALL{}          -> True
        _               -> False
586 587 588


x86_jumpDestsOfInstr
Ian Lynagh's avatar
Ian Lynagh committed
589 590
        :: Instr
        -> [BlockId]
591

Ian Lynagh's avatar
Ian Lynagh committed
592
x86_jumpDestsOfInstr insn
593
  = case insn of
Ian Lynagh's avatar
Ian Lynagh committed
594 595 596
        JXX _ id        -> [id]
        JMP_TBL _ ids _ _ -> [id | Just id <- ids]
        _               -> []
597 598


Ian Lynagh's avatar
Ian Lynagh committed
599 600
x86_patchJumpInstr
        :: Instr -> (BlockId -> BlockId) -> Instr
601 602 603

x86_patchJumpInstr insn patchF
  = case insn of
Ian Lynagh's avatar
Ian Lynagh committed
604 605 606 607
        JXX cc id       -> JXX cc (patchF id)
        JMP_TBL op ids section lbl
          -> JMP_TBL op (map (fmap patchF) ids) section lbl
        _               -> insn
608 609 610 611 612 613 614




-- -----------------------------------------------------------------------------
-- | Make a spill instruction.
x86_mkSpillInstr
615 616 617 618 619
    :: Platform
    -> Reg      -- register to spill
    -> Int      -- current stack delta
    -> Int      -- spill slot to use
    -> Instr
620

621
x86_mkSpillInstr platform reg delta slot
622
  = let off     = spillSlotToOffset is32Bit slot
623
    in
624
    let off_w = (off - delta) `div` (if is32Bit then 4 else 8)
625
    in case targetClassOfReg platform reg of
626
           RcInteger   -> MOV (archWordSize is32Bit)
Ian Lynagh's avatar
Ian Lynagh committed
627
                              (OpReg reg) (OpAddr (spRel platform off_w))
Ian Lynagh's avatar
Ian Lynagh committed
628 629
           RcDouble    -> GST FF80 reg (spRel platform off_w) {- RcFloat/RcDouble -}
           RcDoubleSSE -> MOV FF64 (OpReg reg) (OpAddr (spRel platform off_w))
630
           _         -> panic "X86.mkSpillInstr: no match"
631
    where is32Bit = target32Bit platform
632 633 634

-- | Make a spill reload instruction.
x86_mkLoadInstr
635 636 637 638 639
    :: Platform
    -> Reg      -- register to load
    -> Int      -- current stack delta
    -> Int      -- spill slot to use
    -> Instr
640

641
x86_mkLoadInstr platform reg delta slot
642
  = let off     = spillSlotToOffset is32Bit slot
643
    in
644
        let off_w = (off-delta) `div` (if is32Bit then 4 else 8)
645
        in case targetClassOfReg platform reg of
646
              RcInteger -> MOV (archWordSize is32Bit)
Ian Lynagh's avatar
Ian Lynagh committed
647 648 649
                               (OpAddr (spRel platform off_w)) (OpReg reg)
              RcDouble  -> GLD FF80 (spRel platform off_w) reg {- RcFloat/RcDouble -}
              RcDoubleSSE -> MOV FF64 (OpAddr (spRel platform off_w)) (OpReg reg)
650
              _           -> panic "X86.x86_mkLoadInstr"
651
    where is32Bit = target32Bit platform
652

653 654
spillSlotSize :: Bool -> Int
spillSlotSize is32Bit = if is32Bit then 12 else 8
655

656 657 658
maxSpillSlots :: Bool -> Int
maxSpillSlots is32Bit
    = ((rESERVED_C_STACK_BYTES - 64) `div` spillSlotSize is32Bit) - 1
659 660 661 662

-- convert a spill slot number to a *byte* offset, with no sign:
-- decide on a per arch basis whether you are spilling above or below
-- the C stack pointer.
663 664 665 666
spillSlotToOffset :: Bool -> Int -> Int
spillSlotToOffset is32Bit slot
   | slot >= 0 && slot < maxSpillSlots is32Bit
   = 64 + spillSlotSize is32Bit * slot
667
   | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
668
   = pprPanic "spillSlotToOffset:"
669
              (   text "invalid spill location: " <> int slot
670
              $$  text "maxSpillSlots:          " <> int (maxSpillSlots is32Bit))
671 672 673 674 675

--------------------------------------------------------------------------------

-- | See if this instruction is telling us the current C stack delta
x86_takeDeltaInstr
Ian Lynagh's avatar
Ian Lynagh committed
676 677 678
        :: Instr
        -> Maybe Int

679 680
x86_takeDeltaInstr instr
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
681 682
        DELTA i         -> Just i
        _               -> Nothing
683 684 685


x86_isMetaInstr
Ian Lynagh's avatar
Ian Lynagh committed
686 687 688
        :: Instr
        -> Bool

689 690
x86_isMetaInstr instr
 = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
691 692 693 694 695
        COMMENT{}       -> True
        LDATA{}         -> True
        NEWBLOCK{}      -> True
        DELTA{}         -> True
        _               -> False
696 697 698 699



-- | Make a reg-reg move instruction.
Ian Lynagh's avatar
Ian Lynagh committed
700 701 702
--      On SPARC v8 there are no instructions to move directly between
--      floating point and integer regs. If we need to do that then we
--      have to go via memory.
703 704
--
x86_mkRegRegMoveInstr
705 706 707 708
    :: Platform
    -> Reg
    -> Reg
    -> Instr
709

710 711
x86_mkRegRegMoveInstr platform src dst
 = case targetClassOfReg platform src of
712 713 714 715 716
#if   i386_TARGET_ARCH
        RcInteger -> MOV II32 (OpReg src) (OpReg dst)
#else
        RcInteger -> MOV II64 (OpReg src) (OpReg dst)
#endif
717 718
        RcDouble    -> GMOV src dst
        RcDoubleSSE -> MOV FF64 (OpReg src) (OpReg dst)
Ian Lynagh's avatar
Ian Lynagh committed
719
        _     -> panic "X86.RegInfo.mkRegRegMoveInstr: no match"
720 721

-- | Check whether an instruction represents a reg-reg move.
Ian Lynagh's avatar
Ian Lynagh committed
722 723
--      The register allocator attempts to eliminate reg->reg moves whenever it can,
--      by assigning the src and dest temporaries to the same real register.
724 725
--
x86_takeRegRegMoveInstr
Ian Lynagh's avatar
Ian Lynagh committed
726 727
        :: Instr
        -> Maybe (Reg,Reg)
728

Ian Lynagh's avatar
Ian Lynagh committed
729 730
x86_takeRegRegMoveInstr (MOV _ (OpReg r1) (OpReg r2))
        = Just (r1,r2)
731 732 733 734 735 736

x86_takeRegRegMoveInstr _  = Nothing


-- | Make an unconditional branch instruction.
x86_mkJumpInstr
Ian Lynagh's avatar
Ian Lynagh committed
737 738
        :: BlockId
        -> [Instr]
739

Ian Lynagh's avatar
Ian Lynagh committed
740 741
x86_mkJumpInstr id
        = [JXX ALWAYS id]
742 743 744 745 746





Ian Lynagh's avatar
Ian Lynagh committed
747 748 749
i386_insert_ffrees
        :: [GenBasicBlock Instr]
        -> [GenBasicBlock Instr]
750

751
i386_insert_ffrees blocks
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
752
   | or (map (any is_G_instr) [ instrs | BasicBlock _ instrs <- blocks ])
753
   = map ffree_before_nonlocal_transfers blocks
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
754

755 756 757
   | otherwise
   = blocks
  where
Ian Lynagh's avatar
Ian Lynagh committed
758
   ffree_before_nonlocal_transfers (BasicBlock id insns)
759 760 761 762
     = BasicBlock id (foldr p [] insns)
     where p insn r = case insn of
                        CALL _ _ -> GFREE : insn : r
                        JMP _    -> GFREE : insn : r
763
                        JXX_GBL _ _ -> panic "i386_insert_ffrees: cannot handle JXX_GBL"
Ben.Lippmeier@anu.edu.au's avatar
Ben.Lippmeier@anu.edu.au committed
764
                        _        -> insn : r
765 766 767 768 769 770

-- if you ever add a new FP insn to the fake x86 FP insn set,
-- you must update this too
is_G_instr :: Instr -> Bool
is_G_instr instr
   = case instr of
Ian Lynagh's avatar
Ian Lynagh committed
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
        GMOV{}          -> True
        GLD{}           -> True
        GST{}           -> True
        GLDZ{}          -> True
        GLD1{}          -> True
        GFTOI{}         -> True
        GDTOI{}         -> True
        GITOF{}         -> True
        GITOD{}         -> True
        GDTOF{}         -> True
        GADD{}          -> True
        GDIV{}          -> True
        GSUB{}          -> True
        GMUL{}          -> True
        GCMP{}          -> True
        GABS{}          -> True
        GNEG{}          -> True
        GSQRT{}         -> True
        GSIN{}          -> True
        GCOS{}          -> True
        GTAN{}          -> True
        GFREE           -> panic "is_G_instr: GFREE (!)"
        _               -> False
794 795 796 797


data JumpDest = DestBlockId BlockId | DestImm Imm

798 799 800
getJumpDestBlockId :: JumpDest -> Maybe BlockId
getJumpDestBlockId (DestBlockId bid) = Just bid
getJumpDestBlockId _                 = Nothing
801 802

canShortcut :: Instr -> Maybe JumpDest
803 804 805
canShortcut (JXX ALWAYS id)    = Just (DestBlockId id)
canShortcut (JMP (OpImm imm))  = Just (DestImm imm)
canShortcut _                  = Nothing
806 807


808 809
-- This helper shortcuts a sequence of branches.
-- The blockset helps avoid following cycles.
810
shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr
811
shortcutJump fn insn = shortcutJump' fn (setEmpty :: BlockSet) insn
812
  where shortcutJump' fn seen insn@(JXX cc id) =
813
          if setMember id seen then insn
814 815 816 817
          else case fn id of
                 Nothing                -> insn
                 Just (DestBlockId id') -> shortcutJump' fn seen' (JXX cc id')
                 Just (DestImm imm)     -> shortcutJump' fn seen' (JXX_GBL cc imm)
818
               where seen' = setInsert id seen
819 820 821
        shortcutJump' _ _ other = other

-- Here because it knows about JumpDest
822 823 824 825 826 827 828 829 830 831 832
shortcutStatics :: (BlockId -> Maybe JumpDest) -> (Alignment, CmmStatics) -> (Alignment, CmmStatics)
shortcutStatics fn (align, Statics lbl statics)
  = (align, Statics lbl $ map (shortcutStatic fn) statics)
  -- we need to get the jump tables, so apply the mapping to the entries
  -- of a CmmData too.

shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel
shortcutLabel fn lab
  | Just uq <- maybeAsmTemp lab = shortBlockId fn emptyUniqSet (mkBlockId uq)
  | otherwise                   = lab

833 834
shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic
shortcutStatic fn (CmmStaticLit (CmmLabel lab))
835
  = CmmStaticLit (CmmLabel (shortcutLabel fn lab))
836
shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off))
837
  = CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off)
838 839 840 841 842
        -- slightly dodgy, we're ignoring the second label, but this
        -- works with the way we use CmmLabelDiffOff for jump tables now.
shortcutStatic _ other_static
        = other_static

Ian Lynagh's avatar
Ian Lynagh committed
843 844 845 846 847
shortBlockId
        :: (BlockId -> Maybe JumpDest)
        -> UniqSet Unique
        -> BlockId
        -> CLabel
848

849
shortBlockId fn seen blockid =
850 851 852 853 854 855
  case (elementOfUniqSet uq seen, fn blockid) of
    (True, _)    -> mkAsmTempLabel uq
    (_, Nothing) -> mkAsmTempLabel uq
    (_, Just (DestBlockId blockid'))  -> shortBlockId fn (addOneToUniqSet seen uq) blockid'
    (_, Just (DestImm (ImmCLbl lbl))) -> lbl
    (_, _other) -> panic "shortBlockId"
856
  where uq = getUnique blockid