cgen.nim 81 KB

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