cgen.nim 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements the C code generator.
  10. import
  11. ast, astalgo, trees, platform, magicsys, extccomp, options,
  12. nversion, nimsets, msgs, bitsets, idents, types,
  13. ccgutils, ropes, wordrecg, treetab, cgmeth,
  14. rodutils, renderer, cgendata, aliases,
  15. lowerings, ndi, lineinfos, pathutils, transf,
  16. injectdestructors, astmsgs, modulepaths, backendpragmas,
  17. mangleutils
  18. from expanddefaults import caseObjDefaultBranch
  19. import pipelineutils
  20. when defined(nimPreviewSlimSystem):
  21. import std/assertions
  22. when not defined(leanCompiler):
  23. import spawn, semparallel
  24. import std/strutils except `%`, addf # collides with ropes.`%`
  25. from ic / ic import ModuleBackendFlag
  26. import std/[dynlib, math, tables, sets, os, intsets, hashes]
  27. const
  28. # we use some ASCII control characters to insert directives that will be converted to real code in a postprocessing pass
  29. postprocessDirStart = '\1'
  30. postprocessDirSep = '\31'
  31. postprocessDirEnd = '\23'
  32. when not declared(dynlib.libCandidates):
  33. proc libCandidates(s: string, dest: var seq[string]) =
  34. ## given a library name pattern `s` write possible library names to `dest`.
  35. var le = strutils.find(s, '(')
  36. var ri = strutils.find(s, ')', le+1)
  37. if le >= 0 and ri > le:
  38. var prefix = substr(s, 0, le - 1)
  39. var suffix = substr(s, ri + 1)
  40. for middle in split(substr(s, le + 1, ri - 1), '|'):
  41. libCandidates(prefix & middle & suffix, dest)
  42. else:
  43. dest.add(s)
  44. when options.hasTinyCBackend:
  45. import tccgen
  46. proc hcrOn(m: BModule): bool = m.config.hcrOn
  47. proc hcrOn(p: BProc): bool = p.module.config.hcrOn
  48. proc addForwardedProc(m: BModule, prc: PSym) =
  49. m.g.forwardedProcs.add(prc)
  50. proc findPendingModule(m: BModule, s: PSym): BModule =
  51. # TODO fixme
  52. if m.config.symbolFiles == v2Sf:
  53. let ms = s.itemId.module #getModule(s)
  54. result = m.g.modules[ms]
  55. else:
  56. var ms = getModule(s)
  57. result = m.g.modules[ms.position]
  58. proc initLoc(k: TLocKind, lode: PNode, s: TStorageLoc, flags: TLocFlags = {}): TLoc =
  59. result = TLoc(k: k, storage: s, lode: lode,
  60. r: "", flags: flags
  61. )
  62. proc fillLoc(a: var TLoc, k: TLocKind, lode: PNode, r: Rope, s: TStorageLoc) {.inline.} =
  63. # fills the loc if it is not already initialized
  64. if a.k == locNone:
  65. a.k = k
  66. a.lode = lode
  67. a.storage = s
  68. if a.r == "": a.r = r
  69. proc fillLoc(a: var TLoc, k: TLocKind, lode: PNode, s: TStorageLoc) {.inline.} =
  70. # fills the loc if it is not already initialized
  71. if a.k == locNone:
  72. a.k = k
  73. a.lode = lode
  74. a.storage = s
  75. proc t(a: TLoc): PType {.inline.} =
  76. if a.lode.kind == nkSym:
  77. result = a.lode.sym.typ
  78. else:
  79. result = a.lode.typ
  80. proc lodeTyp(t: PType): PNode =
  81. result = newNode(nkEmpty)
  82. result.typ = t
  83. proc isSimpleConst(typ: PType): bool =
  84. let t = skipTypes(typ, abstractVar)
  85. result = t.kind notin
  86. {tyTuple, tyObject, tyArray, tySet, tySequence} and not
  87. (t.kind == tyProc and t.callConv == ccClosure)
  88. proc useHeader(m: BModule, sym: PSym) =
  89. if lfHeader in sym.loc.flags:
  90. assert(sym.annex != nil)
  91. let str = getStr(sym.annex.path)
  92. m.includeHeader(str)
  93. proc cgsym(m: BModule, name: string)
  94. proc cgsymValue(m: BModule, name: string): Rope
  95. proc getCFile(m: BModule): AbsoluteFile
  96. proc getModuleDllPath(m: BModule): Rope =
  97. let (dir, name, ext) = splitFile(getCFile(m))
  98. let filename = strutils.`%`(platform.OS[m.g.config.target.targetOS].dllFrmt, [name & ext])
  99. result = makeCString(dir.string & "/" & filename)
  100. proc getModuleDllPath(m: BModule, module: int): Rope =
  101. result = getModuleDllPath(m.g.modules[module])
  102. proc getModuleDllPath(m: BModule, s: PSym): Rope =
  103. result = getModuleDllPath(m.g.modules[s.itemId.module])
  104. import std/macros
  105. proc cgFormatValue(result: var string; value: string) =
  106. result.add value
  107. proc cgFormatValue(result: var string; value: BiggestInt) =
  108. result.addInt value
  109. proc cgFormatValue(result: var string; value: Int128) =
  110. result.addInt128 value
  111. # TODO: please document
  112. macro ropecg(m: BModule, frmt: static[FormatStr], args: untyped): Rope =
  113. args.expectKind nnkBracket
  114. # echo "ropecg ", newLit(frmt).repr, ", ", args.repr
  115. var i = 0
  116. result = nnkStmtListExpr.newTree()
  117. result.add quote do:
  118. assert `m` != nil
  119. let resVar = genSym(nskVar, "res")
  120. # during `koch boot` the median of all generates strings from this
  121. # macro is around 40 bytes in length.
  122. result.add newVarStmt(resVar, newCall(bindSym"newStringOfCap", newLit(80)))
  123. let formatValue = bindSym"cgFormatValue"
  124. var num = 0
  125. var strLit = ""
  126. template flushStrLit() =
  127. if strLit != "":
  128. result.add newCall(ident "add", resVar, newLit(strLit))
  129. strLit.setLen 0
  130. while i < frmt.len:
  131. if frmt[i] == '$':
  132. inc(i) # skip '$'
  133. case frmt[i]
  134. of '$':
  135. strLit.add '$'
  136. inc(i)
  137. of '#':
  138. flushStrLit()
  139. inc(i)
  140. result.add newCall(formatValue, resVar, args[num])
  141. inc(num)
  142. of '^':
  143. flushStrLit()
  144. inc(i)
  145. result.add newCall(formatValue, resVar, args[^1])
  146. inc(num)
  147. of '0'..'9':
  148. var j = 0
  149. while true:
  150. j = (j * 10) + ord(frmt[i]) - ord('0')
  151. inc(i)
  152. if i >= frmt.len or not (frmt[i] in {'0'..'9'}): break
  153. num = j
  154. if j > args.len:
  155. error("ropes: invalid format string " & newLit(frmt).repr & " args.len: " & $args.len)
  156. flushStrLit()
  157. result.add newCall(formatValue, resVar, args[j-1])
  158. of 'n':
  159. flushStrLit()
  160. result.add quote do:
  161. if optLineDir notin `m`.config.options:
  162. `resVar`.add("\L")
  163. inc(i)
  164. of 'N':
  165. strLit.add "\L"
  166. inc(i)
  167. else:
  168. error("ropes: invalid format string $" & frmt[i])
  169. elif frmt[i] == '#' and frmt[i+1] in IdentStartChars:
  170. inc(i)
  171. var j = i
  172. while frmt[j] in IdentChars: inc(j)
  173. var ident = newLit(substr(frmt, i, j-1))
  174. i = j
  175. flushStrLit()
  176. result.add newCall(formatValue, resVar, newCall(ident"cgsymValue", m, ident))
  177. elif frmt[i] == '#' and frmt[i+1] == '$':
  178. inc(i, 2)
  179. var j = 0
  180. while frmt[i] in Digits:
  181. j = (j * 10) + ord(frmt[i]) - ord('0')
  182. inc(i)
  183. let ident = args[j-1]
  184. flushStrLit()
  185. result.add newCall(formatValue, resVar, newCall(ident"cgsymValue", m, ident))
  186. elif frmt[i] == '#' and frmt[i+1] == '#':
  187. inc(i, 2)
  188. strLit.add("#")
  189. else:
  190. strLit.add(frmt[i])
  191. inc(i)
  192. flushStrLit()
  193. result.add newCall(ident"rope", resVar)
  194. proc addIndent(p: BProc; result: var Rope) =
  195. var i = result.len
  196. let newLen = i + p.blocks.len
  197. result.setLen newLen
  198. while i < newLen:
  199. result[i] = '\t'
  200. inc i
  201. template appcg(m: BModule, c: var Rope, frmt: FormatStr,
  202. args: untyped) =
  203. c.add(ropecg(m, frmt, args))
  204. template appcg(m: BModule, sec: TCFileSection, frmt: FormatStr,
  205. args: untyped) =
  206. m.s[sec].add(ropecg(m, frmt, args))
  207. template appcg(p: BProc, sec: TCProcSection, frmt: FormatStr,
  208. args: untyped) =
  209. p.s(sec).add(ropecg(p.module, frmt, args))
  210. template line(p: BProc, sec: TCProcSection, r: string) =
  211. addIndent p, p.s(sec)
  212. p.s(sec).add(r)
  213. template lineF(p: BProc, sec: TCProcSection, frmt: FormatStr,
  214. args: untyped) =
  215. addIndent p, p.s(sec)
  216. p.s(sec).add(frmt % args)
  217. template lineCg(p: BProc, sec: TCProcSection, frmt: FormatStr,
  218. args: untyped) =
  219. addIndent p, p.s(sec)
  220. p.s(sec).add(ropecg(p.module, frmt, args))
  221. template linefmt(p: BProc, sec: TCProcSection, frmt: FormatStr,
  222. args: untyped) =
  223. addIndent p, p.s(sec)
  224. p.s(sec).add(ropecg(p.module, frmt, args))
  225. proc safeLineNm(info: TLineInfo): int =
  226. result = toLinenumber(info)
  227. if result < 0: result = 0 # negative numbers are not allowed in #line
  228. proc genPostprocessDir(field1, field2, field3: string): string =
  229. result = postprocessDirStart & field1 & postprocessDirSep & field2 & postprocessDirSep & field3 & postprocessDirEnd
  230. proc genCLineDir(r: var Rope, fileIdx: FileIndex, line: int; conf: ConfigRef) =
  231. assert line >= 0
  232. if optLineDir in conf.options and line > 0:
  233. if fileIdx == InvalidFileIdx:
  234. r.add(rope("\n#line " & $line & " \"generated_not_to_break_here\"\n"))
  235. else:
  236. r.add(rope("\n#line " & $line & " FX_" & $fileIdx.int32 & "\n"))
  237. proc genCLineDir(r: var Rope, fileIdx: FileIndex, line: int; p: BProc; info: TLineInfo; lastFileIndex: FileIndex) =
  238. assert line >= 0
  239. if optLineDir in p.config.options and line > 0:
  240. if fileIdx == InvalidFileIdx:
  241. r.add(rope("\n#line " & $line & " \"generated_not_to_break_here\"\n"))
  242. else:
  243. r.add(rope("\n#line " & $line & " FX_" & $fileIdx.int32 & "\n"))
  244. proc genCLineDir(r: var Rope, info: TLineInfo; conf: ConfigRef) =
  245. if optLineDir in conf.options:
  246. genCLineDir(r, info.fileIndex, info.safeLineNm, conf)
  247. proc freshLineInfo(p: BProc; info: TLineInfo): bool =
  248. if p.lastLineInfo.line != info.line or
  249. p.lastLineInfo.fileIndex != info.fileIndex:
  250. p.lastLineInfo.line = info.line
  251. p.lastLineInfo.fileIndex = info.fileIndex
  252. result = true
  253. else:
  254. result = false
  255. proc genCLineDir(r: var Rope, p: BProc, info: TLineInfo; conf: ConfigRef) =
  256. if optLineDir in conf.options:
  257. let lastFileIndex = p.lastLineInfo.fileIndex
  258. if freshLineInfo(p, info):
  259. genCLineDir(r, info.fileIndex, info.safeLineNm, p, info, lastFileIndex)
  260. proc genLineDir(p: BProc, t: PNode) =
  261. if p == p.module.preInitProc: return
  262. let line = t.info.safeLineNm
  263. if optEmbedOrigSrc in p.config.globalOptions:
  264. p.s(cpsStmts).add("//" & sourceLine(p.config, t.info) & "\L")
  265. let lastFileIndex = p.lastLineInfo.fileIndex
  266. let freshLine = freshLineInfo(p, t.info)
  267. if freshLine:
  268. genCLineDir(p.s(cpsStmts), t.info.fileIndex, line, p, t.info, lastFileIndex)
  269. if ({optLineTrace, optStackTrace} * p.options == {optLineTrace, optStackTrace}) and
  270. (p.prc == nil or sfPure notin p.prc.flags) and t.info.fileIndex != InvalidFileIdx:
  271. if freshLine:
  272. line(p, cpsStmts, genPostprocessDir("nimln", $line, $t.info.fileIndex.int32))
  273. proc accessThreadLocalVar(p: BProc, s: PSym)
  274. proc emulatedThreadVars(conf: ConfigRef): bool {.inline.}
  275. proc genProc(m: BModule, prc: PSym)
  276. proc raiseInstr(p: BProc; result: var Rope)
  277. template compileToCpp(m: BModule): untyped =
  278. m.config.backend == backendCpp or sfCompileToCpp in m.module.flags
  279. proc getTempName(m: BModule): Rope =
  280. result = m.tmpBase & rope(m.labels)
  281. inc m.labels
  282. proc rdLoc(a: TLoc): Rope =
  283. # 'read' location (deref if indirect)
  284. if lfIndirect in a.flags:
  285. result = "(*" & a.r & ")"
  286. else:
  287. result = a.r
  288. proc addRdLoc(a: TLoc; result: var Rope) =
  289. if lfIndirect in a.flags:
  290. result.add "(*" & a.r & ")"
  291. else:
  292. result.add a.r
  293. proc lenField(p: BProc): Rope {.inline.} =
  294. result = rope(if p.module.compileToCpp: "len" else: "Sup.len")
  295. proc lenExpr(p: BProc; a: TLoc): Rope =
  296. if optSeqDestructors in p.config.globalOptions:
  297. result = rdLoc(a) & ".len"
  298. else:
  299. result = "($1 ? $1->$2 : 0)" % [rdLoc(a), lenField(p)]
  300. proc dataFieldAccessor(p: BProc, sym: Rope): Rope =
  301. if optSeqDestructors in p.config.globalOptions:
  302. result = "(" & sym & ").p"
  303. else:
  304. result = sym
  305. proc dataField(p: BProc): Rope =
  306. if optSeqDestructors in p.config.globalOptions:
  307. result = rope".p->data"
  308. else:
  309. result = rope"->data"
  310. proc genProcPrototype(m: BModule, sym: PSym)
  311. include ccgliterals
  312. include ccgtypes
  313. # ------------------------------ Manager of temporaries ------------------
  314. template mapTypeChooser(n: PNode): TSymKind =
  315. (if n.kind == nkSym: n.sym.kind else: skVar)
  316. template mapTypeChooser(a: TLoc): TSymKind = mapTypeChooser(a.lode)
  317. proc addAddrLoc(conf: ConfigRef; a: TLoc; result: var Rope) =
  318. if lfIndirect notin a.flags and mapType(conf, a.t, mapTypeChooser(a) == skParam) != ctArray:
  319. result.add "(&" & a.r & ")"
  320. else:
  321. result.add a.r
  322. proc addrLoc(conf: ConfigRef; a: TLoc): Rope =
  323. if lfIndirect notin a.flags and mapType(conf, a.t, mapTypeChooser(a) == skParam) != ctArray:
  324. result = "(&" & a.r & ")"
  325. else:
  326. result = a.r
  327. proc byRefLoc(p: BProc; a: TLoc): Rope =
  328. if lfIndirect notin a.flags and mapType(p.config, a.t, mapTypeChooser(a) == skParam) != ctArray and not
  329. p.module.compileToCpp:
  330. result = "(&" & a.r & ")"
  331. else:
  332. result = a.r
  333. proc rdCharLoc(a: TLoc): Rope =
  334. # read a location that may need a char-cast:
  335. result = rdLoc(a)
  336. if skipTypes(a.t, abstractRange).kind == tyChar:
  337. result = "((NU8)($1))" % [result]
  338. type
  339. TAssignmentFlag = enum
  340. needToCopy
  341. needToCopySinkParam
  342. needTempForOpenArray
  343. TAssignmentFlags = set[TAssignmentFlag]
  344. proc genObjConstr(p: BProc, e: PNode, d: var TLoc)
  345. proc rawConstExpr(p: BProc, n: PNode; d: var TLoc)
  346. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags)
  347. type
  348. ObjConstrMode = enum
  349. constructObj,
  350. constructRefObj
  351. proc genObjectInit(p: BProc, section: TCProcSection, t: PType, a: var TLoc,
  352. mode: ObjConstrMode) =
  353. #if optNimV2 in p.config.globalOptions: return
  354. case analyseObjectWithTypeField(t)
  355. of frNone:
  356. discard
  357. of frHeader:
  358. var r = rdLoc(a)
  359. if mode == constructRefObj: r = "(*$1)" % [r]
  360. var s = skipTypes(t, abstractInst)
  361. if not p.module.compileToCpp:
  362. while s.kind == tyObject and s[0] != nil:
  363. r.add(".Sup")
  364. s = skipTypes(s[0], skipPtrs)
  365. if optTinyRtti in p.config.globalOptions:
  366. linefmt(p, section, "$1.m_type = $2;$n", [r, genTypeInfoV2(p.module, t, a.lode.info)])
  367. else:
  368. linefmt(p, section, "$1.m_type = $2;$n", [r, genTypeInfoV1(p.module, t, a.lode.info)])
  369. of frEmbedded:
  370. if optTinyRtti in p.config.globalOptions:
  371. var tmp: TLoc = default(TLoc)
  372. if mode == constructRefObj:
  373. let objType = t.skipTypes(abstractInst+{tyRef})
  374. rawConstExpr(p, newNodeIT(nkType, a.lode.info, objType), tmp)
  375. linefmt(p, cpsStmts,
  376. "#nimCopyMem((void*)$1, (NIM_CONST void*)&$2, sizeof($3));$n",
  377. [rdLoc(a), rdLoc(tmp), getTypeDesc(p.module, objType, descKindFromSymKind mapTypeChooser(a))])
  378. else:
  379. rawConstExpr(p, newNodeIT(nkType, a.lode.info, t), tmp)
  380. genAssignment(p, a, tmp, {})
  381. else:
  382. # worst case for performance:
  383. var r = if mode == constructObj: addrLoc(p.config, a) else: rdLoc(a)
  384. linefmt(p, section, "#objectInit($1, $2);$n", [r, genTypeInfoV1(p.module, t, a.lode.info)])
  385. if isException(t):
  386. var r = rdLoc(a)
  387. if mode == constructRefObj: r = "(*$1)" % [r]
  388. var s = skipTypes(t, abstractInst)
  389. if not p.module.compileToCpp:
  390. while s.kind == tyObject and s[0] != nil and s.sym.magic != mException:
  391. r.add(".Sup")
  392. s = skipTypes(s[0], skipPtrs)
  393. linefmt(p, section, "$1.name = $2;$n", [r, makeCString(t.skipTypes(abstractInst).sym.name.s)])
  394. proc genRefAssign(p: BProc, dest, src: TLoc)
  395. proc isComplexValueType(t: PType): bool {.inline.} =
  396. let t = t.skipTypes(abstractInst + tyUserTypeClasses)
  397. result = t.kind in {tyArray, tySet, tyTuple, tyObject, tyOpenArray} or
  398. (t.kind == tyProc and t.callConv == ccClosure)
  399. include ccgreset
  400. proc resetLoc(p: BProc, loc: var TLoc) =
  401. let containsGcRef = optSeqDestructors notin p.config.globalOptions and containsGarbageCollectedRef(loc.t)
  402. let typ = skipTypes(loc.t, abstractVarRange)
  403. if isImportedCppType(typ): return
  404. if optSeqDestructors in p.config.globalOptions and typ.kind in {tyString, tySequence}:
  405. assert loc.r != ""
  406. let atyp = skipTypes(loc.t, abstractInst)
  407. if atyp.kind in {tyVar, tyLent}:
  408. linefmt(p, cpsStmts, "$1->len = 0; $1->p = NIM_NIL;$n", [rdLoc(loc)])
  409. else:
  410. linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
  411. elif not isComplexValueType(typ):
  412. if containsGcRef:
  413. var nilLoc: TLoc = initLoc(locTemp, loc.lode, OnStack)
  414. nilLoc.r = rope("NIM_NIL")
  415. genRefAssign(p, loc, nilLoc)
  416. else:
  417. linefmt(p, cpsStmts, "$1 = 0;$n", [rdLoc(loc)])
  418. else:
  419. if loc.storage != OnStack and containsGcRef:
  420. specializeReset(p, loc)
  421. when false:
  422. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  423. [addrLoc(p.config, loc), genTypeInfoV1(p.module, loc.t, loc.lode.info)])
  424. # XXX: generated reset procs should not touch the m_type
  425. # field, so disabling this should be safe:
  426. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  427. else:
  428. # array passed as argument decayed into pointer, bug #7332
  429. # so we use getTypeDesc here rather than rdLoc(loc)
  430. let tyDesc = getTypeDesc(p.module, loc.t, descKindFromSymKind mapTypeChooser(loc))
  431. if p.module.compileToCpp and isOrHasImportedCppType(typ):
  432. if lfIndirect in loc.flags:
  433. #C++ cant be just zeroed. We need to call the ctors
  434. var tmp = getTemp(p, loc.t)
  435. linefmt(p, cpsStmts,"#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  436. [addrLoc(p.config, loc), addrLoc(p.config, tmp), tyDesc])
  437. else:
  438. linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  439. [addrLoc(p.config, loc), tyDesc])
  440. # XXX: We can be extra clever here and call memset only
  441. # on the bytes following the m_type field?
  442. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  443. proc constructLoc(p: BProc, loc: var TLoc, isTemp = false) =
  444. let typ = loc.t
  445. if optSeqDestructors in p.config.globalOptions and skipTypes(typ, abstractInst + {tyStatic}).kind in {tyString, tySequence}:
  446. linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
  447. elif not isComplexValueType(typ):
  448. if containsGarbageCollectedRef(loc.t):
  449. var nilLoc: TLoc = initLoc(locTemp, loc.lode, OnStack)
  450. nilLoc.r = rope("NIM_NIL")
  451. genRefAssign(p, loc, nilLoc)
  452. else:
  453. linefmt(p, cpsStmts, "$1 = ($2)0;$n", [rdLoc(loc),
  454. getTypeDesc(p.module, typ, descKindFromSymKind mapTypeChooser(loc))])
  455. else:
  456. if (not isTemp or containsGarbageCollectedRef(loc.t)) and not hasNoInit(loc.t):
  457. # don't use nimZeroMem for temporary values for performance if we can
  458. # avoid it:
  459. if not isOrHasImportedCppType(typ):
  460. linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  461. [addrLoc(p.config, loc), getTypeDesc(p.module, typ, descKindFromSymKind mapTypeChooser(loc))])
  462. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  463. proc initLocalVar(p: BProc, v: PSym, immediateAsgn: bool) =
  464. if sfNoInit notin v.flags:
  465. # we know it is a local variable and thus on the stack!
  466. # If ``not immediateAsgn`` it is not initialized in a binding like
  467. # ``var v = X`` and thus we need to init it.
  468. # If ``v`` contains a GC-ref we may pass it to ``unsureAsgnRef`` somehow
  469. # which requires initialization. However this can really only happen if
  470. # ``var v = X()`` gets transformed into ``X(&v)``.
  471. # Nowadays the logic in ccgcalls deals with this case however.
  472. if not immediateAsgn:
  473. constructLoc(p, v.loc)
  474. proc getTemp(p: BProc, t: PType, needsInit=false): TLoc =
  475. inc(p.labels)
  476. result = TLoc(r: "T" & rope(p.labels) & "_", k: locTemp, lode: lodeTyp t,
  477. storage: OnStack, flags: {})
  478. if p.module.compileToCpp and isOrHasImportedCppType(t):
  479. var didGenTemp = false
  480. linefmt(p, cpsLocals, "$1 $2$3;$n", [getTypeDesc(p.module, t, dkVar), result.r,
  481. genCppInitializer(p.module, p, t, didGenTemp)])
  482. else:
  483. linefmt(p, cpsLocals, "$1 $2;$n", [getTypeDesc(p.module, t, dkVar), result.r])
  484. constructLoc(p, result, not needsInit)
  485. when false:
  486. # XXX Introduce a compiler switch in order to detect these easily.
  487. if getSize(p.config, t) > 1024 * 1024:
  488. if p.prc != nil:
  489. echo "ENORMOUS TEMPORARY! ", p.config $ p.prc.info
  490. else:
  491. echo "ENORMOUS TEMPORARY! ", p.config $ p.lastLineInfo
  492. writeStackTrace()
  493. proc getTempCpp(p: BProc, t: PType, value: Rope): TLoc =
  494. inc(p.labels)
  495. result = TLoc(r: "T" & rope(p.labels) & "_", k: locTemp, lode: lodeTyp t,
  496. storage: OnStack, flags: {})
  497. linefmt(p, cpsStmts, "auto $1 = $2;$n", [result.r, value])
  498. proc getIntTemp(p: BProc): TLoc =
  499. inc(p.labels)
  500. result = TLoc(r: "T" & rope(p.labels) & "_", k: locTemp,
  501. storage: OnStack, lode: lodeTyp getSysType(p.module.g.graph, unknownLineInfo, tyInt),
  502. flags: {})
  503. linefmt(p, cpsLocals, "NI $1;$n", [result.r])
  504. proc localVarDecl(p: BProc; n: PNode): Rope =
  505. result = ""
  506. let s = n.sym
  507. if s.loc.k == locNone:
  508. fillLocalName(p, s)
  509. fillLoc(s.loc, locLocalVar, n, OnStack)
  510. if s.kind == skLet: incl(s.loc.flags, lfNoDeepCopy)
  511. if s.kind in {skLet, skVar, skField, skForVar} and s.alignment > 0:
  512. result.addf("NIM_ALIGN($1) ", [rope(s.alignment)])
  513. genCLineDir(result, p, n.info, p.config)
  514. result.add getTypeDesc(p.module, s.typ, dkVar)
  515. if sfCodegenDecl notin s.flags:
  516. if sfRegister in s.flags: result.add(" register")
  517. #elif skipTypes(s.typ, abstractInst).kind in GcTypeKinds:
  518. # decl.add(" GC_GUARD")
  519. if sfVolatile in s.flags: result.add(" volatile")
  520. if sfNoalias in s.flags: result.add(" NIM_NOALIAS")
  521. result.add(" ")
  522. result.add(s.loc.r)
  523. else:
  524. result = runtimeFormat(s.cgDeclFrmt, [result, s.loc.r])
  525. proc assignLocalVar(p: BProc, n: PNode) =
  526. #assert(s.loc.k == locNone) # not yet assigned
  527. # this need not be fulfilled for inline procs; they are regenerated
  528. # for each module that uses them!
  529. let nl = if optLineDir in p.config.options: "" else: "\n"
  530. var decl = localVarDecl(p, n)
  531. if p.module.compileToCpp and isOrHasImportedCppType(n.typ):
  532. var didGenTemp = false
  533. decl.add genCppInitializer(p.module, p, n.typ, didGenTemp)
  534. decl.add ";" & nl
  535. line(p, cpsLocals, decl)
  536. include ccgthreadvars
  537. proc varInDynamicLib(m: BModule, sym: PSym)
  538. proc treatGlobalDifferentlyForHCR(m: BModule, s: PSym): bool =
  539. return m.hcrOn and {sfThread, sfGlobal} * s.flags == {sfGlobal} and
  540. ({lfNoDecl, lfHeader} * s.loc.flags == {})
  541. # and s.owner.kind == skModule # owner isn't always a module (global pragma on local var)
  542. # and s.loc.k == locGlobalVar # loc isn't always initialized when this proc is used
  543. proc genGlobalVarDecl(p: BProc, n: PNode; td, value: Rope; decl: var Rope) =
  544. let s = n.sym
  545. if sfCodegenDecl notin s.flags:
  546. if s.kind in {skLet, skVar, skField, skForVar} and s.alignment > 0:
  547. decl.addf "NIM_ALIGN($1) ", [rope(s.alignment)]
  548. if p.hcrOn: decl.add("static ")
  549. elif sfImportc in s.flags: decl.add("extern ")
  550. elif lfExportLib in s.loc.flags: decl.add("N_LIB_EXPORT_VAR ")
  551. else: decl.add("N_LIB_PRIVATE ")
  552. if s.kind == skLet and value != "": decl.add("NIM_CONST ")
  553. decl.add(td)
  554. if p.hcrOn: decl.add("*")
  555. if sfRegister in s.flags: decl.add(" register")
  556. if sfVolatile in s.flags: decl.add(" volatile")
  557. if sfNoalias in s.flags: decl.add(" NIM_NOALIAS")
  558. else:
  559. if value != "":
  560. decl = runtimeFormat(s.cgDeclFrmt & " = $#;$n", [td, s.loc.r, value])
  561. else:
  562. decl = runtimeFormat(s.cgDeclFrmt & ";$n", [td, s.loc.r])
  563. proc genCppVarForCtor(p: BProc; call: PNode; decl: var Rope; didGenTemp: var bool)
  564. proc assignGlobalVar(p: BProc, n: PNode; value: Rope) =
  565. let s = n.sym
  566. if s.loc.k == locNone:
  567. fillBackendName(p.module, s)
  568. fillLoc(s.loc, locGlobalVar, n, OnHeap)
  569. if treatGlobalDifferentlyForHCR(p.module, s): incl(s.loc.flags, lfIndirect)
  570. if lfDynamicLib in s.loc.flags:
  571. var q = findPendingModule(p.module, s)
  572. if q != nil and not containsOrIncl(q.declaredThings, s.id):
  573. varInDynamicLib(q, s)
  574. else:
  575. s.loc.r = mangleDynLibProc(s)
  576. if value != "":
  577. internalError(p.config, n.info, ".dynlib variables cannot have a value")
  578. return
  579. useHeader(p.module, s)
  580. if lfNoDecl in s.loc.flags: return
  581. if not containsOrIncl(p.module.declaredThings, s.id):
  582. if sfThread in s.flags:
  583. declareThreadVar(p.module, s, sfImportc in s.flags)
  584. if value != "":
  585. internalError(p.config, n.info, ".threadvar variables cannot have a value")
  586. else:
  587. var decl: Rope = ""
  588. let td = getTypeDesc(p.module, s.loc.t, dkVar)
  589. genGlobalVarDecl(p, n, td, value, decl)
  590. if s.constraint.isNil:
  591. if value != "":
  592. if p.module.compileToCpp and value.startsWith "{{}":
  593. # TODO: taking this branch, re"\{\{\}(,\s\{\})*\}" might be emitted, resulting in
  594. # either warnings (GCC 12.2+) or errors (Clang 15, MSVC 19.3+) of C++11+ compilers **when
  595. # explicit constructors are around** due to overload resolution rules in place [^0][^1][^2]
  596. # *Workaround* here: have C++'s static initialization mechanism do the default init work,
  597. # for us lacking a deeper knowledge of an imported object's constructors' ex-/implicitness
  598. # (so far) *and yet* trying to achieve default initialization.
  599. # Still, generating {}s in genConstObjConstr() just to omit them here is faaaar from ideal;
  600. # need to figure out a better way, possibly by keeping around more data about the
  601. # imported objects' contructors?
  602. #
  603. # [^0]: https://en.cppreference.com/w/cpp/language/aggregate_initialization
  604. # [^1]: https://cplusplus.github.io/CWG/issues/1518.html
  605. # [^2]: https://eel.is/c++draft/over.match.ctor
  606. decl.addf(" $1;$n", [s.loc.r])
  607. else:
  608. decl.addf(" $1 = $2;$n", [s.loc.r, value])
  609. else:
  610. decl.addf(" $1;$n", [s.loc.r])
  611. p.module.s[cfsVars].add(decl)
  612. if p.withinLoop > 0 and value == "":
  613. # fixes tests/run/tzeroarray:
  614. resetLoc(p, s.loc)
  615. proc callGlobalVarCppCtor(p: BProc; v: PSym; vn, value: PNode; didGenTemp: var bool) =
  616. let s = vn.sym
  617. fillBackendName(p.module, s)
  618. fillLoc(s.loc, locGlobalVar, vn, OnHeap)
  619. var decl: Rope = ""
  620. let td = getTypeDesc(p.module, vn.sym.typ, dkVar)
  621. genGlobalVarDecl(p, vn, td, "", decl)
  622. decl.add " " & $s.loc.r
  623. genCppVarForCtor(p, value, decl, didGenTemp)
  624. if didGenTemp: return # generated in the caller
  625. p.module.s[cfsVars].add decl
  626. proc assignParam(p: BProc, s: PSym, retType: PType) =
  627. assert(s.loc.r != "")
  628. scopeMangledParam(p, s)
  629. proc fillProcLoc(m: BModule; n: PNode) =
  630. let sym = n.sym
  631. if sym.loc.k == locNone:
  632. fillBackendName(m, sym)
  633. fillLoc(sym.loc, locProc, n, OnStack)
  634. proc getLabel(p: BProc): TLabel =
  635. inc(p.labels)
  636. result = "LA" & rope(p.labels) & "_"
  637. proc fixLabel(p: BProc, labl: TLabel) =
  638. p.s(cpsStmts).add("$1: ;$n" % [labl])
  639. proc genVarPrototype(m: BModule, n: PNode)
  640. proc requestConstImpl(p: BProc, sym: PSym)
  641. proc genStmts(p: BProc, t: PNode)
  642. proc expr(p: BProc, n: PNode, d: var TLoc)
  643. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc)
  644. proc intLiteral(i: BiggestInt; result: var Rope)
  645. proc genLiteral(p: BProc, n: PNode; result: var Rope)
  646. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope; argsCounter: var int)
  647. proc raiseExit(p: BProc)
  648. proc raiseExitCleanup(p: BProc, destroy: string)
  649. proc initLocExpr(p: BProc, e: PNode, flags: TLocFlags = {}): TLoc =
  650. result = initLoc(locNone, e, OnUnknown, flags)
  651. expr(p, e, result)
  652. proc initLocExprSingleUse(p: BProc, e: PNode): TLoc =
  653. result = initLoc(locNone, e, OnUnknown)
  654. if e.kind in nkCallKinds and (e[0].kind != nkSym or e[0].sym.magic == mNone):
  655. # We cannot check for tfNoSideEffect here because of mutable parameters.
  656. discard "bug #8202; enforce evaluation order for nested calls for C++ too"
  657. # We may need to consider that 'f(g())' cannot be rewritten to 'tmp = g(); f(tmp)'
  658. # if 'tmp' lacks a move/assignment operator.
  659. if e[0].kind == nkSym and sfCompileToCpp in e[0].sym.flags:
  660. result.flags.incl lfSingleUse
  661. else:
  662. result.flags.incl lfSingleUse
  663. expr(p, e, result)
  664. include ccgcalls, "ccgstmts.nim"
  665. proc initFrame(p: BProc, procname, filename: Rope): Rope =
  666. const frameDefines = """
  667. $1define nimfr_(proc, file) \
  668. TFrame FR_; \
  669. FR_.procname = proc; FR_.filename = file; FR_.line = 0; FR_.len = 0; #nimFrame(&FR_);
  670. $1define nimfrs_(proc, file, slots, length) \
  671. struct {TFrame* prev;NCSTRING procname;NI line;NCSTRING filename;NI len;VarSlot s[slots];} FR_; \
  672. FR_.procname = proc; FR_.filename = file; FR_.line = 0; FR_.len = length; #nimFrame((TFrame*)&FR_);
  673. $1define nimln_(n) \
  674. FR_.line = n;
  675. $1define nimlf_(n, file) \
  676. FR_.line = n; FR_.filename = file;
  677. """
  678. if p.module.s[cfsFrameDefines].len == 0:
  679. appcg(p.module, p.module.s[cfsFrameDefines], frameDefines, ["#"])
  680. cgsym(p.module, "nimFrame")
  681. result = ropecg(p.module, "\tnimfr_($1, $2);$n", [procname, filename])
  682. proc initFrameNoDebug(p: BProc; frame, procname, filename: Rope; line: int): Rope =
  683. cgsym(p.module, "nimFrame")
  684. p.blocks[0].sections[cpsLocals].addf("TFrame $1;$n", [frame])
  685. result = ropecg(p.module, "\t$1.procname = $2; $1.filename = $3; " &
  686. " $1.line = $4; $1.len = -1; nimFrame(&$1);$n",
  687. [frame, procname, filename, line])
  688. proc deinitFrameNoDebug(p: BProc; frame: Rope): Rope =
  689. result = ropecg(p.module, "\t#popFrameOfAddr(&$1);$n", [frame])
  690. proc deinitFrame(p: BProc): Rope =
  691. result = ropecg(p.module, "\t#popFrame();$n", [])
  692. include ccgexprs
  693. # ----------------------------- dynamic library handling -----------------
  694. # We don't finalize dynamic libs as the OS does this for us.
  695. proc isGetProcAddr(lib: PLib): bool =
  696. let n = lib.path
  697. result = n.kind in nkCallKinds and n.typ != nil and
  698. n.typ.kind in {tyPointer, tyProc}
  699. proc loadDynamicLib(m: BModule, lib: PLib) =
  700. assert(lib != nil)
  701. if not lib.generated:
  702. lib.generated = true
  703. var tmp = getTempName(m)
  704. assert(lib.name == "")
  705. lib.name = tmp # BUGFIX: cgsym has awful side-effects
  706. m.s[cfsVars].addf("static void* $1;$n", [tmp])
  707. if lib.path.kind in {nkStrLit..nkTripleStrLit}:
  708. var s: TStringSeq = @[]
  709. libCandidates(lib.path.strVal, s)
  710. rawMessage(m.config, hintDependency, lib.path.strVal)
  711. var loadlib: Rope = ""
  712. for i in 0..high(s):
  713. inc(m.labels)
  714. if i > 0: loadlib.add("||")
  715. let n = newStrNode(nkStrLit, s[i])
  716. n.info = lib.path.info
  717. appcg(m, loadlib, "($1 = #nimLoadLibrary(", [tmp])
  718. genStringLiteral(m, n, loadlib)
  719. loadlib.addf "))$n", []
  720. appcg(m, m.s[cfsDynLibInit],
  721. "if (!($1)) #nimLoadLibraryError(",
  722. [loadlib])
  723. genStringLiteral(m, lib.path, m.s[cfsDynLibInit])
  724. m.s[cfsDynLibInit].addf ");$n", []
  725. else:
  726. var p = newProc(nil, m)
  727. p.options.excl optStackTrace
  728. p.flags.incl nimErrorFlagDisabled
  729. var dest: TLoc = initLoc(locTemp, lib.path, OnStack)
  730. dest.r = getTempName(m)
  731. appcg(m, m.s[cfsDynLibInit],"$1 $2;$n",
  732. [getTypeDesc(m, lib.path.typ, dkVar), rdLoc(dest)])
  733. expr(p, lib.path, dest)
  734. m.s[cfsVars].add(p.s(cpsLocals))
  735. m.s[cfsDynLibInit].add(p.s(cpsInit))
  736. m.s[cfsDynLibInit].add(p.s(cpsStmts))
  737. appcg(m, m.s[cfsDynLibInit],
  738. "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n",
  739. [tmp, rdLoc(dest)])
  740. if lib.name == "": internalError(m.config, "loadDynamicLib")
  741. proc mangleDynLibProc(sym: PSym): Rope =
  742. # we have to build this as a single rope in order not to trip the
  743. # optimization in genInfixCall, see test tests/cpp/t8241.nim
  744. if sfCompilerProc in sym.flags:
  745. # NOTE: sym.loc.r is the external name!
  746. result = rope(sym.name.s)
  747. else:
  748. result = rope(strutils.`%`("Dl_$1_", $sym.id))
  749. proc symInDynamicLib(m: BModule, sym: PSym) =
  750. var lib = sym.annex
  751. let isCall = isGetProcAddr(lib)
  752. var extname = sym.loc.r
  753. if not isCall: loadDynamicLib(m, lib)
  754. var tmp = mangleDynLibProc(sym)
  755. sym.loc.r = tmp # from now on we only need the internal name
  756. sym.typ.sym = nil # generate a new name
  757. inc(m.labels, 2)
  758. if isCall:
  759. let n = lib.path
  760. var a: TLoc = initLocExpr(m.initProc, n[0])
  761. var params = rdLoc(a) & "("
  762. for i in 1..<n.len-1:
  763. a = initLocExpr(m.initProc, n[i])
  764. params.add(rdLoc(a))
  765. params.add(", ")
  766. let load = "\t$1 = ($2) ($3$4));$n" %
  767. [tmp, getTypeDesc(m, sym.typ, dkVar), params, makeCString($extname)]
  768. var last = lastSon(n)
  769. if last.kind == nkHiddenStdConv: last = last[1]
  770. internalAssert(m.config, last.kind == nkStrLit)
  771. let idx = last.strVal
  772. if idx.len == 0:
  773. m.initProc.s(cpsStmts).add(load)
  774. elif idx.len == 1 and idx[0] in {'0'..'9'}:
  775. m.extensionLoaders[idx[0]].add(load)
  776. else:
  777. internalError(m.config, sym.info, "wrong index: " & idx)
  778. else:
  779. appcg(m, m.s[cfsDynLibInit],
  780. "\t$1 = ($2) #nimGetProcAddr($3, $4);$n",
  781. [tmp, getTypeDesc(m, sym.typ, dkVar), lib.name, makeCString($extname)])
  782. m.s[cfsVars].addf("$2 $1;$n", [sym.loc.r, getTypeDesc(m, sym.loc.t, dkVar)])
  783. proc varInDynamicLib(m: BModule, sym: PSym) =
  784. var lib = sym.annex
  785. var extname = sym.loc.r
  786. loadDynamicLib(m, lib)
  787. incl(sym.loc.flags, lfIndirect)
  788. var tmp = mangleDynLibProc(sym)
  789. sym.loc.r = tmp # from now on we only need the internal name
  790. inc(m.labels, 2)
  791. appcg(m, m.s[cfsDynLibInit],
  792. "$1 = ($2*) #nimGetProcAddr($3, $4);$n",
  793. [tmp, getTypeDesc(m, sym.typ, dkVar), lib.name, makeCString($extname)])
  794. m.s[cfsVars].addf("$2* $1;$n",
  795. [sym.loc.r, getTypeDesc(m, sym.loc.t, dkVar)])
  796. proc symInDynamicLibPartial(m: BModule, sym: PSym) =
  797. sym.loc.r = mangleDynLibProc(sym)
  798. sym.typ.sym = nil # generate a new name
  799. proc cgsymImpl(m: BModule; sym: PSym) {.inline.} =
  800. case sym.kind
  801. of skProc, skFunc, skMethod, skConverter, skIterator: genProc(m, sym)
  802. of skVar, skResult, skLet: genVarPrototype(m, newSymNode sym)
  803. of skType: discard getTypeDesc(m, sym.typ)
  804. else: internalError(m.config, "cgsym: " & $sym.kind)
  805. proc cgsym(m: BModule, name: string) =
  806. let sym = magicsys.getCompilerProc(m.g.graph, name)
  807. if sym != nil:
  808. cgsymImpl m, sym
  809. else:
  810. rawMessage(m.config, errGenerated, "system module needs: " & name)
  811. proc cgsymValue(m: BModule, name: string): Rope =
  812. let sym = magicsys.getCompilerProc(m.g.graph, name)
  813. if sym != nil:
  814. cgsymImpl m, sym
  815. else:
  816. rawMessage(m.config, errGenerated, "system module needs: " & name)
  817. result = sym.loc.r
  818. if m.hcrOn and sym != nil and sym.kind in {skProc..skIterator}:
  819. result.addActualSuffixForHCR(m.module, sym)
  820. proc generateHeaders(m: BModule) =
  821. var nimbase = m.config.nimbasePattern
  822. if nimbase == "": nimbase = "nimbase.h"
  823. m.s[cfsHeaders].addf("\L#include \"$1\"\L", [nimbase])
  824. for it in m.headerFiles:
  825. if it[0] == '#':
  826. m.s[cfsHeaders].add(rope(it.replace('`', '"') & "\L"))
  827. elif it[0] notin {'"', '<'}:
  828. m.s[cfsHeaders].addf("#include \"$1\"$N", [rope(it)])
  829. else:
  830. m.s[cfsHeaders].addf("#include $1$N", [rope(it)])
  831. m.s[cfsHeaders].add("""#undef LANGUAGE_C
  832. #undef MIPSEB
  833. #undef MIPSEL
  834. #undef PPC
  835. #undef R3000
  836. #undef R4000
  837. #undef i386
  838. #undef linux
  839. #undef mips
  840. #undef near
  841. #undef far
  842. #undef powerpc
  843. #undef unix
  844. """)
  845. proc openNamespaceNim(namespace: string; result: var Rope) =
  846. result.add("namespace ")
  847. result.add(namespace)
  848. result.add(" {\L")
  849. proc closeNamespaceNim(result: var Rope) =
  850. result.add("}\L")
  851. proc closureSetup(p: BProc, prc: PSym) =
  852. if tfCapturesEnv notin prc.typ.flags: return
  853. # prc.ast[paramsPos].last contains the type we're after:
  854. var ls = lastSon(prc.ast[paramsPos])
  855. if ls.kind != nkSym:
  856. internalError(p.config, prc.info, "closure generation failed")
  857. var env = ls.sym
  858. #echo "created environment: ", env.id, " for ", prc.name.s
  859. assignLocalVar(p, ls)
  860. # generate cast assignment:
  861. if p.config.selectedGC == gcGo:
  862. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, ($2) ClE_0);$n",
  863. [addrLoc(p.config, env.loc), getTypeDesc(p.module, env.typ)])
  864. else:
  865. linefmt(p, cpsStmts, "$1 = ($2) ClE_0;$n",
  866. [rdLoc(env.loc), getTypeDesc(p.module, env.typ)])
  867. const harmless = {nkConstSection, nkTypeSection, nkEmpty, nkCommentStmt, nkTemplateDef,
  868. nkMacroDef, nkMixinStmt, nkBindStmt, nkFormalParams} +
  869. declarativeDefs
  870. proc containsResult(n: PNode): bool =
  871. result = false
  872. case n.kind
  873. of succ(nkEmpty)..pred(nkSym), succ(nkSym)..nkNilLit, harmless:
  874. discard
  875. of nkReturnStmt:
  876. for i in 0..<n.len:
  877. if containsResult(n[i]): return true
  878. result = n.len > 0 and n[0].kind == nkEmpty
  879. of nkSym:
  880. if n.sym.kind == skResult:
  881. result = true
  882. else:
  883. for i in 0..<n.len:
  884. if containsResult(n[i]): return true
  885. proc easyResultAsgn(n: PNode): PNode =
  886. result = nil
  887. case n.kind
  888. of nkStmtList, nkStmtListExpr:
  889. var i = 0
  890. while i < n.len and n[i].kind in harmless: inc i
  891. if i < n.len: result = easyResultAsgn(n[i])
  892. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  893. if n[0].kind == nkSym and n[0].sym.kind == skResult and not containsResult(n[1]):
  894. incl n.flags, nfPreventCg
  895. return n[1]
  896. of nkReturnStmt:
  897. if n.len > 0:
  898. result = easyResultAsgn(n[0])
  899. if result != nil: incl n.flags, nfPreventCg
  900. else: discard
  901. type
  902. InitResultEnum = enum Unknown, InitSkippable, InitRequired
  903. proc allPathsAsgnResult(p: BProc; n: PNode): InitResultEnum =
  904. # Exceptions coming from calls don't have not be considered here:
  905. #
  906. # proc bar(): string = raise newException(...)
  907. #
  908. # proc foo(): string =
  909. # # optimized out: 'reset(result)'
  910. # result = bar()
  911. #
  912. # try:
  913. # a = foo()
  914. # except:
  915. # echo "a was not written to"
  916. #
  917. template allPathsInBranch(it) =
  918. let a = allPathsAsgnResult(p, it)
  919. case a
  920. of InitRequired: return InitRequired
  921. of InitSkippable: discard
  922. of Unknown:
  923. # sticky, but can be overwritten by InitRequired:
  924. result = Unknown
  925. result = Unknown
  926. case n.kind
  927. of nkStmtList, nkStmtListExpr:
  928. for it in n:
  929. result = allPathsAsgnResult(p, it)
  930. if result != Unknown: return result
  931. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  932. if n[0].kind == nkSym and n[0].sym.kind == skResult:
  933. if not containsResult(n[1]):
  934. if allPathsAsgnResult(p, n[1]) == InitRequired:
  935. result = InitRequired
  936. else:
  937. result = InitSkippable
  938. else: result = InitRequired
  939. elif containsResult(n):
  940. result = InitRequired
  941. else:
  942. result = allPathsAsgnResult(p, n[1])
  943. of nkReturnStmt:
  944. if n.len > 0:
  945. if n[0].kind == nkEmpty and result != InitSkippable:
  946. # This is a bare `return` statement, if `result` was not initialized
  947. # anywhere else (or if we're not sure about this) let's require it to be
  948. # initialized. This avoids cases like #9286 where this heuristic lead to
  949. # wrong code being generated.
  950. result = InitRequired
  951. else: result = allPathsAsgnResult(p, n[0])
  952. of nkIfStmt, nkIfExpr:
  953. var exhaustive = false
  954. result = InitSkippable
  955. for it in n:
  956. # Every condition must not use 'result':
  957. if it.len == 2 and containsResult(it[0]):
  958. return InitRequired
  959. if it.len == 1: exhaustive = true
  960. allPathsInBranch(it.lastSon)
  961. # if the 'if' statement is not exhaustive and yet it touched 'result'
  962. # in some way, say Unknown.
  963. if not exhaustive: result = Unknown
  964. of nkCaseStmt:
  965. if containsResult(n[0]): return InitRequired
  966. result = InitSkippable
  967. var exhaustive = skipTypes(n[0].typ,
  968. abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString, tyCstring}
  969. for i in 1..<n.len:
  970. let it = n[i]
  971. allPathsInBranch(it.lastSon)
  972. if it.kind == nkElse: exhaustive = true
  973. if not exhaustive: result = Unknown
  974. of nkWhileStmt:
  975. # some dubious code can assign the result in the 'while'
  976. # condition and that would be fine. Everything else isn't:
  977. result = allPathsAsgnResult(p, n[0])
  978. if result == Unknown:
  979. result = allPathsAsgnResult(p, n[1])
  980. # we cannot assume that the 'while' loop is really executed at least once:
  981. if result == InitSkippable: result = Unknown
  982. of harmless:
  983. result = Unknown
  984. of nkGotoState, nkBreakState:
  985. # give up for now.
  986. result = InitRequired
  987. of nkSym:
  988. # some path reads from 'result' before it was written to!
  989. if n.sym.kind == skResult: result = InitRequired
  990. of nkTryStmt, nkHiddenTryStmt:
  991. # We need to watch out for the following problem:
  992. # try:
  993. # result = stuffThatRaises()
  994. # except:
  995. # discard "result was not set"
  996. #
  997. # So ... even if the assignment to 'result' is the very first
  998. # assignment this is not good enough! The only pattern we allow for
  999. # is 'finally: result = x'
  1000. result = InitSkippable
  1001. allPathsInBranch(n[0])
  1002. for i in 1..<n.len:
  1003. if n[i].kind == nkFinally:
  1004. result = allPathsAsgnResult(p, n[i].lastSon)
  1005. else:
  1006. allPathsInBranch(n[i].lastSon)
  1007. of nkCallKinds:
  1008. if canRaiseDisp(p, n[0]):
  1009. result = InitRequired
  1010. else:
  1011. for i in 0..<n.safeLen:
  1012. allPathsInBranch(n[i])
  1013. of nkRaiseStmt:
  1014. result = InitRequired
  1015. of nkChckRangeF, nkChckRange64, nkChckRange:
  1016. # TODO: more checks might need to be covered like overflow, indexDefect etc.
  1017. # bug #22852
  1018. result = InitRequired
  1019. else:
  1020. for i in 0..<n.safeLen:
  1021. allPathsInBranch(n[i])
  1022. proc getProcTypeCast(m: BModule, prc: PSym): Rope =
  1023. result = getTypeDesc(m, prc.loc.t)
  1024. if prc.typ.callConv == ccClosure:
  1025. var rettype, params: Rope = ""
  1026. var check = initIntSet()
  1027. genProcParams(m, prc.typ, rettype, params, check)
  1028. result = "$1(*)$2" % [rettype, params]
  1029. proc genProcBody(p: BProc; procBody: PNode) =
  1030. genStmts(p, procBody) # modifies p.locals, p.init, etc.
  1031. if {nimErrorFlagAccessed, nimErrorFlagDeclared, nimErrorFlagDisabled} * p.flags == {nimErrorFlagAccessed}:
  1032. p.flags.incl nimErrorFlagDeclared
  1033. p.blocks[0].sections[cpsLocals].add(ropecg(p.module, "NIM_BOOL* nimErr_;$n", []))
  1034. p.blocks[0].sections[cpsInit].add(ropecg(p.module, "nimErr_ = #nimErrorFlag();$n", []))
  1035. proc isNoReturn(m: BModule; s: PSym): bool {.inline.} =
  1036. sfNoReturn in s.flags and m.config.exc != excGoto
  1037. proc genProcAux*(m: BModule, prc: PSym) =
  1038. var p = newProc(prc, m)
  1039. var header = newRopeAppender()
  1040. let isCppMember = m.config.backend == backendCpp and sfCppMember * prc.flags != {}
  1041. if isCppMember:
  1042. genMemberProcHeader(m, prc, header)
  1043. else:
  1044. genProcHeader(m, prc, header)
  1045. var returnStmt: Rope = ""
  1046. assert(prc.ast != nil)
  1047. var procBody = transformBody(m.g.graph, m.idgen, prc, {})
  1048. if sfInjectDestructors in prc.flags:
  1049. procBody = injectDestructorCalls(m.g.graph, m.idgen, prc, procBody)
  1050. let tmpInfo = prc.info
  1051. discard freshLineInfo(p, prc.info)
  1052. if sfPure notin prc.flags and prc.typ.returnType != nil:
  1053. if resultPos >= prc.ast.len:
  1054. internalError(m.config, prc.info, "proc has no result symbol")
  1055. let resNode = prc.ast[resultPos]
  1056. let res = resNode.sym # get result symbol
  1057. if not isInvalidReturnType(m.config, prc.typ) and sfConstructor notin prc.flags:
  1058. if sfNoInit in prc.flags: incl(res.flags, sfNoInit)
  1059. if sfNoInit in prc.flags and p.module.compileToCpp and (let val = easyResultAsgn(procBody); val != nil):
  1060. var decl = localVarDecl(p, resNode)
  1061. var a: TLoc = initLocExprSingleUse(p, val)
  1062. linefmt(p, cpsStmts, "$1 = $2;$n", [decl, rdLoc(a)])
  1063. else:
  1064. # declare the result symbol:
  1065. assignLocalVar(p, resNode)
  1066. assert(res.loc.r != "")
  1067. if p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc} and
  1068. allPathsAsgnResult(p, procBody) == InitSkippable:
  1069. # In an ideal world the codegen could rely on injectdestructors doing its job properly
  1070. # and then the analysis step would not be required.
  1071. discard "result init optimized out"
  1072. else:
  1073. initLocalVar(p, res, immediateAsgn=false)
  1074. returnStmt = ropecg(p.module, "\treturn $1;$n", [rdLoc(res.loc)])
  1075. elif sfConstructor in prc.flags:
  1076. resNode.sym.loc.flags.incl lfIndirect
  1077. fillLoc(resNode.sym.loc, locParam, resNode, "this", OnHeap)
  1078. prc.loc.r = getTypeDesc(m, resNode.sym.loc.t, dkVar)
  1079. else:
  1080. fillResult(p.config, resNode, prc.typ)
  1081. assignParam(p, res, prc.typ.returnType)
  1082. # We simplify 'unsureAsgn(result, nil); unsureAsgn(result, x)'
  1083. # to 'unsureAsgn(result, x)'
  1084. # Sketch why this is correct: If 'result' points to a stack location
  1085. # the 'unsureAsgn' is a nop. If it points to a global variable the
  1086. # global is either 'nil' or points to valid memory and so the RC operation
  1087. # succeeds without touching not-initialized memory.
  1088. if sfNoInit in prc.flags: discard
  1089. elif allPathsAsgnResult(p, procBody) == InitSkippable: discard
  1090. else:
  1091. resetLoc(p, res.loc)
  1092. if skipTypes(res.typ, abstractInst).kind == tyArray:
  1093. #incl(res.loc.flags, lfIndirect)
  1094. res.loc.storage = OnUnknown
  1095. for i in 1..<prc.typ.n.len:
  1096. let param = prc.typ.n[i].sym
  1097. if param.typ.isCompileTimeOnly: continue
  1098. assignParam(p, param, prc.typ.returnType)
  1099. closureSetup(p, prc)
  1100. genProcBody(p, procBody)
  1101. prc.info = tmpInfo
  1102. var generatedProc: Rope = ""
  1103. generatedProc.genCLineDir prc.info, m.config
  1104. if isNoReturn(p.module, prc):
  1105. if hasDeclspec in extccomp.CC[p.config.cCompiler].props and not isCppMember:
  1106. header = "__declspec(noreturn) " & header
  1107. if sfPure in prc.flags:
  1108. if hasDeclspec in extccomp.CC[p.config.cCompiler].props and not isCppMember:
  1109. header = "__declspec(naked) " & header
  1110. generatedProc.add ropecg(p.module, "$1 {$n$2$3$4}$N$N",
  1111. [header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)])
  1112. else:
  1113. if m.hcrOn and isReloadable(m, prc):
  1114. # Add forward declaration for "_actual"-suffixed functions defined in the same module (or inline).
  1115. # This fixes the use of methods and also the case when 2 functions within the same module
  1116. # call each other using directly the "_actual" versions (an optimization) - see issue #11608
  1117. m.s[cfsProcHeaders].addf("$1;\n", [header])
  1118. generatedProc.add ropecg(p.module, "$1 {$n", [header])
  1119. if optStackTrace in prc.options:
  1120. generatedProc.add(p.s(cpsLocals))
  1121. var procname = makeCString(prc.name.s)
  1122. generatedProc.add(initFrame(p, procname, quotedFilename(p.config, prc.info)))
  1123. else:
  1124. generatedProc.add(p.s(cpsLocals))
  1125. if optProfiler in prc.options:
  1126. # invoke at proc entry for recursion:
  1127. appcg(p, cpsInit, "\t#nimProfile();$n", [])
  1128. # this pair of {} is required for C++ (C++ is weird with its
  1129. # control flow integrity checks):
  1130. if beforeRetNeeded in p.flags: generatedProc.add("{")
  1131. generatedProc.add(p.s(cpsInit))
  1132. generatedProc.add(p.s(cpsStmts))
  1133. if beforeRetNeeded in p.flags: generatedProc.add("\t}BeforeRet_: ;\n")
  1134. if optStackTrace in prc.options: generatedProc.add(deinitFrame(p))
  1135. generatedProc.add(returnStmt)
  1136. generatedProc.add("}\n")
  1137. m.s[cfsProcs].add(generatedProc)
  1138. if isReloadable(m, prc):
  1139. m.s[cfsDynLibInit].addf("\t$1 = ($3) hcrRegisterProc($4, \"$1\", (void*)$2);$n",
  1140. [prc.loc.r, prc.loc.r & "_actual", getProcTypeCast(m, prc), getModuleDllPath(m, prc)])
  1141. proc requiresExternC(m: BModule; sym: PSym): bool {.inline.} =
  1142. result = (sfCompileToCpp in m.module.flags and
  1143. sfCompileToCpp notin sym.getModule().flags and
  1144. m.config.backend != backendCpp) or (
  1145. sym.flags * {sfInfixCall, sfCompilerProc, sfMangleCpp} == {} and
  1146. sym.flags * {sfImportc, sfExportc} != {} and
  1147. sym.magic == mNone and
  1148. m.config.backend == backendCpp)
  1149. proc genProcPrototype(m: BModule, sym: PSym) =
  1150. useHeader(m, sym)
  1151. if lfNoDecl in sym.loc.flags or sfCppMember * sym.flags != {}: return
  1152. if lfDynamicLib in sym.loc.flags:
  1153. if sym.itemId.module != m.module.position and
  1154. not containsOrIncl(m.declaredThings, sym.id):
  1155. m.s[cfsVars].add(ropecg(m, "$1 $2 $3;$n",
  1156. [(if isReloadable(m, sym): "static" else: "extern"),
  1157. getTypeDesc(m, sym.loc.t), mangleDynLibProc(sym)]))
  1158. if isReloadable(m, sym):
  1159. m.s[cfsDynLibInit].addf("\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  1160. [mangleDynLibProc(sym), getTypeDesc(m, sym.loc.t), getModuleDllPath(m, sym)])
  1161. elif not containsOrIncl(m.declaredProtos, sym.id):
  1162. let asPtr = isReloadable(m, sym)
  1163. var header = newRopeAppender()
  1164. genProcHeader(m, sym, header, asPtr)
  1165. if not asPtr:
  1166. if isNoReturn(m, sym) and hasDeclspec in extccomp.CC[m.config.cCompiler].props:
  1167. header = "__declspec(noreturn) " & header
  1168. if sym.typ.callConv != ccInline and requiresExternC(m, sym):
  1169. header = "extern \"C\" " & header
  1170. if sfPure in sym.flags and hasAttribute in CC[m.config.cCompiler].props:
  1171. header.add(" __attribute__((naked))")
  1172. if isNoReturn(m, sym) and hasAttribute in CC[m.config.cCompiler].props:
  1173. header.add(" __attribute__((noreturn))")
  1174. m.s[cfsProcHeaders].add(ropecg(m, "$1;$N", [header]))
  1175. # TODO: figure out how to rename this - it DOES generate a forward declaration
  1176. proc genProcNoForward(m: BModule, prc: PSym) =
  1177. if lfImportCompilerProc in prc.loc.flags:
  1178. fillProcLoc(m, prc.ast[namePos])
  1179. useHeader(m, prc)
  1180. # dependency to a compilerproc:
  1181. cgsym(m, prc.name.s)
  1182. return
  1183. if lfNoDecl in prc.loc.flags:
  1184. fillProcLoc(m, prc.ast[namePos])
  1185. genProcPrototype(m, prc)
  1186. elif lfDynamicLib in prc.loc.flags:
  1187. var q = findPendingModule(m, prc)
  1188. fillProcLoc(q, prc.ast[namePos])
  1189. genProcPrototype(m, prc)
  1190. if q != nil and not containsOrIncl(q.declaredThings, prc.id):
  1191. symInDynamicLib(q, prc)
  1192. # register the procedure even though it is in a different dynamic library and will not be
  1193. # reloadable (and has no _actual suffix) - other modules will need to be able to get it through
  1194. # the hcr dynlib (also put it in the DynLibInit section - right after it gets loaded)
  1195. if isReloadable(q, prc):
  1196. q.s[cfsDynLibInit].addf("\t$1 = ($2) hcrRegisterProc($3, \"$1\", (void*)$1);$n",
  1197. [prc.loc.r, getTypeDesc(q, prc.loc.t), getModuleDllPath(m, q.module)])
  1198. else:
  1199. symInDynamicLibPartial(m, prc)
  1200. elif prc.typ.callConv == ccInline:
  1201. # We add inline procs to the calling module to enable C based inlining.
  1202. # This also means that a check with ``q.declaredThings`` is wrong, we need
  1203. # a check for ``m.declaredThings``.
  1204. if not containsOrIncl(m.declaredThings, prc.id):
  1205. #if prc.loc.k == locNone:
  1206. # mangle the inline proc based on the module where it is defined -
  1207. # not on the first module that uses it
  1208. let m2 = if m.config.symbolFiles != disabledSf: m
  1209. else: findPendingModule(m, prc)
  1210. fillProcLoc(m2, prc.ast[namePos])
  1211. #elif {sfExportc, sfImportc} * prc.flags == {}:
  1212. # # reset name to restore consistency in case of hashing collisions:
  1213. # echo "resetting ", prc.id, " by ", m.module.name.s
  1214. # prc.loc.r = nil
  1215. # prc.loc.r = mangleName(m, prc)
  1216. genProcPrototype(m, prc)
  1217. genProcAux(m, prc)
  1218. elif sfImportc notin prc.flags:
  1219. var q = findPendingModule(m, prc)
  1220. fillProcLoc(q, prc.ast[namePos])
  1221. # generate a getProc call to initialize the pointer for this
  1222. # externally-to-the-current-module defined proc, also important
  1223. # to do the declaredProtos check before the call to genProcPrototype
  1224. if isReloadable(m, prc) and prc.id notin m.declaredProtos and
  1225. q != nil and q.module.id != m.module.id:
  1226. m.s[cfsDynLibInit].addf("\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  1227. [prc.loc.r, getProcTypeCast(m, prc), getModuleDllPath(m, prc)])
  1228. genProcPrototype(m, prc)
  1229. if q != nil and not containsOrIncl(q.declaredThings, prc.id):
  1230. # make sure there is a "prototype" in the external module
  1231. # which will actually become a function pointer
  1232. if isReloadable(m, prc):
  1233. genProcPrototype(q, prc)
  1234. genProcAux(q, prc)
  1235. else:
  1236. fillProcLoc(m, prc.ast[namePos])
  1237. useHeader(m, prc)
  1238. if sfInfixCall notin prc.flags: genProcPrototype(m, prc)
  1239. proc requestConstImpl(p: BProc, sym: PSym) =
  1240. if genConstSetup(p, sym):
  1241. let m = p.module
  1242. # declare implementation:
  1243. var q = findPendingModule(m, sym)
  1244. if q != nil and not containsOrIncl(q.declaredThings, sym.id):
  1245. assert q.initProc.module == q
  1246. genConstDefinition(q, p, sym)
  1247. # declare header:
  1248. if q != m and not containsOrIncl(m.declaredThings, sym.id):
  1249. genConstHeader(m, q, p, sym)
  1250. proc isActivated(prc: PSym): bool = prc.typ != nil
  1251. proc genProc(m: BModule, prc: PSym) =
  1252. if sfBorrow in prc.flags or not isActivated(prc): return
  1253. if sfForward in prc.flags:
  1254. addForwardedProc(m, prc)
  1255. fillProcLoc(m, prc.ast[namePos])
  1256. else:
  1257. genProcNoForward(m, prc)
  1258. if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and
  1259. m.g.generatedHeader != nil and lfNoDecl notin prc.loc.flags:
  1260. genProcPrototype(m.g.generatedHeader, prc)
  1261. if prc.typ.callConv == ccInline:
  1262. if not containsOrIncl(m.g.generatedHeader.declaredThings, prc.id):
  1263. genProcAux(m.g.generatedHeader, prc)
  1264. proc genVarPrototype(m: BModule, n: PNode) =
  1265. #assert(sfGlobal in sym.flags)
  1266. let sym = n.sym
  1267. useHeader(m, sym)
  1268. fillBackendName(m, sym)
  1269. fillLoc(sym.loc, locGlobalVar, n, OnHeap)
  1270. if treatGlobalDifferentlyForHCR(m, sym): incl(sym.loc.flags, lfIndirect)
  1271. if (lfNoDecl in sym.loc.flags) or contains(m.declaredThings, sym.id):
  1272. return
  1273. if sym.owner.id != m.module.id:
  1274. # else we already have the symbol generated!
  1275. assert(sym.loc.r != "")
  1276. incl(m.declaredThings, sym.id)
  1277. if sfThread in sym.flags:
  1278. declareThreadVar(m, sym, true)
  1279. else:
  1280. if sym.kind in {skLet, skVar, skField, skForVar} and sym.alignment > 0:
  1281. m.s[cfsVars].addf "NIM_ALIGN($1) ", [rope(sym.alignment)]
  1282. m.s[cfsVars].add(if m.hcrOn: "static " else: "extern ")
  1283. m.s[cfsVars].add(getTypeDesc(m, sym.loc.t, dkVar))
  1284. if m.hcrOn: m.s[cfsVars].add("*")
  1285. if lfDynamicLib in sym.loc.flags: m.s[cfsVars].add("*")
  1286. if sfRegister in sym.flags: m.s[cfsVars].add(" register")
  1287. if sfVolatile in sym.flags: m.s[cfsVars].add(" volatile")
  1288. if sfNoalias in sym.flags: m.s[cfsVars].add(" NIM_NOALIAS")
  1289. m.s[cfsVars].addf(" $1;$n", [sym.loc.r])
  1290. if m.hcrOn: m.initProc.procSec(cpsLocals).addf(
  1291. "\t$1 = ($2*)hcrGetGlobal($3, \"$1\");$n", [sym.loc.r,
  1292. getTypeDesc(m, sym.loc.t, dkVar), getModuleDllPath(m, sym)])
  1293. proc addNimDefines(result: var Rope; conf: ConfigRef) {.inline.} =
  1294. result.addf("#define NIM_INTBITS $1\L", [
  1295. platform.CPU[conf.target.targetCPU].intSize.rope])
  1296. if conf.cppCustomNamespace.len > 0:
  1297. result.add("#define USE_NIM_NAMESPACE ")
  1298. result.add(conf.cppCustomNamespace)
  1299. result.add("\L")
  1300. if conf.isDefined("nimEmulateOverflowChecks"):
  1301. result.add("#define NIM_EmulateOverflowChecks\L")
  1302. proc headerTop(): Rope =
  1303. result = "/* Generated by Nim Compiler v$1 */$N" % [rope(VersionAsString)]
  1304. proc getCopyright(conf: ConfigRef; cfile: Cfile): Rope =
  1305. result = headerTop()
  1306. if optCompileOnly notin conf.globalOptions:
  1307. result.add ("/* Compiled for: $1, $2, $3 */$N" &
  1308. "/* Command for C compiler:$n $4 */$N") %
  1309. [rope(platform.OS[conf.target.targetOS].name),
  1310. rope(platform.CPU[conf.target.targetCPU].name),
  1311. rope(extccomp.CC[conf.cCompiler].name),
  1312. rope(getCompileCFileCmd(conf, cfile))]
  1313. proc getFileHeader(conf: ConfigRef; cfile: Cfile): Rope =
  1314. result = getCopyright(conf, cfile)
  1315. if conf.hcrOn: result.add("#define NIM_HOT_CODE_RELOADING\L")
  1316. addNimDefines(result, conf)
  1317. proc getSomeNameForModule(conf: ConfigRef, filename: AbsoluteFile): Rope =
  1318. ## Returns a mangled module name.
  1319. result = ""
  1320. result.add mangleModuleName(conf, filename).mangle
  1321. proc getSomeNameForModule(m: BModule): Rope =
  1322. ## Returns a mangled module name.
  1323. assert m.module.kind == skModule
  1324. assert m.module.owner.kind == skPackage
  1325. result = ""
  1326. result.add mangleModuleName(m.g.config, m.filename).mangle
  1327. proc getSomeInitName(m: BModule, suffix: string): Rope =
  1328. if not m.hcrOn:
  1329. result = getSomeNameForModule(m)
  1330. else:
  1331. result = ""
  1332. result.add suffix
  1333. proc getInitName(m: BModule): Rope =
  1334. if sfMainModule in m.module.flags:
  1335. # generate constant name for main module, for "easy" debugging.
  1336. result = rope(m.config.nimMainPrefix) & rope"NimMainModule"
  1337. else:
  1338. result = getSomeInitName(m, "Init000")
  1339. proc getDatInitName(m: BModule): Rope = getSomeInitName(m, "DatInit000")
  1340. proc getHcrInitName(m: BModule): Rope = getSomeInitName(m, "HcrInit000")
  1341. proc hcrGetProcLoadCode(m: BModule, sym, prefix, handle, getProcFunc: string): Rope
  1342. proc genMainProc(m: BModule) =
  1343. ## this function is called in cgenWriteModules after all modules are closed,
  1344. ## it means raising dependency on the symbols is too late as it will not propagate
  1345. ## into other modules, only simple rope manipulations are allowed
  1346. var preMainCode: Rope = ""
  1347. if m.hcrOn:
  1348. proc loadLib(handle: string, name: string): Rope =
  1349. result = ""
  1350. let prc = magicsys.getCompilerProc(m.g.graph, name)
  1351. assert prc != nil
  1352. let n = newStrNode(nkStrLit, prc.annex.path.strVal)
  1353. n.info = prc.annex.path.info
  1354. var strLit = newRopeAppender()
  1355. genStringLiteral(m, n, strLit)
  1356. appcg(m, result, "\tif (!($1 = #nimLoadLibrary($2)))$N" &
  1357. "\t\t#nimLoadLibraryError($2);$N",
  1358. [handle, strLit])
  1359. preMainCode.add(loadLib("hcr_handle", "hcrGetProc"))
  1360. if m.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  1361. preMainCode.add("\t$1PreMain();\L" % [rope m.config.nimMainPrefix])
  1362. else:
  1363. preMainCode.add("\tvoid* rtl_handle;\L")
  1364. preMainCode.add(loadLib("rtl_handle", "nimGC_setStackBottom"))
  1365. preMainCode.add(hcrGetProcLoadCode(m, "nimGC_setStackBottom", "nimrtl_", "rtl_handle", "nimGetProcAddr"))
  1366. preMainCode.add("\tinner = $1PreMain;\L" % [rope m.config.nimMainPrefix])
  1367. preMainCode.add("\tinitStackBottomWith_actual((void *)&inner);\L")
  1368. preMainCode.add("\t(*inner)();\L")
  1369. else:
  1370. preMainCode.add("\t$1PreMain();\L" % [rope m.config.nimMainPrefix])
  1371. var posixCmdLine: Rope = ""
  1372. if optNoMain notin m.config.globalOptions:
  1373. posixCmdLine.add "N_LIB_PRIVATE int cmdCount;\L"
  1374. posixCmdLine.add "N_LIB_PRIVATE char** cmdLine;\L"
  1375. posixCmdLine.add "N_LIB_PRIVATE char** gEnv;\L"
  1376. const
  1377. # The use of a volatile function pointer to call Pre/NimMainInner
  1378. # prevents inlining of the NimMainInner function and dependent
  1379. # functions, which might otherwise merge their stack frames.
  1380. PreMainBody = "$N" &
  1381. "N_LIB_PRIVATE void $3PreMainInner(void) {$N" &
  1382. "$2" &
  1383. "}$N$N" &
  1384. "$4" &
  1385. "N_LIB_PRIVATE void $3PreMain(void) {$N" &
  1386. "##if $5$N" & # 1 for volatile call, 0 for non-volatile
  1387. "\tvoid (*volatile inner)(void);$N" &
  1388. "\tinner = $3PreMainInner;$N" &
  1389. "$1" &
  1390. "\t(*inner)();$N" &
  1391. "##else$N" &
  1392. "$1" &
  1393. "\t$3PreMainInner();$N" &
  1394. "##endif$N" &
  1395. "}$N$N"
  1396. MainProcs =
  1397. "\t$^NimMain();$N"
  1398. MainProcsWithResult =
  1399. MainProcs & ("\treturn $1nim_program_result;$N")
  1400. NimMainInner = "N_LIB_PRIVATE N_CDECL(void, $5NimMainInner)(void) {$N" &
  1401. "$1" &
  1402. "}$N$N"
  1403. NimMainProc =
  1404. "N_CDECL(void, $5NimMain)(void) {$N" &
  1405. "##if $6$N" & # 1 for volatile call, 0 for non-volatile
  1406. "\tvoid (*volatile inner)(void);$N" &
  1407. "$4" &
  1408. "\tinner = $5NimMainInner;$N" &
  1409. "$2" &
  1410. "\t(*inner)();$N" &
  1411. "##else$N" &
  1412. "$4" &
  1413. "$2" &
  1414. "\t$5NimMainInner();$N" &
  1415. "##endif$N" &
  1416. "}$N$N"
  1417. NimMainBody = NimMainInner & NimMainProc
  1418. PosixCMain =
  1419. "int main(int argc, char** args, char** env) {$N" &
  1420. "\tcmdLine = args;$N" &
  1421. "\tcmdCount = argc;$N" &
  1422. "\tgEnv = env;$N" &
  1423. MainProcsWithResult &
  1424. "}$N$N"
  1425. StandaloneCMain =
  1426. "int main(void) {$N" &
  1427. MainProcs &
  1428. "\treturn 0;$N" &
  1429. "}$N$N"
  1430. WinNimMain = NimMainBody
  1431. WinCMain = "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N" &
  1432. " HINSTANCE hPrevInstance, $N" &
  1433. " LPSTR lpCmdLine, int nCmdShow) {$N" &
  1434. MainProcsWithResult & "}$N$N"
  1435. WinNimDllMain = NimMainInner & "N_LIB_EXPORT " & NimMainProc
  1436. WinCDllMain =
  1437. "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N" &
  1438. " LPVOID lpvReserved) {$N" &
  1439. "\tif (fwdreason == DLL_PROCESS_ATTACH) {$N" & MainProcs & "\t}$N" &
  1440. "\treturn 1;$N}$N$N"
  1441. PosixNimDllMain = WinNimDllMain
  1442. PosixCDllMain =
  1443. "N_LIB_PRIVATE void NIM_POSIX_INIT NimMainInit(void) {$N" &
  1444. MainProcs &
  1445. "}$N$N"
  1446. GenodeNimMain =
  1447. "extern Genode::Env *nim_runtime_env;$N" &
  1448. "extern \"C\" void nim_component_construct(Genode::Env*);$N$N" &
  1449. NimMainBody
  1450. ComponentConstruct =
  1451. "void Libc::Component::construct(Libc::Env &env) {$N" &
  1452. "\t// Set Env used during runtime initialization$N" &
  1453. "\tnim_runtime_env = &env;$N" &
  1454. "\tLibc::with_libc([&] () {$N\t" &
  1455. "\t// Initialize runtime and globals$N" &
  1456. MainProcs &
  1457. "\t// Call application construct$N" &
  1458. "\t\tnim_component_construct(&env);$N" &
  1459. "\t});$N" &
  1460. "}$N$N"
  1461. if m.config.target.targetOS == osWindows and
  1462. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1463. m.includeHeader("<windows.h>")
  1464. elif m.config.target.targetOS == osGenode:
  1465. m.includeHeader("<libc/component.h>")
  1466. let initStackBottomCall =
  1467. if m.config.target.targetOS == osStandalone or m.config.selectedGC in {gcNone, gcArc, gcAtomicArc, gcOrc}: "".rope
  1468. else: ropecg(m, "\t#initStackBottomWith((void *)&inner);$N", [])
  1469. inc(m.labels)
  1470. let isVolatile = if m.config.selectedGC notin {gcNone, gcArc, gcAtomicArc, gcOrc}: "1" else: "0"
  1471. appcg(m, m.s[cfsProcs], PreMainBody, [m.g.mainDatInit, m.g.otherModsInit, m.config.nimMainPrefix, posixCmdLine, isVolatile])
  1472. if m.config.target.targetOS == osWindows and
  1473. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1474. if optGenGuiApp in m.config.globalOptions:
  1475. const nimMain = WinNimMain
  1476. appcg(m, m.s[cfsProcs], nimMain,
  1477. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1478. else:
  1479. const nimMain = WinNimDllMain
  1480. appcg(m, m.s[cfsProcs], nimMain,
  1481. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1482. elif m.config.target.targetOS == osGenode:
  1483. const nimMain = GenodeNimMain
  1484. appcg(m, m.s[cfsProcs], nimMain,
  1485. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1486. elif optGenDynLib in m.config.globalOptions:
  1487. const nimMain = PosixNimDllMain
  1488. appcg(m, m.s[cfsProcs], nimMain,
  1489. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1490. else:
  1491. const nimMain = NimMainBody
  1492. appcg(m, m.s[cfsProcs], nimMain,
  1493. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1494. if optNoMain notin m.config.globalOptions:
  1495. if m.config.cppCustomNamespace.len > 0:
  1496. closeNamespaceNim(m.s[cfsProcs])
  1497. m.s[cfsProcs].add "using namespace " & m.config.cppCustomNamespace & ";\L"
  1498. if m.config.target.targetOS == osWindows and
  1499. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1500. if optGenGuiApp in m.config.globalOptions:
  1501. const otherMain = WinCMain
  1502. appcg(m, m.s[cfsProcs], otherMain, [if m.hcrOn: "*" else: "", m.config.nimMainPrefix])
  1503. else:
  1504. const otherMain = WinCDllMain
  1505. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1506. elif m.config.target.targetOS == osGenode:
  1507. const otherMain = ComponentConstruct
  1508. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1509. elif optGenDynLib in m.config.globalOptions:
  1510. const otherMain = PosixCDllMain
  1511. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1512. elif m.config.target.targetOS == osStandalone:
  1513. const otherMain = StandaloneCMain
  1514. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1515. else:
  1516. const otherMain = PosixCMain
  1517. appcg(m, m.s[cfsProcs], otherMain, [if m.hcrOn: "*" else: "", m.config.nimMainPrefix])
  1518. if m.config.cppCustomNamespace.len > 0:
  1519. openNamespaceNim(m.config.cppCustomNamespace, m.s[cfsProcs])
  1520. proc registerInitProcs*(g: BModuleList; m: PSym; flags: set[ModuleBackendFlag]) =
  1521. ## Called from the IC backend.
  1522. if HasDatInitProc in flags:
  1523. let datInit = getSomeNameForModule(g.config, g.config.toFullPath(m.info.fileIndex).AbsoluteFile) & "DatInit000"
  1524. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [datInit])
  1525. g.mainDatInit.addf("\t$1();$N", [datInit])
  1526. if HasModuleInitProc in flags:
  1527. let init = getSomeNameForModule(g.config, g.config.toFullPath(m.info.fileIndex).AbsoluteFile) & "Init000"
  1528. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [init])
  1529. let initCall = "\t$1();$N" % [init]
  1530. if sfMainModule in m.flags:
  1531. g.mainModInit.add(initCall)
  1532. elif sfSystemModule in m.flags:
  1533. g.mainDatInit.add(initCall) # systemInit must called right after systemDatInit if any
  1534. else:
  1535. g.otherModsInit.add(initCall)
  1536. proc whichInitProcs*(m: BModule): set[ModuleBackendFlag] =
  1537. # called from IC.
  1538. result = {}
  1539. if m.hcrOn or m.preInitProc.s(cpsInit).len > 0 or m.preInitProc.s(cpsStmts).len > 0:
  1540. result.incl HasModuleInitProc
  1541. for i in cfsTypeInit1..cfsDynLibInit:
  1542. if m.s[i].len != 0:
  1543. result.incl HasDatInitProc
  1544. break
  1545. proc registerModuleToMain(g: BModuleList; m: BModule) =
  1546. let
  1547. init = m.getInitName
  1548. datInit = m.getDatInitName
  1549. if m.hcrOn:
  1550. var hcrModuleMeta = "$nN_LIB_PRIVATE const char* hcr_module_list[] = {$n" % []
  1551. let systemModulePath = getModuleDllPath(m, g.modules[g.graph.config.m.systemFileIdx.int].module)
  1552. let mainModulePath = getModuleDllPath(m, m.module)
  1553. if sfMainModule in m.module.flags:
  1554. hcrModuleMeta.addf("\t$1,$n", [systemModulePath])
  1555. g.graph.importDeps.withValue(FileIndex(m.module.position), deps):
  1556. for curr in deps[]:
  1557. hcrModuleMeta.addf("\t$1,$n", [getModuleDllPath(m, g.modules[curr.int].module)])
  1558. hcrModuleMeta.addf("\t\"\"};$n", [])
  1559. hcrModuleMeta.addf("$nN_LIB_EXPORT N_NIMCALL(void**, HcrGetImportedModules)() { return (void**)hcr_module_list; }$n", [])
  1560. hcrModuleMeta.addf("$nN_LIB_EXPORT N_NIMCALL(char*, HcrGetSigHash)() { return \"$1\"; }$n$n",
  1561. [($sigHash(m.module, m.config)).rope])
  1562. if sfMainModule in m.module.flags:
  1563. g.mainModProcs.add(hcrModuleMeta)
  1564. g.mainModProcs.addf("static void* hcr_handle;$N", [])
  1565. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [init])
  1566. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [datInit])
  1567. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void*, N_NIMCALL_PTR(void*, getProcAddr)(void*, char*));$N", [m.getHcrInitName])
  1568. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void);$N", [])
  1569. g.mainModInit.addf("\t$1();$N", [init])
  1570. g.otherModsInit.addf("\thcrInit((void**)hcr_module_list, $1, $2, $3, hcr_handle, nimGetProcAddr);$n",
  1571. [mainModulePath, systemModulePath, datInit])
  1572. g.mainDatInit.addf("\t$1(hcr_handle, nimGetProcAddr);$N", [m.getHcrInitName])
  1573. g.mainDatInit.addf("\thcrAddModule($1);\n", [mainModulePath])
  1574. g.mainDatInit.addf("\tHcrCreateTypeInfos();$N", [])
  1575. # nasty nasty hack to get the command line functionality working with HCR
  1576. # register the 2 variables on behalf of the os module which might not even
  1577. # be loaded (in which case it will get collected but that is not a problem)
  1578. # EDIT: indeed, this hack, in combination with another un-necessary one
  1579. # (`makeCString` was doing line wrap of string litterals) was root cause for
  1580. # bug #16265.
  1581. let osModulePath = ($systemModulePath).replace("stdlib_system", "stdlib_os").rope
  1582. g.mainDatInit.addf("\thcrAddModule($1);\n", [osModulePath])
  1583. g.mainDatInit.add("\tint* cmd_count;\n")
  1584. g.mainDatInit.add("\tchar*** cmd_line;\n")
  1585. g.mainDatInit.addf("\thcrRegisterGlobal($1, \"cmdCount\", sizeof(cmd_count), NULL, (void**)&cmd_count);$N", [osModulePath])
  1586. g.mainDatInit.addf("\thcrRegisterGlobal($1, \"cmdLine\", sizeof(cmd_line), NULL, (void**)&cmd_line);$N", [osModulePath])
  1587. g.mainDatInit.add("\t*cmd_count = cmdCount;\n")
  1588. g.mainDatInit.add("\t*cmd_line = cmdLine;\n")
  1589. else:
  1590. m.s[cfsInitProc].add(hcrModuleMeta)
  1591. return
  1592. if m.s[cfsDatInitProc].len > 0:
  1593. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [datInit])
  1594. g.mainDatInit.addf("\t$1();$N", [datInit])
  1595. # Initialization of TLS and GC should be done in between
  1596. # systemDatInit and systemInit calls if any
  1597. if sfSystemModule in m.module.flags:
  1598. if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone:
  1599. g.mainDatInit.add(ropecg(m, "\t#initThreadVarsEmulation();$N", []))
  1600. if m.config.target.targetOS != osStandalone and m.config.selectedGC notin {gcNone, gcArc, gcAtomicArc, gcOrc}:
  1601. g.mainDatInit.add(ropecg(m, "\t#initStackBottomWith((void *)&inner);$N", []))
  1602. if m.s[cfsInitProc].len > 0:
  1603. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [init])
  1604. let initCall = "\t$1();$N" % [init]
  1605. if sfMainModule in m.module.flags:
  1606. g.mainModInit.add(initCall)
  1607. elif sfSystemModule in m.module.flags:
  1608. g.mainDatInit.add(initCall) # systemInit must called right after systemDatInit if any
  1609. else:
  1610. g.otherModsInit.add(initCall)
  1611. proc genDatInitCode(m: BModule) =
  1612. ## this function is called in cgenWriteModules after all modules are closed,
  1613. ## it means raising dependency on the symbols is too late as it will not propagate
  1614. ## into other modules, only simple rope manipulations are allowed
  1615. var moduleDatInitRequired = m.hcrOn
  1616. var prc = "$1 N_NIMCALL(void, $2)(void) {$N" %
  1617. [rope(if m.hcrOn: "N_LIB_EXPORT" else: "N_LIB_PRIVATE"), getDatInitName(m)]
  1618. # we don't want to break into such init code - could happen if a line
  1619. # directive from a function written by the user spills after itself
  1620. genCLineDir(prc, InvalidFileIdx, 999999, m.config)
  1621. for i in cfsTypeInit1..cfsDynLibInit:
  1622. if m.s[i].len != 0:
  1623. moduleDatInitRequired = true
  1624. prc.add(m.s[i])
  1625. prc.addf("}$N$N", [])
  1626. if moduleDatInitRequired:
  1627. m.s[cfsDatInitProc].add(prc)
  1628. #rememberFlag(m.g.graph, m.module, HasDatInitProc)
  1629. # Very similar to the contents of symInDynamicLib - basically only the
  1630. # things needed for the hot code reloading runtime procs to be loaded
  1631. proc hcrGetProcLoadCode(m: BModule, sym, prefix, handle, getProcFunc: string): Rope =
  1632. let prc = magicsys.getCompilerProc(m.g.graph, sym)
  1633. assert prc != nil
  1634. fillProcLoc(m, prc.ast[namePos])
  1635. var extname = prefix & sym
  1636. var tmp = mangleDynLibProc(prc)
  1637. prc.loc.r = tmp
  1638. prc.typ.sym = nil
  1639. if not containsOrIncl(m.declaredThings, prc.id):
  1640. m.s[cfsVars].addf("static $2 $1;$n", [prc.loc.r, getTypeDesc(m, prc.loc.t, dkVar)])
  1641. result = "\t$1 = ($2) $3($4, $5);$n" %
  1642. [tmp, getTypeDesc(m, prc.typ, dkVar), getProcFunc.rope, handle.rope, makeCString(prefix & sym)]
  1643. proc genInitCode(m: BModule) =
  1644. ## this function is called in cgenWriteModules after all modules are closed,
  1645. ## it means raising dependency on the symbols is too late as it will not propagate
  1646. ## into other modules, only simple rope manipulations are allowed
  1647. var moduleInitRequired = m.hcrOn
  1648. let initname = getInitName(m)
  1649. var prc = "$1 N_NIMCALL(void, $2)(void) {$N" %
  1650. [rope(if m.hcrOn: "N_LIB_EXPORT" else: "N_LIB_PRIVATE"), initname]
  1651. # we don't want to break into such init code - could happen if a line
  1652. # directive from a function written by the user spills after itself
  1653. genCLineDir(prc, InvalidFileIdx, 999999, m.config)
  1654. if m.typeNodes > 0:
  1655. if m.hcrOn:
  1656. appcg(m, m.s[cfsTypeInit1], "\t#TNimNode* $1;$N", [m.typeNodesName])
  1657. appcg(m, m.s[cfsTypeInit1], "\thcrRegisterGlobal($3, \"$1_$2\", sizeof(TNimNode) * $2, NULL, (void**)&$1);$N",
  1658. [m.typeNodesName, m.typeNodes, getModuleDllPath(m, m.module)])
  1659. else:
  1660. appcg(m, m.s[cfsTypeInit1], "static #TNimNode $1[$2];$n",
  1661. [m.typeNodesName, m.typeNodes])
  1662. if m.nimTypes > 0:
  1663. appcg(m, m.s[cfsTypeInit1], "static #TNimType $1[$2];$n",
  1664. [m.nimTypesName, m.nimTypes])
  1665. if m.hcrOn:
  1666. prc.addf("\tint* nim_hcr_dummy_ = 0;$n" &
  1667. "\tNIM_BOOL nim_hcr_do_init_ = " &
  1668. "hcrRegisterGlobal($1, \"module_initialized_\", 1, NULL, (void**)&nim_hcr_dummy_);$n",
  1669. [getModuleDllPath(m, m.module)])
  1670. template writeSection(thing: untyped, section: TCProcSection, addHcrGuards = false) =
  1671. if m.thing.s(section).len > 0:
  1672. moduleInitRequired = true
  1673. if addHcrGuards: prc.add("\tif (nim_hcr_do_init_) {\n\n")
  1674. prc.add(m.thing.s(section))
  1675. if addHcrGuards: prc.add("\n\t} // nim_hcr_do_init_\n")
  1676. if m.preInitProc.s(cpsInit).len > 0 or m.preInitProc.s(cpsStmts).len > 0:
  1677. # Give this small function its own scope
  1678. prc.addf("{$N", [])
  1679. # Keep a bogus frame in case the code needs one
  1680. prc.add("\tTFrame FR_; FR_.len = 0;\n")
  1681. writeSection(preInitProc, cpsLocals)
  1682. writeSection(preInitProc, cpsInit, m.hcrOn)
  1683. writeSection(preInitProc, cpsStmts)
  1684. prc.addf("}/* preInitProc end */$N", [])
  1685. when false:
  1686. m.initProc.blocks[0].sections[cpsLocals].add m.preInitProc.s(cpsLocals)
  1687. m.initProc.blocks[0].sections[cpsInit].prepend m.preInitProc.s(cpsInit)
  1688. m.initProc.blocks[0].sections[cpsStmts].prepend m.preInitProc.s(cpsStmts)
  1689. # add new scope for following code, because old vcc compiler need variable
  1690. # be defined at the top of the block
  1691. prc.addf("{$N", [])
  1692. writeSection(initProc, cpsLocals)
  1693. if m.initProc.s(cpsInit).len > 0 or m.initProc.s(cpsStmts).len > 0:
  1694. moduleInitRequired = true
  1695. if optStackTrace in m.initProc.options and frameDeclared notin m.flags:
  1696. # BUT: the generated init code might depend on a current frame, so
  1697. # declare it nevertheless:
  1698. incl m.flags, frameDeclared
  1699. if preventStackTrace notin m.flags:
  1700. var procname = makeCString(m.module.name.s)
  1701. prc.add(initFrame(m.initProc, procname, quotedFilename(m.config, m.module.info)))
  1702. else:
  1703. prc.add("\tTFrame FR_; FR_.len = 0;\n")
  1704. writeSection(initProc, cpsInit, m.hcrOn)
  1705. writeSection(initProc, cpsStmts)
  1706. if beforeRetNeeded in m.initProc.flags:
  1707. prc.add("\tBeforeRet_: ;\n")
  1708. if m.config.exc == excGoto:
  1709. if getCompilerProc(m.g.graph, "nimTestErrorFlag") != nil:
  1710. m.appcg(prc, "\t#nimTestErrorFlag();$n", [])
  1711. if optStackTrace in m.initProc.options and preventStackTrace notin m.flags:
  1712. prc.add(deinitFrame(m.initProc))
  1713. elif m.config.exc == excGoto:
  1714. if getCompilerProc(m.g.graph, "nimTestErrorFlag") != nil:
  1715. m.appcg(prc, "\t#nimTestErrorFlag();$n", [])
  1716. prc.addf("}$N", [])
  1717. prc.addf("}$N$N", [])
  1718. # we cannot simply add the init proc to ``m.s[cfsProcs]`` anymore because
  1719. # that would lead to a *nesting* of merge sections which the merger does
  1720. # not support. So we add it to another special section: ``cfsInitProc``
  1721. if m.hcrOn:
  1722. var procsToLoad = @["hcrRegisterProc", "hcrGetProc", "hcrRegisterGlobal", "hcrGetGlobal"]
  1723. m.s[cfsInitProc].addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void* handle, N_NIMCALL_PTR(void*, getProcAddr)(void*, char*)) {$N", [getHcrInitName(m)])
  1724. if sfMainModule in m.module.flags:
  1725. # additional procs to load
  1726. procsToLoad.add("hcrInit")
  1727. procsToLoad.add("hcrAddModule")
  1728. # load procs
  1729. for curr in procsToLoad:
  1730. m.s[cfsInitProc].add(hcrGetProcLoadCode(m, curr, "", "handle", "getProcAddr"))
  1731. m.s[cfsInitProc].addf("}$N$N", [])
  1732. for i, el in pairs(m.extensionLoaders):
  1733. if el != "":
  1734. let ex = "NIM_EXTERNC N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N" %
  1735. [(i.ord - '0'.ord).rope, el]
  1736. moduleInitRequired = true
  1737. prc.add(ex)
  1738. if moduleInitRequired or sfMainModule in m.module.flags:
  1739. m.s[cfsInitProc].add(prc)
  1740. #rememberFlag(m.g.graph, m.module, HasModuleInitProc)
  1741. genDatInitCode(m)
  1742. if m.hcrOn:
  1743. m.s[cfsInitProc].addf("N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void) {$N", [])
  1744. m.s[cfsInitProc].add(m.hcrCreateTypeInfosProc)
  1745. m.s[cfsInitProc].addf("}$N$N", [])
  1746. registerModuleToMain(m.g, m)
  1747. proc postprocessCode(conf: ConfigRef, r: var Rope) =
  1748. # find the first directive
  1749. var f = r.find(postprocessDirStart)
  1750. if f == -1:
  1751. return
  1752. var
  1753. nimlnDirLastF = ""
  1754. var res: Rope = r.substr(0, f - 1)
  1755. while f != -1:
  1756. var
  1757. e = r.find(postprocessDirEnd, f + 1)
  1758. dir = r.substr(f + 1, e - 1).split(postprocessDirSep)
  1759. case dir[0]
  1760. of "nimln":
  1761. if dir[2] == nimlnDirLastF:
  1762. res.add("nimln_(" & dir[1] & ");")
  1763. else:
  1764. res.add("nimlf_(" & dir[1] & ", " & quotedFilename(conf, dir[2].parseInt.FileIndex) & ");")
  1765. nimlnDirLastF = dir[2]
  1766. else:
  1767. raiseAssert "unexpected postprocess directive"
  1768. # find the next directive
  1769. f = r.find(postprocessDirStart, e + 1)
  1770. # copy the code until the next directive
  1771. if f != -1:
  1772. res.add(r.substr(e + 1, f - 1))
  1773. else:
  1774. res.add(r.substr(e + 1))
  1775. r = res
  1776. proc genModule(m: BModule, cfile: Cfile): Rope =
  1777. var moduleIsEmpty = true
  1778. result = getFileHeader(m.config, cfile)
  1779. generateThreadLocalStorage(m)
  1780. generateHeaders(m)
  1781. result.add(m.s[cfsHeaders])
  1782. if m.config.cppCustomNamespace.len > 0:
  1783. openNamespaceNim(m.config.cppCustomNamespace, result)
  1784. if m.s[cfsFrameDefines].len > 0:
  1785. result.add(m.s[cfsFrameDefines])
  1786. for i in cfsForwardTypes..cfsProcs:
  1787. if m.s[i].len > 0:
  1788. moduleIsEmpty = false
  1789. result.add(m.s[i])
  1790. if m.s[cfsInitProc].len > 0:
  1791. moduleIsEmpty = false
  1792. result.add(m.s[cfsInitProc])
  1793. if m.s[cfsDatInitProc].len > 0 or m.hcrOn:
  1794. moduleIsEmpty = false
  1795. result.add(m.s[cfsDatInitProc])
  1796. if m.config.cppCustomNamespace.len > 0:
  1797. closeNamespaceNim(result)
  1798. if optLineDir in m.config.options:
  1799. var srcFileDefs = ""
  1800. for fi in 0..m.config.m.fileInfos.high:
  1801. srcFileDefs.add("#define FX_" & $fi & " " & makeSingleLineCString(toFullPath(m.config, fi.FileIndex)) & "\n")
  1802. result = srcFileDefs & result
  1803. if moduleIsEmpty:
  1804. result = ""
  1805. postprocessCode(m.config, result)
  1806. proc initProcOptions(m: BModule): TOptions =
  1807. let opts = m.config.options
  1808. if sfSystemModule in m.module.flags: opts-{optStackTrace} else: opts
  1809. proc rawNewModule(g: BModuleList; module: PSym, filename: AbsoluteFile): BModule =
  1810. new(result)
  1811. result.g = g
  1812. result.tmpBase = rope("TM" & $hashOwner(module) & "_")
  1813. result.headerFiles = @[]
  1814. result.declaredThings = initIntSet()
  1815. result.declaredProtos = initIntSet()
  1816. result.cfilename = filename
  1817. result.filename = filename
  1818. result.typeCache = initTable[SigHash, Rope]()
  1819. result.forwTypeCache = initTable[SigHash, Rope]()
  1820. result.module = module
  1821. result.typeInfoMarker = initTable[SigHash, Rope]()
  1822. result.sigConflicts = initCountTable[SigHash]()
  1823. result.initProc = newProc(nil, result)
  1824. for i in low(result.s)..high(result.s): result.s[i] = newRopeAppender()
  1825. result.initProc.options = initProcOptions(result)
  1826. result.preInitProc = newProc(nil, result)
  1827. result.preInitProc.flags.incl nimErrorFlagDisabled
  1828. result.preInitProc.labels = 100_000 # little hack so that unique temporaries are generated
  1829. result.dataCache = initNodeTable()
  1830. result.typeStack = @[]
  1831. result.typeNodesName = getTempName(result)
  1832. result.nimTypesName = getTempName(result)
  1833. # no line tracing for the init sections of the system module so that we
  1834. # don't generate a TFrame which can confuse the stack bottom initialization:
  1835. if sfSystemModule in module.flags:
  1836. incl result.flags, preventStackTrace
  1837. excl(result.preInitProc.options, optStackTrace)
  1838. let ndiName = if optCDebug in g.config.globalOptions: changeFileExt(completeCfilePath(g.config, filename), "ndi")
  1839. else: AbsoluteFile""
  1840. open(result.ndi, ndiName, g.config)
  1841. proc rawNewModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule =
  1842. result = rawNewModule(g, module, AbsoluteFile toFullPath(conf, module.position.FileIndex))
  1843. proc newModule*(g: BModuleList; module: PSym; conf: ConfigRef): BModule =
  1844. # we should create only one cgen module for each module sym
  1845. result = rawNewModule(g, module, conf)
  1846. if module.position >= g.modules.len:
  1847. setLen(g.modules, module.position + 1)
  1848. #growCache g.modules, module.position
  1849. g.modules[module.position] = result
  1850. template injectG() {.dirty.} =
  1851. if graph.backend == nil:
  1852. graph.backend = newModuleList(graph)
  1853. let g = BModuleList(graph.backend)
  1854. proc setupCgen*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
  1855. injectG()
  1856. result = newModule(g, module, graph.config)
  1857. result.idgen = idgen
  1858. if optGenIndex in graph.config.globalOptions and g.generatedHeader == nil:
  1859. let f = if graph.config.headerFile.len > 0: AbsoluteFile graph.config.headerFile
  1860. else: graph.config.projectFull
  1861. g.generatedHeader = rawNewModule(g, module,
  1862. changeFileExt(completeCfilePath(graph.config, f), hExt))
  1863. incl g.generatedHeader.flags, isHeaderFile
  1864. proc writeHeader(m: BModule) =
  1865. var result = headerTop()
  1866. var guard = "__$1__" % [m.filename.splitFile.name.rope]
  1867. result.addf("#ifndef $1$n#define $1$n", [guard])
  1868. addNimDefines(result, m.config)
  1869. generateHeaders(m)
  1870. generateThreadLocalStorage(m)
  1871. for i in cfsHeaders..cfsProcs:
  1872. result.add(m.s[i])
  1873. if m.config.cppCustomNamespace.len > 0 and i == cfsHeaders:
  1874. openNamespaceNim(m.config.cppCustomNamespace, result)
  1875. result.add(m.s[cfsInitProc])
  1876. if optGenDynLib in m.config.globalOptions:
  1877. result.add("N_LIB_IMPORT ")
  1878. result.addf("N_CDECL(void, $1NimMain)(void);$n", [rope m.config.nimMainPrefix])
  1879. if m.config.cppCustomNamespace.len > 0: closeNamespaceNim(result)
  1880. result.addf("#endif /* $1 */$n", [guard])
  1881. if not writeRope(result, m.filename):
  1882. rawMessage(m.config, errCannotOpenFile, m.filename.string)
  1883. proc getCFile(m: BModule): AbsoluteFile =
  1884. let ext =
  1885. if m.compileToCpp: ".nim.cpp"
  1886. elif m.config.backend == backendObjc or sfCompileToObjc in m.module.flags: ".nim.m"
  1887. else: ".nim.c"
  1888. result = changeFileExt(completeCfilePath(m.config, mangleModuleName(m.config, m.cfilename).AbsoluteFile), ext)
  1889. when false:
  1890. proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
  1891. injectG()
  1892. var m = newModule(g, module, graph.config)
  1893. readMergeInfo(getCFile(m), m)
  1894. result = m
  1895. proc addHcrInitGuards(p: BProc, n: PNode, inInitGuard: var bool) =
  1896. if n.kind == nkStmtList:
  1897. for child in n:
  1898. addHcrInitGuards(p, child, inInitGuard)
  1899. else:
  1900. let stmtShouldExecute = n.kind in {nkVarSection, nkLetSection} or
  1901. nfExecuteOnReload in n.flags
  1902. if inInitGuard:
  1903. if stmtShouldExecute:
  1904. endBlock(p)
  1905. inInitGuard = false
  1906. else:
  1907. if not stmtShouldExecute:
  1908. line(p, cpsStmts, "if (nim_hcr_do_init_)\n")
  1909. startBlock(p)
  1910. inInitGuard = true
  1911. genStmts(p, n)
  1912. proc genTopLevelStmt*(m: BModule; n: PNode) =
  1913. ## Also called from `ic/cbackend.nim`.
  1914. if pipelineutils.skipCodegen(m.config, n): return
  1915. m.initProc.options = initProcOptions(m)
  1916. #softRnl = if optLineDir in m.config.options: noRnl else: rnl
  1917. # XXX replicate this logic!
  1918. var transformedN = transformStmt(m.g.graph, m.idgen, m.module, n)
  1919. if sfInjectDestructors in m.module.flags:
  1920. transformedN = injectDestructorCalls(m.g.graph, m.idgen, m.module, transformedN)
  1921. if m.hcrOn:
  1922. addHcrInitGuards(m.initProc, transformedN, m.inHcrInitGuard)
  1923. else:
  1924. genProcBody(m.initProc, transformedN)
  1925. proc shouldRecompile(m: BModule; code: Rope, cfile: Cfile): bool =
  1926. if optForceFullMake notin m.config.globalOptions:
  1927. if not moduleHasChanged(m.g.graph, m.module):
  1928. result = false
  1929. elif not equalsFile(code, cfile.cname):
  1930. when false:
  1931. #m.config.symbolFiles == readOnlySf: #isDefined(m.config, "nimdiff"):
  1932. if fileExists(cfile.cname):
  1933. copyFile(cfile.cname.string, cfile.cname.string & ".backup")
  1934. echo "diff ", cfile.cname.string, ".backup ", cfile.cname.string
  1935. else:
  1936. echo "new file ", cfile.cname.string
  1937. if not writeRope(code, cfile.cname):
  1938. rawMessage(m.config, errCannotOpenFile, cfile.cname.string)
  1939. result = true
  1940. elif fileExists(cfile.obj) and os.fileNewer(cfile.obj.string, cfile.cname.string):
  1941. result = false
  1942. else:
  1943. result = true
  1944. else:
  1945. if not writeRope(code, cfile.cname):
  1946. rawMessage(m.config, errCannotOpenFile, cfile.cname.string)
  1947. result = true
  1948. # We need 2 different logics here: pending modules (including
  1949. # 'nim__dat') may require file merging for the combination of dead code
  1950. # elimination and incremental compilation! Non pending modules need no
  1951. # such logic and in fact the logic hurts for the main module at least;
  1952. # it would generate multiple 'main' procs, for instance.
  1953. proc writeModule(m: BModule, pending: bool) =
  1954. template onExit() = close(m.ndi, m.config)
  1955. let cfile = getCFile(m)
  1956. if moduleHasChanged(m.g.graph, m.module):
  1957. genInitCode(m)
  1958. finishTypeDescriptions(m)
  1959. if sfMainModule in m.module.flags:
  1960. # generate main file:
  1961. genMainProc(m)
  1962. m.s[cfsProcHeaders].add(m.g.mainModProcs)
  1963. generateThreadVarsSize(m)
  1964. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1965. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1966. var code = genModule(m, cf)
  1967. if code != "" or m.config.symbolFiles != disabledSf:
  1968. when hasTinyCBackend:
  1969. if m.config.cmd == cmdTcc:
  1970. tccgen.compileCCode($code, m.config)
  1971. onExit()
  1972. return
  1973. if not shouldRecompile(m, code, cf): cf.flags = {CfileFlag.Cached}
  1974. addFileToCompile(m.config, cf)
  1975. onExit()
  1976. proc updateCachedModule(m: BModule) =
  1977. let cfile = getCFile(m)
  1978. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1979. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1980. if sfMainModule notin m.module.flags:
  1981. genMainProc(m)
  1982. cf.flags = {CfileFlag.Cached}
  1983. addFileToCompile(m.config, cf)
  1984. proc generateLibraryDestroyGlobals(graph: ModuleGraph; m: BModule; body: PNode; isDynlib: bool): PSym =
  1985. let procname = getIdent(graph.cache, "NimDestroyGlobals")
  1986. result = newSym(skProc, procname, m.idgen, m.module.owner, m.module.info)
  1987. result.typ = newProcType(m.module.info, m.idgen, m.module.owner)
  1988. result.typ.callConv = ccCDecl
  1989. incl result.flags, sfExportc
  1990. result.loc.r = "NimDestroyGlobals"
  1991. if isDynlib:
  1992. incl(result.loc.flags, lfExportLib)
  1993. let theProc = newNodeI(nkProcDef, m.module.info, bodyPos+1)
  1994. for i in 0..<theProc.len: theProc[i] = newNodeI(nkEmpty, m.module.info)
  1995. theProc[namePos] = newSymNode(result)
  1996. theProc[bodyPos] = body
  1997. result.ast = theProc
  1998. proc finalCodegenActions*(graph: ModuleGraph; m: BModule; n: PNode) =
  1999. ## Also called from IC.
  2000. if sfMainModule in m.module.flags:
  2001. # phase ordering problem here: We need to announce this
  2002. # dependency to 'nimTestErrorFlag' before system.c has been written to disk.
  2003. if m.config.exc == excGoto and getCompilerProc(graph, "nimTestErrorFlag") != nil:
  2004. cgsym(m, "nimTestErrorFlag")
  2005. if {optGenStaticLib, optGenDynLib, optNoMain} * m.config.globalOptions == {}:
  2006. for i in countdown(high(graph.globalDestructors), 0):
  2007. n.add graph.globalDestructors[i]
  2008. else:
  2009. var body = newNodeI(nkStmtList, m.module.info)
  2010. for i in countdown(high(graph.globalDestructors), 0):
  2011. body.add graph.globalDestructors[i]
  2012. body.flags.incl nfTransf # should not be further transformed
  2013. let dtor = generateLibraryDestroyGlobals(graph, m, body, optGenDynLib in m.config.globalOptions)
  2014. genProcAux(m, dtor)
  2015. if pipelineutils.skipCodegen(m.config, n): return
  2016. if moduleHasChanged(graph, m.module):
  2017. # if the module is cached, we don't regenerate the main proc
  2018. # nor the dispatchers? But if the dispatchers changed?
  2019. # XXX emit the dispatchers into its own .c file?
  2020. if n != nil:
  2021. m.initProc.options = initProcOptions(m)
  2022. genProcBody(m.initProc, n)
  2023. if m.hcrOn:
  2024. # make sure this is pulled in (meaning hcrGetGlobal() is called for it during init)
  2025. let sym = magicsys.getCompilerProc(m.g.graph, "programResult")
  2026. # ignore when not available, could be a module imported early in `system`
  2027. if sym != nil:
  2028. cgsymImpl m, sym
  2029. if m.inHcrInitGuard:
  2030. endBlock(m.initProc)
  2031. if sfMainModule in m.module.flags:
  2032. if m.hcrOn:
  2033. # pull ("define" since they are inline when HCR is on) these functions in the main file
  2034. # so it can load the HCR runtime and later pass the library handle to the HCR runtime which
  2035. # will in turn pass it to the other modules it initializes so they can initialize the
  2036. # register/get procs so they don't have to have the definitions of these functions as well
  2037. cgsym(m, "nimLoadLibrary")
  2038. cgsym(m, "nimLoadLibraryError")
  2039. cgsym(m, "nimGetProcAddr")
  2040. cgsym(m, "procAddrError")
  2041. cgsym(m, "rawWrite")
  2042. # raise dependencies on behalf of genMainProc
  2043. if m.config.target.targetOS != osStandalone and m.config.selectedGC notin {gcNone, gcArc, gcAtomicArc, gcOrc}:
  2044. cgsym(m, "initStackBottomWith")
  2045. if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone:
  2046. cgsym(m, "initThreadVarsEmulation")
  2047. if m.g.forwardedProcs.len == 0:
  2048. incl m.flags, objHasKidsValid
  2049. if optMultiMethods in m.g.config.globalOptions or
  2050. m.g.config.selectedGC notin {gcArc, gcOrc, gcAtomicArc} or
  2051. vtables notin m.g.config.features:
  2052. generateIfMethodDispatchers(graph, m.idgen)
  2053. let mm = m
  2054. m.g.modulesClosed.add mm
  2055. proc genForwardedProcs(g: BModuleList) =
  2056. # Forward declared proc:s lack bodies when first encountered, so they're given
  2057. # a second pass here
  2058. # Note: ``genProcNoForward`` may add to ``forwardedProcs``
  2059. while g.forwardedProcs.len > 0:
  2060. let
  2061. prc = g.forwardedProcs.pop()
  2062. m = g.modules[prc.itemId.module]
  2063. if sfForward in prc.flags:
  2064. internalError(m.config, prc.info, "still forwarded: " & prc.name.s)
  2065. genProcNoForward(m, prc)
  2066. proc cgenWriteModules*(backend: RootRef, config: ConfigRef) =
  2067. let g = BModuleList(backend)
  2068. g.config = config
  2069. # we need to process the transitive closure because recursive module
  2070. # deps are allowed (and the system module is processed in the wrong
  2071. # order anyway)
  2072. genForwardedProcs(g)
  2073. for m in cgenModules(g):
  2074. m.writeModule(pending=true)
  2075. writeMapping(config, g.mapping)
  2076. if g.generatedHeader != nil: writeHeader(g.generatedHeader)