cgen.nim 82 KB

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