cbackend.nim 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2021 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## New entry point into our C/C++ code generator. Ideally
  10. ## somebody would rewrite the old backend (which is 8000 lines of crufty Nim code)
  11. ## to work on packed trees directly and produce the C code as an AST which can
  12. ## then be rendered to text in a very simple manner. Unfortunately nobody wrote
  13. ## this code. So instead we wrap the existing cgen.nim and its friends so that
  14. ## we call directly into the existing code generation logic but avoiding the
  15. ## naive, outdated `passes` design. Thus you will see some
  16. ## `useAliveDataFromDce in flags` checks in the old code -- the old code is
  17. ## also doing cross-module dependency tracking and DCE that we don't need
  18. ## anymore. DCE is now done as prepass over the entire packed module graph.
  19. import std/packedsets, algorithm, tables
  20. when defined(nimPreviewSlimSystem):
  21. import std/assertions
  22. import ".."/[ast, options, lineinfos, modulegraphs, cgendata, cgen,
  23. pathutils, extccomp, msgs, modulepaths]
  24. import packed_ast, ic, dce, rodfiles
  25. proc unpackTree(g: ModuleGraph; thisModule: int;
  26. tree: PackedTree; n: NodePos): PNode =
  27. var decoder = initPackedDecoder(g.config, g.cache)
  28. result = loadNodes(decoder, g.packed, thisModule, tree, n)
  29. proc setupBackendModule(g: ModuleGraph; m: var LoadedModule) =
  30. if g.backend == nil:
  31. g.backend = cgendata.newModuleList(g)
  32. assert g.backend != nil
  33. var bmod = cgen.newModule(BModuleList(g.backend), m.module, g.config)
  34. bmod.idgen = idgenFromLoadedModule(m)
  35. proc generateCodeForModule(g: ModuleGraph; m: var LoadedModule; alive: var AliveSyms) =
  36. var bmod = BModuleList(g.backend).modules[m.module.position]
  37. assert bmod != nil
  38. bmod.flags.incl useAliveDataFromDce
  39. bmod.alive = move alive[m.module.position]
  40. for p in allNodes(m.fromDisk.topLevel):
  41. let n = unpackTree(g, m.module.position, m.fromDisk.topLevel, p)
  42. cgen.genTopLevelStmt(bmod, n)
  43. finalCodegenActions(g, bmod, newNodeI(nkStmtList, m.module.info))
  44. m.fromDisk.backendFlags = cgen.whichInitProcs(bmod)
  45. proc replayTypeInfo(g: ModuleGraph; m: var LoadedModule; origin: FileIndex) =
  46. for x in mitems(m.fromDisk.emittedTypeInfo):
  47. #echo "found type ", x, " for file ", int(origin)
  48. g.emittedTypeInfo[x] = origin
  49. proc addFileToLink(config: ConfigRef; m: PSym) =
  50. let filename = AbsoluteFile toFullPath(config, m.position.FileIndex)
  51. let ext =
  52. if config.backend == backendCpp: ".nim.cpp"
  53. elif config.backend == backendObjc: ".nim.m"
  54. else: ".nim.c"
  55. let cfile = changeFileExt(completeCfilePath(config,
  56. mangleModuleName(config, filename).AbsoluteFile), ext)
  57. let objFile = completeCfilePath(config, toObjFile(config, cfile))
  58. if fileExists(objFile):
  59. var cf = Cfile(nimname: m.name.s, cname: cfile,
  60. obj: objFile,
  61. flags: {CfileFlag.Cached})
  62. addFileToCompile(config, cf)
  63. when defined(debugDce):
  64. import os, std/packedsets
  65. proc storeAliveSymsImpl(asymFile: AbsoluteFile; s: seq[int32]) =
  66. var f = rodfiles.create(asymFile.string)
  67. f.storeHeader()
  68. f.storeSection aliveSymsSection
  69. f.storeSeq(s)
  70. close f
  71. template prepare {.dirty.} =
  72. let asymFile = toRodFile(config, AbsoluteFile toFullPath(config, position.FileIndex), ".alivesyms")
  73. var s = newSeqOfCap[int32](alive[position].len)
  74. for a in items(alive[position]): s.add int32(a)
  75. sort(s)
  76. proc storeAliveSyms(config: ConfigRef; position: int; alive: AliveSyms) =
  77. prepare()
  78. storeAliveSymsImpl(asymFile, s)
  79. proc aliveSymsChanged(config: ConfigRef; position: int; alive: AliveSyms): bool =
  80. prepare()
  81. var f2 = rodfiles.open(asymFile.string)
  82. f2.loadHeader()
  83. f2.loadSection aliveSymsSection
  84. var oldData: seq[int32]
  85. f2.loadSeq(oldData)
  86. f2.close
  87. if f2.err == ok and oldData == s:
  88. result = false
  89. else:
  90. when defined(debugDce):
  91. let oldAsSet = toPackedSet[int32](oldData)
  92. let newAsSet = toPackedSet[int32](s)
  93. echo "set of live symbols changed ", asymFile.changeFileExt("rod"), " ", position, " ", f2.err
  94. echo "in old but not in new ", oldAsSet.difference(newAsSet), " number of entries in old ", oldAsSet.len
  95. echo "in new but not in old ", newAsSet.difference(oldAsSet), " number of entries in new ", newAsSet.len
  96. #if execShellCmd(getAppFilename() & " rod " & quoteShell(asymFile.changeFileExt("rod"))) != 0:
  97. # echo "command failed"
  98. result = true
  99. storeAliveSymsImpl(asymFile, s)
  100. proc genPackedModule(g: ModuleGraph, i: int; alive: var AliveSyms) =
  101. # case statement here to enforce exhaustive checks.
  102. case g.packed[i].status
  103. of undefined:
  104. discard "nothing to do"
  105. of loading, stored:
  106. assert false
  107. of storing, outdated:
  108. storeAliveSyms(g.config, g.packed[i].module.position, alive)
  109. generateCodeForModule(g, g.packed[i], alive)
  110. closeRodFile(g, g.packed[i].module)
  111. of loaded:
  112. if g.packed[i].loadedButAliveSetChanged:
  113. generateCodeForModule(g, g.packed[i], alive)
  114. else:
  115. addFileToLink(g.config, g.packed[i].module)
  116. replayTypeInfo(g, g.packed[i], FileIndex(i))
  117. if g.backend == nil:
  118. g.backend = cgendata.newModuleList(g)
  119. registerInitProcs(BModuleList(g.backend), g.packed[i].module, g.packed[i].fromDisk.backendFlags)
  120. proc generateCode*(g: ModuleGraph) =
  121. ## The single entry point, generate C(++) code for the entire
  122. ## Nim program aka `ModuleGraph`.
  123. resetForBackend(g)
  124. var alive = computeAliveSyms(g.packed, g.config)
  125. when false:
  126. for i in 0..high(g.packed):
  127. echo i, " is of status ", g.packed[i].status, " ", toFullPath(g.config, FileIndex(i))
  128. # First pass: Setup all the backend modules for all the modules that have
  129. # changed:
  130. for i in 0..high(g.packed):
  131. # case statement here to enforce exhaustive checks.
  132. case g.packed[i].status
  133. of undefined:
  134. discard "nothing to do"
  135. of loading, stored:
  136. assert false
  137. of storing, outdated:
  138. setupBackendModule(g, g.packed[i])
  139. of loaded:
  140. # Even though this module didn't change, DCE might trigger a change.
  141. # Consider this case: Module A uses symbol S from B and B does not use
  142. # S itself. A is then edited not to use S either. Thus we have to
  143. # recompile B in order to remove S from the final result.
  144. if aliveSymsChanged(g.config, g.packed[i].module.position, alive):
  145. g.packed[i].loadedButAliveSetChanged = true
  146. setupBackendModule(g, g.packed[i])
  147. # Second pass: Code generation.
  148. let mainModuleIdx = g.config.projectMainIdx2.int
  149. # We need to generate the main module last, because only then
  150. # all init procs have been registered:
  151. for i in 0..high(g.packed):
  152. if i != mainModuleIdx:
  153. genPackedModule(g, i, alive)
  154. if mainModuleIdx >= 0:
  155. genPackedModule(g, mainModuleIdx, alive)