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