cgen.nim 81 KB

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