Define cTargetArch and start to use it rather than ifdefs
[ghc-hetmet.git] / compiler / nativeGen / AsmCodeGen.lhs
1 -- -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow 1993-2004
4 -- 
5 -- This is the top-level module in the native code generator.
6 --
7 -- -----------------------------------------------------------------------------
8
9 \begin{code}
10 module AsmCodeGen ( nativeCodeGen ) where
11
12 #include "HsVersions.h"
13 #include "nativeGen/NCG.h"
14
15
16 #if   alpha_TARGET_ARCH
17 import Alpha.CodeGen
18 import Alpha.Regs
19 import Alpha.RegInfo
20 import Alpha.Instr
21
22 #elif i386_TARGET_ARCH || x86_64_TARGET_ARCH
23 import X86.CodeGen
24 import X86.Regs
25 import X86.Instr
26 import X86.Ppr
27
28 #elif sparc_TARGET_ARCH
29 import SPARC.CodeGen
30 import SPARC.CodeGen.Expand
31 import SPARC.Regs
32 import SPARC.Instr
33 import SPARC.Ppr
34 import SPARC.ShortcutJump
35
36 #elif powerpc_TARGET_ARCH
37 import PPC.CodeGen
38 import PPC.Cond
39 import PPC.Regs
40 import PPC.RegInfo
41 import PPC.Instr
42 import PPC.Ppr
43
44 #else
45 #error "AsmCodeGen: unknown architecture"
46
47 #endif
48
49 import RegAlloc.Liveness
50 import qualified RegAlloc.Linear.Main           as Linear
51
52 import qualified GraphColor                     as Color
53 import qualified RegAlloc.Graph.Main            as Color
54 import qualified RegAlloc.Graph.Stats           as Color
55 import qualified RegAlloc.Graph.TrivColorable   as Color
56
57 import TargetReg
58 import Platform
59 import Instruction
60 import PIC
61 import Reg
62 import NCGMonad
63
64 import BlockId
65 import CgUtils          ( fixStgRegisters )
66 import Cmm
67 import CmmOpt           ( cmmMiniInline, cmmMachOpFold )
68 import PprCmm
69 import CLabel
70
71 import UniqFM
72 import Unique           ( Unique, getUnique )
73 import UniqSupply
74 import DynFlags
75 import StaticFlags
76 import Util
77 import Config
78
79 import Digraph
80 import qualified Pretty
81 import BufWrite
82 import Outputable
83 import FastString
84 import UniqSet
85 import ErrUtils
86 import Module
87
88 -- DEBUGGING ONLY
89 --import OrdList
90
91 import Data.List
92 import Data.Maybe
93 import Control.Monad
94 import System.IO
95 import Distribution.System
96
97 {-
98 The native-code generator has machine-independent and
99 machine-dependent modules.
100
101 This module ("AsmCodeGen") is the top-level machine-independent
102 module.  Before entering machine-dependent land, we do some
103 machine-independent optimisations (defined below) on the
104 'CmmStmts's.
105
106 We convert to the machine-specific 'Instr' datatype with
107 'cmmCodeGen', assuming an infinite supply of registers.  We then use
108 a machine-independent register allocator ('regAlloc') to rejoin
109 reality.  Obviously, 'regAlloc' has machine-specific helper
110 functions (see about "RegAllocInfo" below).
111
112 Finally, we order the basic blocks of the function so as to minimise
113 the number of jumps between blocks, by utilising fallthrough wherever
114 possible.
115
116 The machine-dependent bits break down as follows:
117
118   * ["MachRegs"]  Everything about the target platform's machine
119     registers (and immediate operands, and addresses, which tend to
120     intermingle/interact with registers).
121
122   * ["MachInstrs"]  Includes the 'Instr' datatype (possibly should
123     have a module of its own), plus a miscellany of other things
124     (e.g., 'targetDoubleSize', 'smStablePtrTable', ...)
125
126   * ["MachCodeGen"]  is where 'Cmm' stuff turns into
127     machine instructions.
128
129   * ["PprMach"] 'pprInstr' turns an 'Instr' into text (well, really
130     a 'Doc').
131
132   * ["RegAllocInfo"] In the register allocator, we manipulate
133     'MRegsState's, which are 'BitSet's, one bit per machine register.
134     When we want to say something about a specific machine register
135     (e.g., ``it gets clobbered by this instruction''), we set/unset
136     its bit.  Obviously, we do this 'BitSet' thing for efficiency
137     reasons.
138
139     The 'RegAllocInfo' module collects together the machine-specific
140     info needed to do register allocation.
141
142    * ["RegisterAlloc"] The (machine-independent) register allocator.
143 -}
144
145 -- -----------------------------------------------------------------------------
146 -- Top-level of the native codegen
147
148 --------------------
149 nativeCodeGen :: DynFlags -> Handle -> UniqSupply -> [RawCmm] -> IO ()
150 nativeCodeGen dflags h us cmms
151  = do
152         let split_cmms  = concat $ map add_split cmms
153
154         -- BufHandle is a performance hack.  We could hide it inside
155         -- Pretty if it weren't for the fact that we do lots of little
156         -- printDocs here (in order to do codegen in constant space).
157         bufh <- newBufHandle h
158         (imports, prof) <- cmmNativeGens dflags bufh us split_cmms [] [] 0
159         bFlush bufh
160
161         let (native, colorStats, linearStats)
162                 = unzip3 prof
163
164         -- dump native code
165         dumpIfSet_dyn dflags
166                 Opt_D_dump_asm "Asm code"
167                 (vcat $ map (docToSDoc . pprNatCmmTop) $ concat native)
168
169         -- dump global NCG stats for graph coloring allocator
170         (case concat $ catMaybes colorStats of
171           []    -> return ()
172           stats -> do   
173                 -- build the global register conflict graph
174                 let graphGlobal 
175                         = foldl Color.union Color.initGraph
176                         $ [ Color.raGraph stat
177                                 | stat@Color.RegAllocStatsStart{} <- stats]
178            
179                 dumpSDoc dflags Opt_D_dump_asm_stats "NCG stats"
180                         $ Color.pprStats stats graphGlobal
181
182                 dumpIfSet_dyn dflags
183                         Opt_D_dump_asm_conflicts "Register conflict graph"
184                         $ Color.dotGraph 
185                                 targetRegDotColor 
186                                 (Color.trivColorable 
187                                         targetVirtualRegSqueeze 
188                                         targetRealRegSqueeze)
189                         $ graphGlobal)
190
191
192         -- dump global NCG stats for linear allocator
193         (case concat $ catMaybes linearStats of
194                 []      -> return ()
195                 stats   -> dumpSDoc dflags Opt_D_dump_asm_stats "NCG stats"
196                                 $ Linear.pprStats (concat native) stats)
197
198         -- write out the imports
199         Pretty.printDoc Pretty.LeftMode h
200                 $ makeImportsDoc dflags (concat imports)
201
202         return  ()
203
204  where  add_split (Cmm tops)
205                 | dopt Opt_SplitObjs dflags = split_marker : tops
206                 | otherwise                 = tops
207
208         split_marker = CmmProc [] mkSplitMarkerLabel [] (ListGraph [])
209
210
211 -- | Do native code generation on all these cmms.
212 --
213 cmmNativeGens :: DynFlags
214               -> BufHandle
215               -> UniqSupply
216               -> [RawCmmTop]
217               -> [[CLabel]]
218               -> [ ([NatCmmTop Instr],
219                    Maybe [Color.RegAllocStats Instr],
220                    Maybe [Linear.RegAllocStats]) ]
221               -> Int
222               -> IO ( [[CLabel]],
223                       [([NatCmmTop Instr],
224                       Maybe [Color.RegAllocStats Instr],
225                       Maybe [Linear.RegAllocStats])] )
226
227 cmmNativeGens _ _ _ [] impAcc profAcc _
228         = return (reverse impAcc, reverse profAcc)
229
230 cmmNativeGens dflags h us (cmm : cmms) impAcc profAcc count
231  = do
232         (us', native, imports, colorStats, linearStats)
233                 <- cmmNativeGen dflags us cmm count
234
235         Pretty.bufLeftRender h
236                 $ {-# SCC "pprNativeCode" #-} Pretty.vcat $ map pprNatCmmTop native
237
238            -- carefully evaluate this strictly.  Binding it with 'let'
239            -- and then using 'seq' doesn't work, because the let
240            -- apparently gets inlined first.
241         lsPprNative <- return $!
242                 if  dopt Opt_D_dump_asm       dflags
243                  || dopt Opt_D_dump_asm_stats dflags
244                         then native
245                         else []
246
247         count' <- return $! count + 1;
248
249         -- force evaulation all this stuff to avoid space leaks
250         seqString (showSDoc $ vcat $ map ppr imports) `seq` return ()
251
252         cmmNativeGens dflags h us' cmms
253                         (imports : impAcc)
254                         ((lsPprNative, colorStats, linearStats) : profAcc)
255                         count'
256
257  where  seqString []            = ()
258         seqString (x:xs)        = x `seq` seqString xs `seq` ()
259
260
261 -- | Complete native code generation phase for a single top-level chunk of Cmm.
262 --      Dumping the output of each stage along the way.
263 --      Global conflict graph and NGC stats
264 cmmNativeGen 
265         :: DynFlags
266         -> UniqSupply
267         -> RawCmmTop                                    -- ^ the cmm to generate code for
268         -> Int                                          -- ^ sequence number of this top thing
269         -> IO   ( UniqSupply
270                 , [NatCmmTop Instr]                     -- native code
271                 , [CLabel]                              -- things imported by this cmm
272                 , Maybe [Color.RegAllocStats Instr]     -- stats for the coloring register allocator
273                 , Maybe [Linear.RegAllocStats])         -- stats for the linear register allocators
274
275 cmmNativeGen dflags us cmm count
276  = do
277
278         -- rewrite assignments to global regs
279         let fixed_cmm =
280                 {-# SCC "fixStgRegisters" #-}
281                 fixStgRegisters cmm
282
283         -- cmm to cmm optimisations
284         let (opt_cmm, imports) =
285                 {-# SCC "cmmToCmm" #-}
286                 cmmToCmm dflags fixed_cmm
287
288         dumpIfSet_dyn dflags
289                 Opt_D_dump_opt_cmm "Optimised Cmm"
290                 (pprCmm $ Cmm [opt_cmm])
291
292         -- generate native code from cmm
293         let ((native, lastMinuteImports), usGen) =
294                 {-# SCC "genMachCode" #-}
295                 initUs us $ genMachCode dflags opt_cmm
296
297         dumpIfSet_dyn dflags
298                 Opt_D_dump_asm_native "Native code"
299                 (vcat $ map (docToSDoc . pprNatCmmTop) native)
300
301         -- tag instructions with register liveness information
302         let (withLiveness, usLive) =
303                 {-# SCC "regLiveness" #-}
304                 initUs usGen 
305                         $ mapUs regLiveness 
306                         $ map natCmmTopToLive native
307
308         dumpIfSet_dyn dflags
309                 Opt_D_dump_asm_liveness "Liveness annotations added"
310                 (vcat $ map ppr withLiveness)
311                 
312         -- allocate registers
313         (alloced, usAlloc, ppr_raStatsColor, ppr_raStatsLinear) <-
314          if ( dopt Opt_RegsGraph dflags
315            || dopt Opt_RegsIterative dflags)
316           then do
317                 -- the regs usable for allocation
318                 let (alloc_regs :: UniqFM (UniqSet RealReg))
319                         = foldr (\r -> plusUFM_C unionUniqSets
320                                         $ unitUFM (targetClassOfRealReg r) (unitUniqSet r))
321                                 emptyUFM
322                         $ allocatableRegs
323
324                 -- do the graph coloring register allocation
325                 let ((alloced, regAllocStats), usAlloc)
326                         = {-# SCC "RegAlloc" #-}
327                           initUs usLive
328                           $ Color.regAlloc
329                                 dflags
330                                 alloc_regs
331                                 (mkUniqSet [0..maxSpillSlots])
332                                 withLiveness
333
334                 -- dump out what happened during register allocation
335                 dumpIfSet_dyn dflags
336                         Opt_D_dump_asm_regalloc "Registers allocated"
337                         (vcat $ map (docToSDoc . pprNatCmmTop) alloced)
338
339                 dumpIfSet_dyn dflags
340                         Opt_D_dump_asm_regalloc_stages "Build/spill stages"
341                         (vcat   $ map (\(stage, stats)
342                                         -> text "# --------------------------"
343                                         $$ text "#  cmm " <> int count <> text " Stage " <> int stage
344                                         $$ ppr stats)
345                                 $ zip [0..] regAllocStats)
346
347                 let mPprStats =
348                         if dopt Opt_D_dump_asm_stats dflags
349                          then Just regAllocStats else Nothing
350
351                 -- force evaluation of the Maybe to avoid space leak
352                 mPprStats `seq` return ()
353
354                 return  ( alloced, usAlloc
355                         , mPprStats
356                         , Nothing)
357
358           else do
359                 -- do linear register allocation
360                 let ((alloced, regAllocStats), usAlloc) 
361                         = {-# SCC "RegAlloc" #-}
362                           initUs usLive
363                           $ liftM unzip
364                           $ mapUs Linear.regAlloc withLiveness
365
366                 dumpIfSet_dyn dflags
367                         Opt_D_dump_asm_regalloc "Registers allocated"
368                         (vcat $ map (docToSDoc . pprNatCmmTop) alloced)
369
370                 let mPprStats =
371                         if dopt Opt_D_dump_asm_stats dflags
372                          then Just (catMaybes regAllocStats) else Nothing
373
374                 -- force evaluation of the Maybe to avoid space leak
375                 mPprStats `seq` return ()
376
377                 return  ( alloced, usAlloc
378                         , Nothing
379                         , mPprStats)
380
381         ---- shortcut branches
382         let shorted     =
383                 {-# SCC "shortcutBranches" #-}
384                 shortcutBranches dflags alloced
385
386         ---- sequence blocks
387         let sequenced   =
388                 {-# SCC "sequenceBlocks" #-}
389                 map sequenceTop shorted
390
391         ---- x86fp_kludge
392         let kludged =
393 #if i386_TARGET_ARCH
394                 {-# SCC "x86fp_kludge" #-}
395                 map x86fp_kludge sequenced
396 #else
397                 sequenced
398 #endif
399
400         ---- expansion of SPARC synthetic instrs
401 #if sparc_TARGET_ARCH
402         let expanded = 
403                 {-# SCC "sparc_expand" #-}
404                 map expandTop kludged
405
406         dumpIfSet_dyn dflags
407                 Opt_D_dump_asm_expanded "Synthetic instructions expanded"
408                 (vcat $ map (docToSDoc . pprNatCmmTop) expanded)
409 #else
410         let expanded = 
411                 kludged
412 #endif
413
414         return  ( usAlloc
415                 , expanded
416                 , lastMinuteImports ++ imports
417                 , ppr_raStatsColor
418                 , ppr_raStatsLinear)
419
420
421 #if i386_TARGET_ARCH
422 x86fp_kludge :: NatCmmTop Instr -> NatCmmTop Instr
423 x86fp_kludge top@(CmmData _ _) = top
424 x86fp_kludge (CmmProc info lbl params (ListGraph code)) = 
425         CmmProc info lbl params (ListGraph $ i386_insert_ffrees code)
426 #endif
427
428
429 -- | Build a doc for all the imports.
430 --
431 makeImportsDoc :: DynFlags -> [CLabel] -> Pretty.Doc
432 makeImportsDoc dflags imports
433  = dyld_stubs imports
434
435 #if HAVE_SUBSECTIONS_VIA_SYMBOLS
436                 -- On recent versions of Darwin, the linker supports
437                 -- dead-stripping of code and data on a per-symbol basis.
438                 -- There's a hack to make this work in PprMach.pprNatCmmTop.
439             Pretty.$$ Pretty.text ".subsections_via_symbols"
440 #endif
441 #if HAVE_GNU_NONEXEC_STACK
442                 -- On recent GNU ELF systems one can mark an object file
443                 -- as not requiring an executable stack. If all objects
444                 -- linked into a program have this note then the program
445                 -- will not use an executable stack, which is good for
446                 -- security. GHC generated code does not need an executable
447                 -- stack so add the note in:
448             Pretty.$$ Pretty.text ".section .note.GNU-stack,\"\",@progbits"
449 #endif
450 #if !defined(darwin_TARGET_OS)
451                 -- And just because every other compiler does, lets stick in
452                 -- an identifier directive: .ident "GHC x.y.z"
453             Pretty.$$ let compilerIdent = Pretty.text "GHC" Pretty.<+>
454                                           Pretty.text cProjectVersion
455                        in Pretty.text ".ident" Pretty.<+>
456                           Pretty.doubleQuotes compilerIdent
457 #endif
458
459  where
460         -- Generate "symbol stubs" for all external symbols that might
461         -- come from a dynamic library.
462         dyld_stubs :: [CLabel] -> Pretty.Doc
463 {-      dyld_stubs imps = Pretty.vcat $ map pprDyldSymbolStub $
464                                     map head $ group $ sort imps-}
465
466         arch    = platformArch  $ targetPlatform dflags
467         os      = platformOS    $ targetPlatform dflags
468         
469         -- (Hack) sometimes two Labels pretty-print the same, but have
470         -- different uniques; so we compare their text versions...
471         dyld_stubs imps
472                 | needImportedSymbols arch os
473                 = Pretty.vcat $
474                         (pprGotDeclaration arch os :) $
475                         map ( pprImportedSymbol arch os . fst . head) $
476                         groupBy (\(_,a) (_,b) -> a == b) $
477                         sortBy (\(_,a) (_,b) -> compare a b) $
478                         map doPpr $
479                         imps
480                 | otherwise
481                 = Pretty.empty
482
483         doPpr lbl = (lbl, Pretty.render $ pprCLabel lbl astyle)
484         astyle = mkCodeStyle AsmStyle
485
486
487 -- -----------------------------------------------------------------------------
488 -- Sequencing the basic blocks
489
490 -- Cmm BasicBlocks are self-contained entities: they always end in a
491 -- jump, either non-local or to another basic block in the same proc.
492 -- In this phase, we attempt to place the basic blocks in a sequence
493 -- such that as many of the local jumps as possible turn into
494 -- fallthroughs.
495
496 sequenceTop 
497         :: NatCmmTop Instr
498         -> NatCmmTop Instr
499
500 sequenceTop top@(CmmData _ _) = top
501 sequenceTop (CmmProc info lbl params (ListGraph blocks)) = 
502   CmmProc info lbl params (ListGraph $ makeFarBranches $ sequenceBlocks blocks)
503
504 -- The algorithm is very simple (and stupid): we make a graph out of
505 -- the blocks where there is an edge from one block to another iff the
506 -- first block ends by jumping to the second.  Then we topologically
507 -- sort this graph.  Then traverse the list: for each block, we first
508 -- output the block, then if it has an out edge, we move the
509 -- destination of the out edge to the front of the list, and continue.
510
511 -- FYI, the classic layout for basic blocks uses postorder DFS; this
512 -- algorithm is implemented in cmm/ZipCfg.hs (NR 6 Sep 2007).
513
514 sequenceBlocks 
515         :: Instruction instr
516         => [NatBasicBlock instr] 
517         -> [NatBasicBlock instr]
518
519 sequenceBlocks [] = []
520 sequenceBlocks (entry:blocks) = 
521   seqBlocks (mkNode entry : reverse (flattenSCCs (sccBlocks blocks)))
522   -- the first block is the entry point ==> it must remain at the start.
523
524
525 sccBlocks 
526         :: Instruction instr
527         => [NatBasicBlock instr] 
528         -> [SCC ( NatBasicBlock instr
529                 , Unique
530                 , [Unique])]
531
532 sccBlocks blocks = stronglyConnCompFromEdgedVerticesR (map mkNode blocks)
533
534 -- we're only interested in the last instruction of
535 -- the block, and only if it has a single destination.
536 getOutEdges 
537         :: Instruction instr
538         => [instr] -> [Unique]
539
540 getOutEdges instrs 
541         = case jumpDestsOfInstr (last instrs) of
542                 [one] -> [getUnique one]
543                 _many -> []
544
545 mkNode :: (Instruction t)
546        => GenBasicBlock t
547        -> (GenBasicBlock t, Unique, [Unique])
548 mkNode block@(BasicBlock id instrs) = (block, getUnique id, getOutEdges instrs)
549
550 seqBlocks :: (Eq t) => [(GenBasicBlock t1, t, [t])] -> [GenBasicBlock t1]
551 seqBlocks [] = []
552 seqBlocks ((block,_,[]) : rest)
553   = block : seqBlocks rest
554 seqBlocks ((block@(BasicBlock id instrs),_,[next]) : rest)
555   | can_fallthrough = BasicBlock id (init instrs) : seqBlocks rest'
556   | otherwise       = block : seqBlocks rest'
557   where
558         (can_fallthrough, rest') = reorder next [] rest
559           -- TODO: we should do a better job for cycles; try to maximise the
560           -- fallthroughs within a loop.
561 seqBlocks _ = panic "AsmCodegen:seqBlocks"
562
563 reorder :: (Eq a) => a -> [(t, a, t1)] -> [(t, a, t1)] -> (Bool, [(t, a, t1)])
564 reorder  _ accum [] = (False, reverse accum)
565 reorder id accum (b@(block,id',out) : rest)
566   | id == id'  = (True, (block,id,out) : reverse accum ++ rest)
567   | otherwise  = reorder id (b:accum) rest
568
569
570 -- -----------------------------------------------------------------------------
571 -- Making far branches
572
573 -- Conditional branches on PowerPC are limited to +-32KB; if our Procs get too
574 -- big, we have to work around this limitation.
575
576 makeFarBranches 
577         :: [NatBasicBlock Instr] 
578         -> [NatBasicBlock Instr]
579
580 #if powerpc_TARGET_ARCH
581 makeFarBranches blocks
582     | last blockAddresses < nearLimit = blocks
583     | otherwise = zipWith handleBlock blockAddresses blocks
584     where
585         blockAddresses = scanl (+) 0 $ map blockLen blocks
586         blockLen (BasicBlock _ instrs) = length instrs
587         
588         handleBlock addr (BasicBlock id instrs)
589                 = BasicBlock id (zipWith makeFar [addr..] instrs)
590         
591         makeFar addr (BCC ALWAYS tgt) = BCC ALWAYS tgt
592         makeFar addr (BCC cond tgt)
593             | abs (addr - targetAddr) >= nearLimit
594             = BCCFAR cond tgt
595             | otherwise
596             = BCC cond tgt
597             where Just targetAddr = lookupUFM blockAddressMap tgt
598         makeFar addr other            = other
599         
600         nearLimit = 7000 -- 8192 instructions are allowed; let's keep some
601                          -- distance, as we have a few pseudo-insns that are
602                          -- pretty-printed as multiple instructions,
603                          -- and it's just not worth the effort to calculate
604                          -- things exactly
605         
606         blockAddressMap = listToUFM $ zip (map blockId blocks) blockAddresses
607 #else
608 makeFarBranches = id
609 #endif
610
611 -- -----------------------------------------------------------------------------
612 -- Shortcut branches
613
614 shortcutBranches 
615         :: DynFlags 
616         -> [NatCmmTop Instr] 
617         -> [NatCmmTop Instr]
618
619 shortcutBranches dflags tops
620   | optLevel dflags < 1 = tops    -- only with -O or higher
621   | otherwise           = map (apply_mapping mapping) tops'
622   where
623     (tops', mappings) = mapAndUnzip build_mapping tops
624     mapping = foldr plusUFM emptyUFM mappings
625
626 build_mapping :: GenCmmTop d t (ListGraph Instr)
627               -> (GenCmmTop d t (ListGraph Instr), UniqFM JumpDest)
628 build_mapping top@(CmmData _ _) = (top, emptyUFM)
629 build_mapping (CmmProc info lbl params (ListGraph []))
630   = (CmmProc info lbl params (ListGraph []), emptyUFM)
631 build_mapping (CmmProc info lbl params (ListGraph (head:blocks)))
632   = (CmmProc info lbl params (ListGraph (head:others)), mapping)
633         -- drop the shorted blocks, but don't ever drop the first one,
634         -- because it is pointed to by a global label.
635   where
636     -- find all the blocks that just consist of a jump that can be
637     -- shorted.
638     -- Don't completely eliminate loops here -- that can leave a dangling jump!
639     (_, shortcut_blocks, others) = foldl split (emptyBlockSet, [], []) blocks
640     split (s, shortcut_blocks, others) b@(BasicBlock id [insn])
641         | Just (DestBlockId dest) <- canShortcut insn,
642           (elemBlockSet dest s) || dest == id -- loop checks
643         = (s, shortcut_blocks, b : others)
644     split (s, shortcut_blocks, others) (BasicBlock id [insn])
645         | Just dest <- canShortcut insn
646         = (extendBlockSet s id, (id,dest) : shortcut_blocks, others)
647     split (s, shortcut_blocks, others) other = (s, shortcut_blocks, other : others)
648
649
650     -- build a mapping from BlockId to JumpDest for shorting branches
651     mapping = foldl add emptyUFM shortcut_blocks
652     add ufm (id,dest) = addToUFM ufm id dest
653     
654 apply_mapping :: UniqFM JumpDest
655               -> GenCmmTop CmmStatic h (ListGraph Instr)
656               -> GenCmmTop CmmStatic h (ListGraph Instr)
657 apply_mapping ufm (CmmData sec statics) 
658   = CmmData sec (map (shortcutStatic (lookupUFM ufm)) statics)
659   -- we need to get the jump tables, so apply the mapping to the entries
660   -- of a CmmData too.
661 apply_mapping ufm (CmmProc info lbl params (ListGraph blocks))
662   = CmmProc info lbl params (ListGraph $ map short_bb blocks)
663   where
664     short_bb (BasicBlock id insns) = BasicBlock id $! map short_insn insns
665     short_insn i = shortcutJump (lookupUFM ufm) i
666                  -- shortcutJump should apply the mapping repeatedly,
667                  -- just in case we can short multiple branches.
668
669 -- -----------------------------------------------------------------------------
670 -- Instruction selection
671
672 -- Native code instruction selection for a chunk of stix code.  For
673 -- this part of the computation, we switch from the UniqSM monad to
674 -- the NatM monad.  The latter carries not only a Unique, but also an
675 -- Int denoting the current C stack pointer offset in the generated
676 -- code; this is needed for creating correct spill offsets on
677 -- architectures which don't offer, or for which it would be
678 -- prohibitively expensive to employ, a frame pointer register.  Viz,
679 -- x86.
680
681 -- The offset is measured in bytes, and indicates the difference
682 -- between the current (simulated) C stack-ptr and the value it was at
683 -- the beginning of the block.  For stacks which grow down, this value
684 -- should be either zero or negative.
685
686 -- Switching between the two monads whilst carrying along the same
687 -- Unique supply breaks abstraction.  Is that bad?
688
689 genMachCode 
690         :: DynFlags 
691         -> RawCmmTop 
692         -> UniqSM 
693                 ( [NatCmmTop Instr]
694                 , [CLabel])
695
696 genMachCode dflags cmm_top
697   = do  { initial_us <- getUs
698         ; let initial_st           = mkNatM_State initial_us 0 dflags
699               (new_tops, final_st) = initNat initial_st (cmmTopCodeGen dflags cmm_top)
700               final_delta          = natm_delta final_st
701               final_imports        = natm_imports final_st
702         ; if   final_delta == 0
703           then return (new_tops, final_imports)
704           else pprPanic "genMachCode: nonzero final delta" (int final_delta)
705     }
706
707
708 -- -----------------------------------------------------------------------------
709 -- Generic Cmm optimiser
710
711 {-
712 Here we do:
713
714   (a) Constant folding
715   (b) Simple inlining: a temporary which is assigned to and then
716       used, once, can be shorted.
717   (c) Position independent code and dynamic linking
718         (i)  introduce the appropriate indirections
719              and position independent refs
720         (ii) compile a list of imported symbols
721
722 Ideas for other things we could do (ToDo):
723
724   - shortcut jumps-to-jumps
725   - eliminate dead code blocks
726   - simple CSE: if an expr is assigned to a temp, then replace later occs of
727     that expr with the temp, until the expr is no longer valid (can push through
728     temp assignments, and certain assigns to mem...)
729 -}
730
731 cmmToCmm :: DynFlags -> RawCmmTop -> (RawCmmTop, [CLabel])
732 cmmToCmm _ top@(CmmData _ _) = (top, [])
733 cmmToCmm dflags (CmmProc info lbl params (ListGraph blocks)) = runCmmOpt dflags $ do
734   blocks' <- mapM cmmBlockConFold (cmmMiniInline blocks)
735   return $ CmmProc info lbl params (ListGraph blocks')
736
737 newtype CmmOptM a = CmmOptM (([CLabel], DynFlags) -> (# a, [CLabel] #))
738
739 instance Monad CmmOptM where
740   return x = CmmOptM $ \(imports, _) -> (# x,imports #)
741   (CmmOptM f) >>= g =
742     CmmOptM $ \(imports, dflags) ->
743                 case f (imports, dflags) of
744                   (# x, imports' #) ->
745                     case g x of
746                       CmmOptM g' -> g' (imports', dflags)
747
748 addImportCmmOpt :: CLabel -> CmmOptM ()
749 addImportCmmOpt lbl = CmmOptM $ \(imports, _dflags) -> (# (), lbl:imports #)
750
751 getDynFlagsCmmOpt :: CmmOptM DynFlags
752 getDynFlagsCmmOpt = CmmOptM $ \(imports, dflags) -> (# dflags, imports #)
753
754 runCmmOpt :: DynFlags -> CmmOptM a -> (a, [CLabel])
755 runCmmOpt dflags (CmmOptM f) = case f ([], dflags) of
756                         (# result, imports #) -> (result, imports)
757
758 cmmBlockConFold :: CmmBasicBlock -> CmmOptM CmmBasicBlock
759 cmmBlockConFold (BasicBlock id stmts) = do
760   stmts' <- mapM cmmStmtConFold stmts
761   return $ BasicBlock id stmts'
762
763 cmmStmtConFold :: CmmStmt -> CmmOptM CmmStmt
764 cmmStmtConFold stmt
765    = case stmt of
766         CmmAssign reg src
767            -> do src' <- cmmExprConFold DataReference src
768                  return $ case src' of
769                    CmmReg reg' | reg == reg' -> CmmNop
770                    new_src -> CmmAssign reg new_src
771
772         CmmStore addr src
773            -> do addr' <- cmmExprConFold DataReference addr
774                  src'  <- cmmExprConFold DataReference src
775                  return $ CmmStore addr' src'
776
777         CmmJump addr regs
778            -> do addr' <- cmmExprConFold JumpReference addr
779                  return $ CmmJump addr' regs
780
781         CmmCall target regs args srt returns
782            -> do target' <- case target of
783                               CmmCallee e conv -> do
784                                 e' <- cmmExprConFold CallReference e
785                                 return $ CmmCallee e' conv
786                               other -> return other
787                  args' <- mapM (\(CmmHinted arg hint) -> do
788                                   arg' <- cmmExprConFold DataReference arg
789                                   return (CmmHinted arg' hint)) args
790                  return $ CmmCall target' regs args' srt returns
791
792         CmmCondBranch test dest
793            -> do test' <- cmmExprConFold DataReference test
794                  return $ case test' of
795                    CmmLit (CmmInt 0 _) -> 
796                      CmmComment (mkFastString ("deleted: " ++ 
797                                         showSDoc (pprStmt stmt)))
798
799                    CmmLit (CmmInt _ _) -> CmmBranch dest
800                    _other -> CmmCondBranch test' dest
801
802         CmmSwitch expr ids
803            -> do expr' <- cmmExprConFold DataReference expr
804                  return $ CmmSwitch expr' ids
805
806         other
807            -> return other
808
809
810 cmmExprConFold :: ReferenceKind -> CmmExpr -> CmmOptM CmmExpr
811 cmmExprConFold referenceKind expr
812    = case expr of
813         CmmLoad addr rep
814            -> do addr' <- cmmExprConFold DataReference addr
815                  return $ CmmLoad addr' rep
816
817         CmmMachOp mop args
818            -- For MachOps, we first optimize the children, and then we try 
819            -- our hand at some constant-folding.
820            -> do args' <- mapM (cmmExprConFold DataReference) args
821                  return $ cmmMachOpFold mop args'
822
823         CmmLit (CmmLabel lbl)
824            -> do
825                 dflags <- getDynFlagsCmmOpt
826                 cmmMakeDynamicReference dflags addImportCmmOpt referenceKind lbl
827         CmmLit (CmmLabelOff lbl off)
828            -> do
829                  dflags <- getDynFlagsCmmOpt
830                  dynRef <- cmmMakeDynamicReference dflags addImportCmmOpt referenceKind lbl
831                  return $ cmmMachOpFold (MO_Add wordWidth) [
832                      dynRef,
833                      (CmmLit $ CmmInt (fromIntegral off) wordWidth)
834                    ]
835
836         -- On powerpc (non-PIC), it's easier to jump directly to a label than
837         -- to use the register table, so we replace these registers
838         -- with the corresponding labels:
839         CmmReg (CmmGlobal EagerBlackholeInfo)
840           | cTargetArch == PPC && not opt_PIC
841           -> cmmExprConFold referenceKind $
842              CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "__stg_EAGER_BLACKHOLE_info")))
843         CmmReg (CmmGlobal GCEnter1)
844           | cTargetArch == PPC && not opt_PIC
845           -> cmmExprConFold referenceKind $
846              CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "__stg_gc_enter_1"))) 
847         CmmReg (CmmGlobal GCFun)
848           | cTargetArch == PPC && not opt_PIC
849           -> cmmExprConFold referenceKind $
850              CmmLit (CmmLabel (mkCmmCodeLabel rtsPackageId (fsLit "__stg_gc_fun")))
851
852         other
853            -> return other
854
855 \end{code}
856