cgen.nim 79 KB

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