PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/compiler/nativeGen/AsmCodeGen.lhs

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