cgen.nim 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  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:
  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.backend == backendCpp 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. template mapTypeChooser(n: PNode): TSymKind =
  255. (if n.kind == nkSym: n.sym.kind else: skVar)
  256. template mapTypeChooser(a: TLoc): TSymKind = mapTypeChooser(a.lode)
  257. proc addrLoc(conf: ConfigRef; a: TLoc): Rope =
  258. result = a.r
  259. if lfIndirect notin a.flags and mapType(conf, a.t, mapTypeChooser(a)) != ctArray:
  260. result = "(&" & result & ")"
  261. proc byRefLoc(p: BProc; a: TLoc): Rope =
  262. result = a.r
  263. if lfIndirect notin a.flags and mapType(p.config, a.t, mapTypeChooser(a)) != ctArray and not
  264. p.module.compileToCpp:
  265. result = "(&" & result & ")"
  266. proc rdCharLoc(a: TLoc): Rope =
  267. # read a location that may need a char-cast:
  268. result = rdLoc(a)
  269. if skipTypes(a.t, abstractRange).kind == tyChar:
  270. result = "((NU8)($1))" % [result]
  271. type
  272. TAssignmentFlag = enum
  273. needToCopy
  274. TAssignmentFlags = set[TAssignmentFlag]
  275. proc genObjConstr(p: BProc, e: PNode, d: var TLoc)
  276. proc rawConstExpr(p: BProc, n: PNode; d: var TLoc)
  277. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags)
  278. type
  279. ObjConstrMode = enum
  280. constructObj,
  281. constructRefObj
  282. proc genObjectInit(p: BProc, section: TCProcSection, t: PType, a: var TLoc,
  283. mode: ObjConstrMode) =
  284. #if optNimV2 in p.config.globalOptions: return
  285. case analyseObjectWithTypeField(t)
  286. of frNone:
  287. discard
  288. of frHeader:
  289. var r = rdLoc(a)
  290. if mode == constructRefObj: r = "(*$1)" % [r]
  291. var s = skipTypes(t, abstractInst)
  292. if not p.module.compileToCpp:
  293. while s.kind == tyObject and s[0] != nil:
  294. r.add(".Sup")
  295. s = skipTypes(s[0], skipPtrs)
  296. if optTinyRtti in p.config.globalOptions:
  297. linefmt(p, section, "$1.m_type = $2;$n", [r, genTypeInfoV2(p.module, t, a.lode.info)])
  298. else:
  299. linefmt(p, section, "$1.m_type = $2;$n", [r, genTypeInfoV1(p.module, t, a.lode.info)])
  300. of frEmbedded:
  301. if optTinyRtti in p.config.globalOptions:
  302. var tmp: TLoc
  303. if mode == constructRefObj:
  304. let objType = t.skipTypes(abstractInst+{tyRef})
  305. rawConstExpr(p, newNodeIT(nkType, a.lode.info, objType), tmp)
  306. linefmt(p, cpsStmts,
  307. "#nimCopyMem((void*)$1, (NIM_CONST void*)&$2, sizeof($3));$n",
  308. [rdLoc(a), rdLoc(tmp), getTypeDesc(p.module, objType, mapTypeChooser(a))])
  309. else:
  310. rawConstExpr(p, newNodeIT(nkType, a.lode.info, t), tmp)
  311. genAssignment(p, a, tmp, {})
  312. else:
  313. # worst case for performance:
  314. var r = if mode == constructObj: addrLoc(p.config, a) else: rdLoc(a)
  315. linefmt(p, section, "#objectInit($1, $2);$n", [r, genTypeInfoV1(p.module, t, a.lode.info)])
  316. if isException(t):
  317. var r = rdLoc(a)
  318. if mode == constructRefObj: r = "(*$1)" % [r]
  319. var s = skipTypes(t, abstractInst)
  320. if not p.module.compileToCpp:
  321. while s.kind == tyObject and s[0] != nil and s.sym.magic != mException:
  322. r.add(".Sup")
  323. s = skipTypes(s[0], skipPtrs)
  324. linefmt(p, section, "$1.name = $2;$n", [r, makeCString(t.skipTypes(abstractInst).sym.name.s)])
  325. proc genRefAssign(p: BProc, dest, src: TLoc)
  326. proc isComplexValueType(t: PType): bool {.inline.} =
  327. let t = t.skipTypes(abstractInst + tyUserTypeClasses)
  328. result = t.kind in {tyArray, tySet, tyTuple, tyObject, tyOpenArray} or
  329. (t.kind == tyProc and t.callConv == ccClosure)
  330. include ccgreset
  331. proc resetLoc(p: BProc, loc: var TLoc) =
  332. let containsGcRef = optSeqDestructors notin p.config.globalOptions and containsGarbageCollectedRef(loc.t)
  333. let typ = skipTypes(loc.t, abstractVarRange)
  334. if isImportedCppType(typ): return
  335. if optSeqDestructors in p.config.globalOptions and typ.kind in {tyString, tySequence}:
  336. assert rdLoc(loc) != nil
  337. linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
  338. elif not isComplexValueType(typ):
  339. if containsGcRef:
  340. var nilLoc: TLoc
  341. initLoc(nilLoc, locTemp, loc.lode, OnStack)
  342. nilLoc.r = rope("NIM_NIL")
  343. genRefAssign(p, loc, nilLoc)
  344. else:
  345. linefmt(p, cpsStmts, "$1 = 0;$n", [rdLoc(loc)])
  346. else:
  347. if loc.storage != OnStack and containsGcRef:
  348. specializeReset(p, loc)
  349. when false:
  350. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  351. [addrLoc(p.config, loc), genTypeInfoV1(p.module, loc.t, loc.lode.info)])
  352. # XXX: generated reset procs should not touch the m_type
  353. # field, so disabling this should be safe:
  354. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  355. else:
  356. # array passed as argument decayed into pointer, bug #7332
  357. # so we use getTypeDesc here rather than rdLoc(loc)
  358. linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  359. [addrLoc(p.config, loc),
  360. getTypeDesc(p.module, loc.t, mapTypeChooser(loc))])
  361. # XXX: We can be extra clever here and call memset only
  362. # on the bytes following the m_type field?
  363. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  364. proc constructLoc(p: BProc, loc: var TLoc, isTemp = false) =
  365. let typ = loc.t
  366. if optSeqDestructors in p.config.globalOptions and skipTypes(typ, abstractInst + {tyStatic}).kind in {tyString, tySequence}:
  367. linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
  368. elif not isComplexValueType(typ):
  369. linefmt(p, cpsStmts, "$1 = ($2)0;$n", [rdLoc(loc),
  370. getTypeDesc(p.module, typ, mapTypeChooser(loc))])
  371. else:
  372. if not isTemp or containsGarbageCollectedRef(loc.t):
  373. # don't use nimZeroMem for temporary values for performance if we can
  374. # avoid it:
  375. if not isImportedCppType(typ):
  376. linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  377. [addrLoc(p.config, loc), getTypeDesc(p.module, typ, mapTypeChooser(loc))])
  378. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  379. proc initLocalVar(p: BProc, v: PSym, immediateAsgn: bool) =
  380. if sfNoInit notin v.flags:
  381. # we know it is a local variable and thus on the stack!
  382. # If ``not immediateAsgn`` it is not initialized in a binding like
  383. # ``var v = X`` and thus we need to init it.
  384. # If ``v`` contains a GC-ref we may pass it to ``unsureAsgnRef`` somehow
  385. # which requires initialization. However this can really only happen if
  386. # ``var v = X()`` gets transformed into ``X(&v)``.
  387. # Nowadays the logic in ccgcalls deals with this case however.
  388. if not immediateAsgn:
  389. constructLoc(p, v.loc)
  390. proc getTemp(p: BProc, t: PType, result: var TLoc; needsInit=false) =
  391. inc(p.labels)
  392. result.r = "T" & rope(p.labels) & "_"
  393. linefmt(p, cpsLocals, "$1 $2;$n", [getTypeDesc(p.module, t, skVar), result.r])
  394. result.k = locTemp
  395. result.lode = lodeTyp t
  396. result.storage = OnStack
  397. result.flags = {}
  398. constructLoc(p, result, not needsInit)
  399. proc getTempCpp(p: BProc, t: PType, result: var TLoc; value: Rope) =
  400. inc(p.labels)
  401. result.r = "T" & rope(p.labels) & "_"
  402. linefmt(p, cpsStmts, "$1 $2 = $3;$n", [getTypeDesc(p.module, t, skVar), result.r, value])
  403. result.k = locTemp
  404. result.lode = lodeTyp t
  405. result.storage = OnStack
  406. result.flags = {}
  407. proc getIntTemp(p: BProc, result: var TLoc) =
  408. inc(p.labels)
  409. result.r = "T" & rope(p.labels) & "_"
  410. linefmt(p, cpsLocals, "NI $1;$n", [result.r])
  411. result.k = locTemp
  412. result.storage = OnStack
  413. result.lode = lodeTyp getSysType(p.module.g.graph, unknownLineInfo, tyInt)
  414. result.flags = {}
  415. proc localVarDecl(p: BProc; n: PNode): Rope =
  416. let s = n.sym
  417. if s.loc.k == locNone:
  418. fillLoc(s.loc, locLocalVar, n, mangleLocalName(p, s), OnStack)
  419. if s.kind == skLet: incl(s.loc.flags, lfNoDeepCopy)
  420. if s.kind in {skLet, skVar, skField, skForVar} and s.alignment > 0:
  421. result.addf("NIM_ALIGN($1) ", [rope(s.alignment)])
  422. result.add getTypeDesc(p.module, s.typ, skVar)
  423. if s.constraint.isNil:
  424. if sfRegister in s.flags: result.add(" register")
  425. #elif skipTypes(s.typ, abstractInst).kind in GcTypeKinds:
  426. # decl.add(" GC_GUARD")
  427. if sfVolatile in s.flags: result.add(" volatile")
  428. if sfNoalias in s.flags: result.add(" NIM_NOALIAS")
  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, skVar)
  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 sfNoalias in s.flags: decl.add(" NIM_NOALIAS")
  484. if value != nil:
  485. decl.addf(" $1 = $2;$n", [s.loc.r, value])
  486. else:
  487. decl.addf(" $1;$n", [s.loc.r])
  488. else:
  489. if value != nil:
  490. decl = runtimeFormat(s.cgDeclFrmt & " = $#;$n", [td, s.loc.r, value])
  491. else:
  492. decl = runtimeFormat(s.cgDeclFrmt & ";$n", [td, s.loc.r])
  493. p.module.s[cfsVars].add(decl)
  494. if p.withinLoop > 0 and value == nil:
  495. # fixes tests/run/tzeroarray:
  496. resetLoc(p, s.loc)
  497. proc assignParam(p: BProc, s: PSym, retType: PType) =
  498. assert(s.loc.r != nil)
  499. scopeMangledParam(p, s)
  500. proc fillProcLoc(m: BModule; n: PNode) =
  501. let sym = n.sym
  502. if sym.loc.k == locNone:
  503. fillLoc(sym.loc, locProc, n, mangleName(m, sym), OnStack)
  504. proc getLabel(p: BProc): TLabel =
  505. inc(p.labels)
  506. result = "LA" & rope(p.labels) & "_"
  507. proc fixLabel(p: BProc, labl: TLabel) =
  508. lineF(p, cpsStmts, "$1: ;$n", [labl])
  509. proc genVarPrototype(m: BModule, n: PNode)
  510. proc requestConstImpl(p: BProc, sym: PSym)
  511. proc genStmts(p: BProc, t: PNode)
  512. proc expr(p: BProc, n: PNode, d: var TLoc)
  513. proc genProcPrototype(m: BModule, sym: PSym)
  514. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc)
  515. proc intLiteral(i: BiggestInt): Rope
  516. proc genLiteral(p: BProc, n: PNode): Rope
  517. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType): Rope
  518. proc raiseExit(p: BProc)
  519. proc initLocExpr(p: BProc, e: PNode, result: var TLoc) =
  520. initLoc(result, locNone, e, OnUnknown)
  521. expr(p, e, result)
  522. proc initLocExprSingleUse(p: BProc, e: PNode, result: var TLoc) =
  523. initLoc(result, locNone, e, OnUnknown)
  524. if e.kind in nkCallKinds and (e[0].kind != nkSym or e[0].sym.magic == mNone):
  525. # We cannot check for tfNoSideEffect here because of mutable parameters.
  526. discard "bug #8202; enforce evaluation order for nested calls for C++ too"
  527. # We may need to consider that 'f(g())' cannot be rewritten to 'tmp = g(); f(tmp)'
  528. # if 'tmp' lacks a move/assignment operator.
  529. if e[0].kind == nkSym and sfCompileToCpp in e[0].sym.flags:
  530. result.flags.incl lfSingleUse
  531. else:
  532. result.flags.incl lfSingleUse
  533. expr(p, e, result)
  534. include ccgcalls, "ccgstmts.nim"
  535. proc initFrame(p: BProc, procname, filename: Rope): Rope =
  536. const frameDefines = """
  537. $1 define nimfr_(proc, file) \
  538. TFrame FR_; \
  539. FR_.procname = proc; FR_.filename = file; FR_.line = 0; FR_.len = 0; #nimFrame(&FR_);
  540. $1 define nimfrs_(proc, file, slots, length) \
  541. struct {TFrame* prev;NCSTRING procname;NI line;NCSTRING filename; NI len; VarSlot s[slots];} FR_; \
  542. FR_.procname = proc; FR_.filename = file; FR_.line = 0; FR_.len = length; #nimFrame((TFrame*)&FR_);
  543. $1 define nimln_(n, file) \
  544. FR_.line = n; FR_.filename = file;
  545. """
  546. if p.module.s[cfsFrameDefines].len == 0:
  547. appcg(p.module, p.module.s[cfsFrameDefines], frameDefines, ["#"])
  548. discard cgsym(p.module, "nimFrame")
  549. result = ropecg(p.module, "\tnimfr_($1, $2);$n", [procname, filename])
  550. proc initFrameNoDebug(p: BProc; frame, procname, filename: Rope; line: int): Rope =
  551. discard cgsym(p.module, "nimFrame")
  552. p.blocks[0].sections[cpsLocals].addf("TFrame $1;$n", [frame])
  553. result = ropecg(p.module, "\t$1.procname = $2; $1.filename = $3; " &
  554. " $1.line = $4; $1.len = -1; nimFrame(&$1);$n",
  555. [frame, procname, filename, line])
  556. proc deinitFrameNoDebug(p: BProc; frame: Rope): Rope =
  557. result = ropecg(p.module, "\t#popFrameOfAddr(&$1);$n", [frame])
  558. proc deinitFrame(p: BProc): Rope =
  559. result = ropecg(p.module, "\t#popFrame();$n", [])
  560. include ccgexprs
  561. # ----------------------------- dynamic library handling -----------------
  562. # We don't finalize dynamic libs as the OS does this for us.
  563. proc isGetProcAddr(lib: PLib): bool =
  564. let n = lib.path
  565. result = n.kind in nkCallKinds and n.typ != nil and
  566. n.typ.kind in {tyPointer, tyProc}
  567. proc loadDynamicLib(m: BModule, lib: PLib) =
  568. assert(lib != nil)
  569. if not lib.generated:
  570. lib.generated = true
  571. var tmp = getTempName(m)
  572. assert(lib.name == nil)
  573. lib.name = tmp # BUGFIX: cgsym has awful side-effects
  574. m.s[cfsVars].addf("static void* $1;$n", [tmp])
  575. if lib.path.kind in {nkStrLit..nkTripleStrLit}:
  576. var s: TStringSeq = @[]
  577. libCandidates(lib.path.strVal, s)
  578. rawMessage(m.config, hintDependency, lib.path.strVal)
  579. var loadlib: Rope = nil
  580. for i in 0..high(s):
  581. inc(m.labels)
  582. if i > 0: loadlib.add("||")
  583. let n = newStrNode(nkStrLit, s[i])
  584. n.info = lib.path.info
  585. appcg(m, loadlib, "($1 = #nimLoadLibrary($2))$n",
  586. [tmp, genStringLiteral(m, n)])
  587. appcg(m, m.s[cfsDynLibInit],
  588. "if (!($1)) #nimLoadLibraryError($2);$n",
  589. [loadlib, genStringLiteral(m, lib.path)])
  590. else:
  591. var p = newProc(nil, m)
  592. p.options.excl optStackTrace
  593. p.flags.incl nimErrorFlagDisabled
  594. var dest: TLoc
  595. initLoc(dest, locTemp, lib.path, OnStack)
  596. dest.r = getTempName(m)
  597. appcg(m, m.s[cfsDynLibInit],"$1 $2;$n",
  598. [getTypeDesc(m, lib.path.typ, skVar), rdLoc(dest)])
  599. expr(p, lib.path, dest)
  600. m.s[cfsVars].add(p.s(cpsLocals))
  601. m.s[cfsDynLibInit].add(p.s(cpsInit))
  602. m.s[cfsDynLibInit].add(p.s(cpsStmts))
  603. appcg(m, m.s[cfsDynLibInit],
  604. "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n",
  605. [tmp, rdLoc(dest)])
  606. if lib.name == nil: internalError(m.config, "loadDynamicLib")
  607. proc mangleDynLibProc(sym: PSym): Rope =
  608. # we have to build this as a single rope in order not to trip the
  609. # optimization in genInfixCall, see test tests/cpp/t8241.nim
  610. if sfCompilerProc in sym.flags:
  611. # NOTE: sym.loc.r is the external name!
  612. result = rope(sym.name.s)
  613. else:
  614. result = rope(strutils.`%`("Dl_$1_", $sym.id))
  615. proc symInDynamicLib(m: BModule, sym: PSym) =
  616. var lib = sym.annex
  617. let isCall = isGetProcAddr(lib)
  618. var extname = sym.loc.r
  619. if not isCall: loadDynamicLib(m, lib)
  620. var tmp = mangleDynLibProc(sym)
  621. sym.loc.r = tmp # from now on we only need the internal name
  622. sym.typ.sym = nil # generate a new name
  623. inc(m.labels, 2)
  624. if isCall:
  625. let n = lib.path
  626. var a: TLoc
  627. initLocExpr(m.initProc, n[0], a)
  628. var params = rdLoc(a) & "("
  629. for i in 1..<n.len-1:
  630. initLocExpr(m.initProc, n[i], a)
  631. params.add(rdLoc(a))
  632. params.add(", ")
  633. let load = "\t$1 = ($2) ($3$4));$n" %
  634. [tmp, getTypeDesc(m, sym.typ, skVar), params, makeCString($extname)]
  635. var last = lastSon(n)
  636. if last.kind == nkHiddenStdConv: last = last[1]
  637. internalAssert(m.config, last.kind == nkStrLit)
  638. let idx = last.strVal
  639. if idx.len == 0:
  640. m.initProc.s(cpsStmts).add(load)
  641. elif idx.len == 1 and idx[0] in {'0'..'9'}:
  642. m.extensionLoaders[idx[0]].add(load)
  643. else:
  644. internalError(m.config, sym.info, "wrong index: " & idx)
  645. else:
  646. appcg(m, m.s[cfsDynLibInit],
  647. "\t$1 = ($2) #nimGetProcAddr($3, $4);$n",
  648. [tmp, getTypeDesc(m, sym.typ, skVar), lib.name, makeCString($extname)])
  649. m.s[cfsVars].addf("$2 $1;$n", [sym.loc.r, getTypeDesc(m, sym.loc.t, skVar)])
  650. proc varInDynamicLib(m: BModule, sym: PSym) =
  651. var lib = sym.annex
  652. var extname = sym.loc.r
  653. loadDynamicLib(m, lib)
  654. incl(sym.loc.flags, lfIndirect)
  655. var tmp = mangleDynLibProc(sym)
  656. sym.loc.r = tmp # from now on we only need the internal name
  657. inc(m.labels, 2)
  658. appcg(m, m.s[cfsDynLibInit],
  659. "$1 = ($2*) #nimGetProcAddr($3, $4);$n",
  660. [tmp, getTypeDesc(m, sym.typ, skVar), lib.name, makeCString($extname)])
  661. m.s[cfsVars].addf("$2* $1;$n",
  662. [sym.loc.r, getTypeDesc(m, sym.loc.t, skVar)])
  663. proc symInDynamicLibPartial(m: BModule, sym: PSym) =
  664. sym.loc.r = mangleDynLibProc(sym)
  665. sym.typ.sym = nil # generate a new name
  666. proc cgsym(m: BModule, name: string): Rope =
  667. let sym = magicsys.getCompilerProc(m.g.graph, name)
  668. if sym != nil:
  669. case sym.kind
  670. of skProc, skFunc, skMethod, skConverter, skIterator: genProc(m, sym)
  671. of skVar, skResult, skLet: genVarPrototype(m, newSymNode sym)
  672. of skType: discard getTypeDesc(m, sym.typ)
  673. else: internalError(m.config, "cgsym: " & name & ": " & $sym.kind)
  674. else:
  675. # we used to exclude the system module from this check, but for DLL
  676. # generation support this sloppyness leads to hard to detect bugs, so
  677. # we're picky here for the system module too:
  678. rawMessage(m.config, errGenerated, "system module needs: " & name)
  679. result = sym.loc.r
  680. if m.hcrOn and sym != nil and sym.kind in {skProc..skIterator}:
  681. result.addActualSuffixForHCR(m.module, sym)
  682. proc generateHeaders(m: BModule) =
  683. m.s[cfsHeaders].add("\L#include \"nimbase.h\"\L")
  684. for it in m.headerFiles:
  685. if it[0] == '#':
  686. m.s[cfsHeaders].add(rope(it.replace('`', '"') & "\L"))
  687. elif it[0] notin {'"', '<'}:
  688. m.s[cfsHeaders].addf("#include \"$1\"$N", [rope(it)])
  689. else:
  690. m.s[cfsHeaders].addf("#include $1$N", [rope(it)])
  691. m.s[cfsHeaders].add("""#undef LANGUAGE_C
  692. #undef MIPSEB
  693. #undef MIPSEL
  694. #undef PPC
  695. #undef R3000
  696. #undef R4000
  697. #undef i386
  698. #undef linux
  699. #undef mips
  700. #undef near
  701. #undef far
  702. #undef powerpc
  703. #undef unix
  704. """)
  705. proc openNamespaceNim(namespace: string): Rope =
  706. result.add("namespace ")
  707. result.add(namespace)
  708. result.add(" {\L")
  709. proc closeNamespaceNim(): Rope =
  710. result.add("}\L")
  711. proc closureSetup(p: BProc, prc: PSym) =
  712. if tfCapturesEnv notin prc.typ.flags: return
  713. # prc.ast[paramsPos].last contains the type we're after:
  714. var ls = lastSon(prc.ast[paramsPos])
  715. if ls.kind != nkSym:
  716. internalError(p.config, prc.info, "closure generation failed")
  717. var env = ls.sym
  718. #echo "created environment: ", env.id, " for ", prc.name.s
  719. assignLocalVar(p, ls)
  720. # generate cast assignment:
  721. if p.config.selectedGC == gcGo:
  722. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, ($2) ClE_0);$n",
  723. [addrLoc(p.config, env.loc), getTypeDesc(p.module, env.typ)])
  724. else:
  725. linefmt(p, cpsStmts, "$1 = ($2) ClE_0;$n",
  726. [rdLoc(env.loc), getTypeDesc(p.module, env.typ)])
  727. proc containsResult(n: PNode): bool =
  728. if n.kind == nkSym and n.sym.kind == skResult:
  729. result = true
  730. else:
  731. for i in 0..<n.safeLen:
  732. if containsResult(n[i]): return true
  733. const harmless = {nkConstSection, nkTypeSection, nkEmpty, nkCommentStmt, nkTemplateDef, nkMacroDef} +
  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.backend != backendCpp) or (
  959. sym.flags * {sfInfixCall, sfCompilerProc, sfMangleCpp} == {} and
  960. sym.flags * {sfImportc, sfExportc} != {} and
  961. sym.magic == mNone and
  962. m.config.backend == backendCpp)
  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 m.hcrOn: incl(sym.loc.flags, lfIndirect)
  1056. if lfNoDecl in sym.loc.flags: return
  1057. # declare implementation:
  1058. var q = findPendingModule(m, sym)
  1059. if q != nil and not containsOrIncl(q.declaredThings, sym.id):
  1060. assert q.initProc.module == q
  1061. # add a suffix for hcr - will later init the global pointer with this data
  1062. let actualConstName = if m.hcrOn: sym.loc.r & "_const" else: sym.loc.r
  1063. q.s[cfsData].addf("N_LIB_PRIVATE NIM_CONST $1 $2 = $3;$n",
  1064. [getTypeDesc(q, sym.typ), actualConstName, genBracedInit(q.initProc, sym.ast, isConst = true)])
  1065. if m.hcrOn:
  1066. # generate the global pointer with the real name
  1067. q.s[cfsVars].addf("static $1* $2;$n", [getTypeDesc(m, sym.loc.t, skVar), sym.loc.r])
  1068. # register it (but ignore the boolean result of hcrRegisterGlobal)
  1069. q.initProc.procSec(cpsLocals).addf(
  1070. "\thcrRegisterGlobal($1, \"$2\", sizeof($3), NULL, (void**)&$2);$n",
  1071. [getModuleDllPath(q, sym), sym.loc.r, rdLoc(sym.loc)])
  1072. # always copy over the contents of the actual constant with the _const
  1073. # suffix ==> this means that the constant is reloadable & updatable!
  1074. q.initProc.procSec(cpsLocals).add(ropecg(q,
  1075. "\t#nimCopyMem((void*)$1, (NIM_CONST void*)&$2, sizeof($3));$n",
  1076. [sym.loc.r, actualConstName, rdLoc(sym.loc)]))
  1077. # declare header:
  1078. if q != m and not containsOrIncl(m.declaredThings, sym.id):
  1079. assert(sym.loc.r != nil)
  1080. if m.hcrOn:
  1081. m.s[cfsVars].addf("static $1* $2;$n", [getTypeDesc(m, sym.loc.t, skVar), sym.loc.r]);
  1082. m.initProc.procSec(cpsLocals).addf(
  1083. "\t$1 = ($2*)hcrGetGlobal($3, \"$1\");$n", [sym.loc.r,
  1084. getTypeDesc(m, sym.loc.t, skVar), getModuleDllPath(q, sym)])
  1085. else:
  1086. let headerDecl = "extern NIM_CONST $1 $2;$n" %
  1087. [getTypeDesc(m, sym.loc.t, skVar), sym.loc.r]
  1088. m.s[cfsData].add(headerDecl)
  1089. if sfExportc in sym.flags and p.module.g.generatedHeader != nil:
  1090. p.module.g.generatedHeader.s[cfsData].add(headerDecl)
  1091. proc isActivated(prc: PSym): bool = prc.typ != nil
  1092. proc genProc(m: BModule, prc: PSym) =
  1093. if sfBorrow in prc.flags or not isActivated(prc): return
  1094. if sfForward in prc.flags:
  1095. addForwardedProc(m, prc)
  1096. fillProcLoc(m, prc.ast[namePos])
  1097. else:
  1098. genProcNoForward(m, prc)
  1099. if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and
  1100. m.g.generatedHeader != nil and lfNoDecl notin prc.loc.flags:
  1101. genProcPrototype(m.g.generatedHeader, prc)
  1102. if prc.typ.callConv == ccInline:
  1103. if not containsOrIncl(m.g.generatedHeader.declaredThings, prc.id):
  1104. genProcAux(m.g.generatedHeader, prc)
  1105. proc genVarPrototype(m: BModule, n: PNode) =
  1106. #assert(sfGlobal in sym.flags)
  1107. let sym = n.sym
  1108. useHeader(m, sym)
  1109. fillLoc(sym.loc, locGlobalVar, n, mangleName(m, sym), OnHeap)
  1110. if treatGlobalDifferentlyForHCR(m, sym): incl(sym.loc.flags, lfIndirect)
  1111. if (lfNoDecl in sym.loc.flags) or contains(m.declaredThings, sym.id):
  1112. return
  1113. if sym.owner.id != m.module.id:
  1114. # else we already have the symbol generated!
  1115. assert(sym.loc.r != nil)
  1116. if sfThread in sym.flags:
  1117. declareThreadVar(m, sym, true)
  1118. else:
  1119. incl(m.declaredThings, sym.id)
  1120. if sym.kind in {skLet, skVar, skField, skForVar} and sym.alignment > 0:
  1121. m.s[cfsVars].addf "NIM_ALIGN($1) ", [rope(sym.alignment)]
  1122. m.s[cfsVars].add(if m.hcrOn: "static " else: "extern ")
  1123. m.s[cfsVars].add(getTypeDesc(m, sym.loc.t, skVar))
  1124. if m.hcrOn: m.s[cfsVars].add("*")
  1125. if lfDynamicLib in sym.loc.flags: m.s[cfsVars].add("*")
  1126. if sfRegister in sym.flags: m.s[cfsVars].add(" register")
  1127. if sfVolatile in sym.flags: m.s[cfsVars].add(" volatile")
  1128. if sfNoalias in sym.flags: m.s[cfsVars].add(" NIM_NOALIAS")
  1129. m.s[cfsVars].addf(" $1;$n", [sym.loc.r])
  1130. if m.hcrOn: m.initProc.procSec(cpsLocals).addf(
  1131. "\t$1 = ($2*)hcrGetGlobal($3, \"$1\");$n", [sym.loc.r,
  1132. getTypeDesc(m, sym.loc.t, skVar), getModuleDllPath(m, sym)])
  1133. proc addNimDefines(result: var Rope; conf: ConfigRef) {.inline.} =
  1134. result.addf("#define NIM_INTBITS $1\L", [
  1135. platform.CPU[conf.target.targetCPU].intSize.rope])
  1136. if conf.cppCustomNamespace.len > 0:
  1137. result.add("#define USE_NIM_NAMESPACE ")
  1138. result.add(conf.cppCustomNamespace)
  1139. result.add("\L")
  1140. if conf.isDefined("nimEmulateOverflowChecks"):
  1141. result.add("#define NIM_EmulateOverflowChecks\L")
  1142. proc getCopyright(conf: ConfigRef; cfile: Cfile): Rope =
  1143. if optCompileOnly in conf.globalOptions:
  1144. result = ("/* Generated by Nim Compiler v$1 */$N" &
  1145. "/* (c) " & copyrightYear & " Andreas Rumpf */$N" &
  1146. "/* The generated code is subject to the original license. */$N") %
  1147. [rope(VersionAsString)]
  1148. else:
  1149. result = ("/* Generated by Nim Compiler v$1 */$N" &
  1150. "/* (c) " & copyrightYear & " Andreas Rumpf */$N" &
  1151. "/* The generated code is subject to the original license. */$N" &
  1152. "/* Compiled for: $2, $3, $4 */$N" &
  1153. "/* Command for C compiler:$n $5 */$N") %
  1154. [rope(VersionAsString),
  1155. rope(platform.OS[conf.target.targetOS].name),
  1156. rope(platform.CPU[conf.target.targetCPU].name),
  1157. rope(extccomp.CC[conf.cCompiler].name),
  1158. rope(getCompileCFileCmd(conf, cfile))]
  1159. proc getFileHeader(conf: ConfigRef; cfile: Cfile): Rope =
  1160. result = getCopyright(conf, cfile)
  1161. if conf.hcrOn: result.add("#define NIM_HOT_CODE_RELOADING\L")
  1162. addNimDefines(result, conf)
  1163. proc getSomeNameForModule(m: PSym): Rope =
  1164. assert m.kind == skModule
  1165. assert m.owner.kind == skPackage
  1166. if {sfSystemModule, sfMainModule} * m.flags == {}:
  1167. result = m.owner.name.s.mangle.rope
  1168. result.add "_"
  1169. result.add m.name.s.mangle
  1170. proc getSomeInitName(m: BModule, suffix: string): Rope =
  1171. if not m.hcrOn:
  1172. result = getSomeNameForModule(m.module)
  1173. result.add suffix
  1174. proc getInitName(m: BModule): Rope =
  1175. if sfMainModule in m.module.flags:
  1176. # generate constant name for main module, for "easy" debugging.
  1177. result = rope"NimMainModule"
  1178. else:
  1179. result = getSomeInitName(m, "Init000")
  1180. proc getDatInitName(m: BModule): Rope = getSomeInitName(m, "DatInit000")
  1181. proc getHcrInitName(m: BModule): Rope = getSomeInitName(m, "HcrInit000")
  1182. proc hcrGetProcLoadCode(m: BModule, sym, prefix, handle, getProcFunc: string): Rope
  1183. proc genMainProc(m: BModule) =
  1184. ## this function is called in cgenWriteModules after all modules are closed,
  1185. ## it means raising dependency on the symbols is too late as it will not propagate
  1186. ## into other modules, only simple rope manipulations are allowed
  1187. var preMainCode: Rope
  1188. if m.hcrOn:
  1189. proc loadLib(handle: string, name: string): Rope =
  1190. let prc = magicsys.getCompilerProc(m.g.graph, name)
  1191. assert prc != nil
  1192. let n = newStrNode(nkStrLit, prc.annex.path.strVal)
  1193. n.info = prc.annex.path.info
  1194. appcg(m, result, "\tif (!($1 = #nimLoadLibrary($2)))$N" &
  1195. "\t\t#nimLoadLibraryError($2);$N",
  1196. [handle, genStringLiteral(m, n)])
  1197. preMainCode.add(loadLib("hcr_handle", "hcrGetProc"))
  1198. preMainCode.add("\tvoid* rtl_handle;\L")
  1199. preMainCode.add(loadLib("rtl_handle", "nimGC_setStackBottom"))
  1200. preMainCode.add(hcrGetProcLoadCode(m, "nimGC_setStackBottom", "nimrtl_", "rtl_handle", "nimGetProcAddr"))
  1201. preMainCode.add("\tinner = PreMain;\L")
  1202. preMainCode.add("\tinitStackBottomWith_actual((void *)&inner);\L")
  1203. preMainCode.add("\t(*inner)();\L")
  1204. else:
  1205. preMainCode.add("\tPreMain();\L")
  1206. const
  1207. # not a big deal if we always compile these 3 global vars... makes the HCR code easier
  1208. PosixCmdLine =
  1209. "N_LIB_PRIVATE int cmdCount;$N" &
  1210. "N_LIB_PRIVATE char** cmdLine;$N" &
  1211. "N_LIB_PRIVATE char** gEnv;$N"
  1212. # The use of a volatile function pointer to call Pre/NimMainInner
  1213. # prevents inlining of the NimMainInner function and dependent
  1214. # functions, which might otherwise merge their stack frames.
  1215. PreMainBody = "$N" &
  1216. "N_LIB_PRIVATE void PreMainInner(void) {$N" &
  1217. "$2" &
  1218. "}$N$N" &
  1219. PosixCmdLine &
  1220. "N_LIB_PRIVATE void PreMain(void) {$N" &
  1221. "\tvoid (*volatile inner)(void);$N" &
  1222. "\tinner = PreMainInner;$N" &
  1223. "$1" &
  1224. "\t(*inner)();$N" &
  1225. "}$N$N"
  1226. MainProcs =
  1227. "\tNimMain();$N"
  1228. MainProcsWithResult =
  1229. MainProcs & ("\treturn $1nim_program_result;$N")
  1230. NimMainInner = "N_LIB_PRIVATE N_CDECL(void, NimMainInner)(void) {$N" &
  1231. "$1" &
  1232. "}$N$N"
  1233. NimMainProc =
  1234. "N_CDECL(void, NimMain)(void) {$N" &
  1235. "\tvoid (*volatile inner)(void);$N" &
  1236. "$4" &
  1237. "\tinner = NimMainInner;$N" &
  1238. "$2" &
  1239. "\t(*inner)();$N" &
  1240. "}$N$N"
  1241. NimMainBody = NimMainInner & NimMainProc
  1242. PosixCMain =
  1243. "int main(int argc, char** args, char** env) {$N" &
  1244. "\tcmdLine = args;$N" &
  1245. "\tcmdCount = argc;$N" &
  1246. "\tgEnv = env;$N" &
  1247. MainProcsWithResult &
  1248. "}$N$N"
  1249. StandaloneCMain =
  1250. "int main(void) {$N" &
  1251. MainProcs &
  1252. "\treturn 0;$N" &
  1253. "}$N$N"
  1254. WinNimMain = NimMainBody
  1255. WinCMain = "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N" &
  1256. " HINSTANCE hPrevInstance, $N" &
  1257. " LPSTR lpCmdLine, int nCmdShow) {$N" &
  1258. MainProcsWithResult & "}$N$N"
  1259. WinNimDllMain = NimMainInner & "N_LIB_EXPORT " & NimMainProc
  1260. WinCDllMain =
  1261. "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N" &
  1262. " LPVOID lpvReserved) {$N" &
  1263. "\tif(fwdreason == DLL_PROCESS_ATTACH) {$N" & MainProcs & "}$N" &
  1264. "\treturn 1;$N}$N$N"
  1265. PosixNimDllMain = WinNimDllMain
  1266. PosixCDllMain =
  1267. "N_LIB_PRIVATE void NIM_POSIX_INIT NimMainInit(void) {$N" &
  1268. MainProcs &
  1269. "}$N$N"
  1270. GenodeNimMain =
  1271. "extern Genode::Env *nim_runtime_env;$N" &
  1272. "extern void nim_component_construct(Genode::Env*);$N$N" &
  1273. NimMainBody
  1274. ComponentConstruct =
  1275. "void Libc::Component::construct(Libc::Env &env) {$N" &
  1276. "\t// Set Env used during runtime initialization$N" &
  1277. "\tnim_runtime_env = &env;$N" &
  1278. "\tLibc::with_libc([&] () {$N\t" &
  1279. "\t// Initialize runtime and globals$N" &
  1280. MainProcs &
  1281. "\t// Call application construct$N" &
  1282. "\t\tnim_component_construct(&env);$N" &
  1283. "\t});$N" &
  1284. "}$N$N"
  1285. if m.config.target.targetOS == osWindows and
  1286. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1287. m.includeHeader("<windows.h>")
  1288. elif m.config.target.targetOS == osGenode:
  1289. m.includeHeader("<libc/component.h>")
  1290. let initStackBottomCall =
  1291. if m.config.target.targetOS == osStandalone or m.config.selectedGC == gcNone: "".rope
  1292. else: ropecg(m, "\t#initStackBottomWith((void *)&inner);$N", [])
  1293. inc(m.labels)
  1294. appcg(m, m.s[cfsProcs], PreMainBody, [m.g.mainDatInit, m.g.otherModsInit])
  1295. if m.config.target.targetOS == osWindows and
  1296. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1297. if optGenGuiApp in m.config.globalOptions:
  1298. const nimMain = WinNimMain
  1299. appcg(m, m.s[cfsProcs], nimMain,
  1300. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode])
  1301. else:
  1302. const nimMain = WinNimDllMain
  1303. appcg(m, m.s[cfsProcs], nimMain,
  1304. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode])
  1305. elif m.config.target.targetOS == osGenode:
  1306. const nimMain = GenodeNimMain
  1307. appcg(m, m.s[cfsProcs], nimMain,
  1308. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode])
  1309. elif optGenDynLib in m.config.globalOptions:
  1310. const nimMain = PosixNimDllMain
  1311. appcg(m, m.s[cfsProcs], nimMain,
  1312. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode])
  1313. elif m.config.target.targetOS == osStandalone:
  1314. const nimMain = NimMainBody
  1315. appcg(m, m.s[cfsProcs], nimMain,
  1316. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode])
  1317. else:
  1318. const nimMain = NimMainBody
  1319. appcg(m, m.s[cfsProcs], nimMain,
  1320. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode])
  1321. if optNoMain notin m.config.globalOptions:
  1322. if m.config.cppCustomNamespace.len > 0:
  1323. m.s[cfsProcs].add closeNamespaceNim() & "using namespace " & m.config.cppCustomNamespace & ";\L"
  1324. if m.config.target.targetOS == osWindows and
  1325. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1326. if optGenGuiApp in m.config.globalOptions:
  1327. const otherMain = WinCMain
  1328. appcg(m, m.s[cfsProcs], otherMain, [if m.hcrOn: "*" else: ""])
  1329. else:
  1330. const otherMain = WinCDllMain
  1331. appcg(m, m.s[cfsProcs], otherMain, [])
  1332. elif m.config.target.targetOS == osGenode:
  1333. const otherMain = ComponentConstruct
  1334. appcg(m, m.s[cfsProcs], otherMain, [])
  1335. elif optGenDynLib in m.config.globalOptions:
  1336. const otherMain = PosixCDllMain
  1337. appcg(m, m.s[cfsProcs], otherMain, [])
  1338. elif m.config.target.targetOS == osStandalone:
  1339. const otherMain = StandaloneCMain
  1340. appcg(m, m.s[cfsProcs], otherMain, [])
  1341. else:
  1342. const otherMain = PosixCMain
  1343. appcg(m, m.s[cfsProcs], otherMain, [if m.hcrOn: "*" else: ""])
  1344. if m.config.cppCustomNamespace.len > 0:
  1345. m.s[cfsProcs].add openNamespaceNim(m.config.cppCustomNamespace)
  1346. proc registerModuleToMain(g: BModuleList; m: BModule) =
  1347. let
  1348. init = m.getInitName
  1349. datInit = m.getDatInitName
  1350. if m.hcrOn:
  1351. var hcrModuleMeta = "$nN_LIB_PRIVATE const char* hcr_module_list[] = {$n" % []
  1352. let systemModulePath = getModuleDllPath(m, g.modules[g.graph.config.m.systemFileIdx.int].module)
  1353. let mainModulePath = getModuleDllPath(m, m.module)
  1354. if sfMainModule in m.module.flags:
  1355. hcrModuleMeta.addf("\t$1,$n", [systemModulePath])
  1356. g.graph.importDeps.withValue(FileIndex(m.module.position), deps):
  1357. for curr in deps[]:
  1358. hcrModuleMeta.addf("\t$1,$n", [getModuleDllPath(m, g.modules[curr.int].module)])
  1359. hcrModuleMeta.addf("\t\"\"};$n", [])
  1360. hcrModuleMeta.addf("$nN_LIB_EXPORT N_NIMCALL(void**, HcrGetImportedModules)() { return (void**)hcr_module_list; }$n", [])
  1361. hcrModuleMeta.addf("$nN_LIB_EXPORT N_NIMCALL(char*, HcrGetSigHash)() { return \"$1\"; }$n$n",
  1362. [($sigHash(m.module)).rope])
  1363. if sfMainModule in m.module.flags:
  1364. g.mainModProcs.add(hcrModuleMeta)
  1365. g.mainModProcs.addf("static void* hcr_handle;$N", [])
  1366. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [init])
  1367. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [datInit])
  1368. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void*, N_NIMCALL_PTR(void*, getProcAddr)(void*, char*));$N", [m.getHcrInitName])
  1369. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void);$N", [])
  1370. g.mainModInit.addf("\t$1();$N", [init])
  1371. g.otherModsInit.addf("\thcrInit((void**)hcr_module_list, $1, $2, $3, hcr_handle, nimGetProcAddr);$n",
  1372. [mainModulePath, systemModulePath, datInit])
  1373. g.mainDatInit.addf("\t$1(hcr_handle, nimGetProcAddr);$N", [m.getHcrInitName])
  1374. g.mainDatInit.addf("\thcrAddModule($1);\n", [mainModulePath])
  1375. g.mainDatInit.addf("\tHcrCreateTypeInfos();$N", [])
  1376. # nasty nasty hack to get the command line functionality working with HCR
  1377. # register the 2 variables on behalf of the os module which might not even
  1378. # be loaded (in which case it will get collected but that is not a problem)
  1379. let osModulePath = ($systemModulePath).replace("stdlib_system", "stdlib_os").rope
  1380. g.mainDatInit.addf("\thcrAddModule($1);\n", [osModulePath])
  1381. g.mainDatInit.add("\tint* cmd_count;\n")
  1382. g.mainDatInit.add("\tchar*** cmd_line;\n")
  1383. g.mainDatInit.addf("\thcrRegisterGlobal($1, \"cmdCount\", sizeof(cmd_count), NULL, (void**)&cmd_count);$N", [osModulePath])
  1384. g.mainDatInit.addf("\thcrRegisterGlobal($1, \"cmdLine\", sizeof(cmd_line), NULL, (void**)&cmd_line);$N", [osModulePath])
  1385. g.mainDatInit.add("\t*cmd_count = cmdCount;\n")
  1386. g.mainDatInit.add("\t*cmd_line = cmdLine;\n")
  1387. else:
  1388. m.s[cfsInitProc].add(hcrModuleMeta)
  1389. return
  1390. if m.s[cfsDatInitProc].len > 0:
  1391. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [datInit])
  1392. g.mainDatInit.addf("\t$1();$N", [datInit])
  1393. # Initialization of TLS and GC should be done in between
  1394. # systemDatInit and systemInit calls if any
  1395. if sfSystemModule in m.module.flags:
  1396. if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone:
  1397. g.mainDatInit.add(ropecg(m, "\t#initThreadVarsEmulation();$N", []))
  1398. if m.config.target.targetOS != osStandalone and m.config.selectedGC notin {gcNone, gcArc, gcOrc}:
  1399. g.mainDatInit.add(ropecg(m, "\t#initStackBottomWith((void *)&inner);$N", []))
  1400. if m.s[cfsInitProc].len > 0:
  1401. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [init])
  1402. let initCall = "\t$1();$N" % [init]
  1403. if sfMainModule in m.module.flags:
  1404. g.mainModInit.add(initCall)
  1405. elif sfSystemModule in m.module.flags:
  1406. g.mainDatInit.add(initCall) # systemInit must called right after systemDatInit if any
  1407. else:
  1408. g.otherModsInit.add(initCall)
  1409. proc genDatInitCode(m: BModule) =
  1410. ## this function is called in cgenWriteModules after all modules are closed,
  1411. ## it means raising dependency on the symbols is too late as it will not propagate
  1412. ## into other modules, only simple rope manipulations are allowed
  1413. var moduleDatInitRequired = m.hcrOn
  1414. var prc = "$1 N_NIMCALL(void, $2)(void) {$N" %
  1415. [rope(if m.hcrOn: "N_LIB_EXPORT" else: "N_LIB_PRIVATE"), getDatInitName(m)]
  1416. # we don't want to break into such init code - could happen if a line
  1417. # directive from a function written by the user spills after itself
  1418. genCLineDir(prc, "generated_not_to_break_here", 999999, m.config)
  1419. for i in cfsTypeInit1..cfsDynLibInit:
  1420. if m.s[i].len != 0:
  1421. moduleDatInitRequired = true
  1422. prc.add(genSectionStart(i, m.config))
  1423. prc.add(m.s[i])
  1424. prc.add(genSectionEnd(i, m.config))
  1425. prc.addf("}$N$N", [])
  1426. if moduleDatInitRequired:
  1427. m.s[cfsDatInitProc].add(prc)
  1428. # Very similar to the contents of symInDynamicLib - basically only the
  1429. # things needed for the hot code reloading runtime procs to be loaded
  1430. proc hcrGetProcLoadCode(m: BModule, sym, prefix, handle, getProcFunc: string): Rope =
  1431. let prc = magicsys.getCompilerProc(m.g.graph, sym)
  1432. assert prc != nil
  1433. fillProcLoc(m, prc.ast[namePos])
  1434. var extname = prefix & sym
  1435. var tmp = mangleDynLibProc(prc)
  1436. prc.loc.r = tmp
  1437. prc.typ.sym = nil
  1438. if not containsOrIncl(m.declaredThings, prc.id):
  1439. m.s[cfsVars].addf("static $2 $1;$n", [prc.loc.r, getTypeDesc(m, prc.loc.t, skVar)])
  1440. result = "\t$1 = ($2) $3($4, $5);$n" %
  1441. [tmp, getTypeDesc(m, prc.typ, skVar), getProcFunc.rope, handle.rope, makeCString(prefix & sym)]
  1442. proc genInitCode(m: BModule) =
  1443. ## this function is called in cgenWriteModules after all modules are closed,
  1444. ## it means raising dependency on the symbols is too late as it will not propagate
  1445. ## into other modules, only simple rope manipulations are allowed
  1446. var moduleInitRequired = m.hcrOn
  1447. let initname = getInitName(m)
  1448. var prc = "$1 N_NIMCALL(void, $2)(void) {$N" %
  1449. [rope(if m.hcrOn: "N_LIB_EXPORT" else: "N_LIB_PRIVATE"), initname]
  1450. # we don't want to break into such init code - could happen if a line
  1451. # directive from a function written by the user spills after itself
  1452. genCLineDir(prc, "generated_not_to_break_here", 999999, m.config)
  1453. if m.typeNodes > 0:
  1454. if m.hcrOn:
  1455. appcg(m, m.s[cfsTypeInit1], "\t#TNimNode* $1;$N", [m.typeNodesName])
  1456. appcg(m, m.s[cfsTypeInit1], "\thcrRegisterGlobal($3, \"$1_$2\", sizeof(TNimNode) * $2, NULL, (void**)&$1);$N",
  1457. [m.typeNodesName, m.typeNodes, getModuleDllPath(m, m.module)])
  1458. else:
  1459. appcg(m, m.s[cfsTypeInit1], "static #TNimNode $1[$2];$n",
  1460. [m.typeNodesName, m.typeNodes])
  1461. if m.nimTypes > 0:
  1462. appcg(m, m.s[cfsTypeInit1], "static #TNimType $1[$2];$n",
  1463. [m.nimTypesName, m.nimTypes])
  1464. if m.hcrOn:
  1465. prc.addf("\tint* nim_hcr_dummy_ = 0;$n" &
  1466. "\tNIM_BOOL nim_hcr_do_init_ = " &
  1467. "hcrRegisterGlobal($1, \"module_initialized_\", 1, NULL, (void**)&nim_hcr_dummy_);$n",
  1468. [getModuleDllPath(m, m.module)])
  1469. template writeSection(thing: untyped, section: TCProcSection, addHcrGuards = false) =
  1470. if m.thing.s(section).len > 0:
  1471. moduleInitRequired = true
  1472. if addHcrGuards: prc.add("\tif (nim_hcr_do_init_) {\n\n")
  1473. prc.add(genSectionStart(section, m.config))
  1474. prc.add(m.thing.s(section))
  1475. prc.add(genSectionEnd(section, m.config))
  1476. if addHcrGuards: prc.add("\n\t} // nim_hcr_do_init_\n")
  1477. if m.preInitProc.s(cpsInit).len > 0 or m.preInitProc.s(cpsStmts).len > 0:
  1478. # Give this small function its own scope
  1479. prc.addf("{$N", [])
  1480. # Keep a bogus frame in case the code needs one
  1481. prc.add(~"\tTFrame FR_; FR_.len = 0;$N")
  1482. writeSection(preInitProc, cpsLocals)
  1483. writeSection(preInitProc, cpsInit, m.hcrOn)
  1484. writeSection(preInitProc, cpsStmts)
  1485. prc.addf("}$N", [])
  1486. when false:
  1487. m.initProc.blocks[0].sections[cpsLocals].add m.preInitProc.s(cpsLocals)
  1488. m.initProc.blocks[0].sections[cpsInit].prepend m.preInitProc.s(cpsInit)
  1489. m.initProc.blocks[0].sections[cpsStmts].prepend m.preInitProc.s(cpsStmts)
  1490. # add new scope for following code, because old vcc compiler need variable
  1491. # be defined at the top of the block
  1492. prc.addf("{$N", [])
  1493. writeSection(initProc, cpsLocals)
  1494. if m.initProc.s(cpsInit).len > 0 or m.initProc.s(cpsStmts).len > 0:
  1495. moduleInitRequired = true
  1496. if optStackTrace in m.initProc.options and frameDeclared notin m.flags:
  1497. # BUT: the generated init code might depend on a current frame, so
  1498. # declare it nevertheless:
  1499. incl m.flags, frameDeclared
  1500. if preventStackTrace notin m.flags:
  1501. var procname = makeCString(m.module.name.s)
  1502. prc.add(initFrame(m.initProc, procname, quotedFilename(m.config, m.module.info)))
  1503. else:
  1504. prc.add(~"\tTFrame FR_; FR_.len = 0;$N")
  1505. writeSection(initProc, cpsInit, m.hcrOn)
  1506. writeSection(initProc, cpsStmts)
  1507. if beforeRetNeeded in m.initProc.flags:
  1508. prc.add(~"\tBeforeRet_: ;$n")
  1509. if sfMainModule in m.module.flags and m.config.exc == excGoto:
  1510. if getCompilerProc(m.g.graph, "nimTestErrorFlag") != nil:
  1511. m.appcg(prc, "\t#nimTestErrorFlag();$n", [])
  1512. if optStackTrace in m.initProc.options and preventStackTrace notin m.flags:
  1513. prc.add(deinitFrame(m.initProc))
  1514. prc.addf("}$N", [])
  1515. prc.addf("}$N$N", [])
  1516. # we cannot simply add the init proc to ``m.s[cfsProcs]`` anymore because
  1517. # that would lead to a *nesting* of merge sections which the merger does
  1518. # not support. So we add it to another special section: ``cfsInitProc``
  1519. if m.hcrOn:
  1520. var procsToLoad = @["hcrRegisterProc", "hcrGetProc", "hcrRegisterGlobal", "hcrGetGlobal"]
  1521. m.s[cfsInitProc].addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void* handle, N_NIMCALL_PTR(void*, getProcAddr)(void*, char*)) {$N", [getHcrInitName(m)])
  1522. if sfMainModule in m.module.flags:
  1523. # additional procs to load
  1524. procsToLoad.add("hcrInit")
  1525. procsToLoad.add("hcrAddModule")
  1526. # load procs
  1527. for curr in procsToLoad:
  1528. m.s[cfsInitProc].add(hcrGetProcLoadCode(m, curr, "", "handle", "getProcAddr"))
  1529. m.s[cfsInitProc].addf("}$N$N", [])
  1530. for i, el in pairs(m.extensionLoaders):
  1531. if el != nil:
  1532. let ex = "NIM_EXTERNC N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N" %
  1533. [(i.ord - '0'.ord).rope, el]
  1534. moduleInitRequired = true
  1535. prc.add(ex)
  1536. if moduleInitRequired or sfMainModule in m.module.flags:
  1537. m.s[cfsInitProc].add(prc)
  1538. genDatInitCode(m)
  1539. if m.hcrOn:
  1540. m.s[cfsInitProc].addf("N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void) {$N", [])
  1541. m.s[cfsInitProc].add(m.hcrCreateTypeInfosProc)
  1542. m.s[cfsInitProc].addf("}$N$N", [])
  1543. registerModuleToMain(m.g, m)
  1544. proc genModule(m: BModule, cfile: Cfile): Rope =
  1545. var moduleIsEmpty = true
  1546. result = getFileHeader(m.config, cfile)
  1547. result.add(genMergeInfo(m))
  1548. generateThreadLocalStorage(m)
  1549. generateHeaders(m)
  1550. result.add(genSectionStart(cfsHeaders, m.config))
  1551. result.add(m.s[cfsHeaders])
  1552. if m.config.cppCustomNamespace.len > 0:
  1553. result.add openNamespaceNim(m.config.cppCustomNamespace)
  1554. result.add(genSectionEnd(cfsHeaders, m.config))
  1555. result.add(genSectionStart(cfsFrameDefines, m.config))
  1556. if m.s[cfsFrameDefines].len > 0:
  1557. result.add(m.s[cfsFrameDefines])
  1558. else:
  1559. result.add("#define nimfr_(x, y)\n#define nimln_(x, y)\n")
  1560. result.add(genSectionEnd(cfsFrameDefines, m.config))
  1561. for i in cfsForwardTypes..cfsProcs:
  1562. if m.s[i].len > 0:
  1563. moduleIsEmpty = false
  1564. result.add(genSectionStart(i, m.config))
  1565. result.add(m.s[i])
  1566. result.add(genSectionEnd(i, m.config))
  1567. if m.s[cfsInitProc].len > 0:
  1568. moduleIsEmpty = false
  1569. result.add(m.s[cfsInitProc])
  1570. if m.s[cfsDatInitProc].len > 0 or m.hcrOn:
  1571. moduleIsEmpty = false
  1572. result.add(m.s[cfsDatInitProc])
  1573. if m.config.cppCustomNamespace.len > 0:
  1574. result.add closeNamespaceNim()
  1575. if moduleIsEmpty:
  1576. result = nil
  1577. proc initProcOptions(m: BModule): TOptions =
  1578. let opts = m.config.options
  1579. if sfSystemModule in m.module.flags: opts-{optStackTrace} else: opts
  1580. proc rawNewModule(g: BModuleList; module: PSym, filename: AbsoluteFile): BModule =
  1581. new(result)
  1582. result.g = g
  1583. result.tmpBase = rope("TM" & $hashOwner(module) & "_")
  1584. result.headerFiles = @[]
  1585. result.declaredThings = initIntSet()
  1586. result.declaredProtos = initIntSet()
  1587. result.cfilename = filename
  1588. result.filename = filename
  1589. result.typeCache = initTable[SigHash, Rope]()
  1590. result.forwTypeCache = initTable[SigHash, Rope]()
  1591. result.module = module
  1592. result.typeInfoMarker = initTable[SigHash, Rope]()
  1593. result.sigConflicts = initCountTable[SigHash]()
  1594. result.initProc = newProc(nil, result)
  1595. result.initProc.options = initProcOptions(result)
  1596. result.preInitProc = newProc(nil, result)
  1597. result.preInitProc.flags.incl nimErrorFlagDisabled
  1598. result.preInitProc.labels = 100_000 # little hack so that unique temporaries are generated
  1599. initNodeTable(result.dataCache)
  1600. result.typeStack = @[]
  1601. result.typeNodesName = getTempName(result)
  1602. result.nimTypesName = getTempName(result)
  1603. # no line tracing for the init sections of the system module so that we
  1604. # don't generate a TFrame which can confuse the stack bottom initialization:
  1605. if sfSystemModule in module.flags:
  1606. incl result.flags, preventStackTrace
  1607. excl(result.preInitProc.options, optStackTrace)
  1608. let ndiName = if optCDebug in g.config.globalOptions: changeFileExt(completeCfilePath(g.config, filename), "ndi")
  1609. else: AbsoluteFile""
  1610. open(result.ndi, ndiName, g.config)
  1611. proc rawNewModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule =
  1612. result = rawNewModule(g, module, AbsoluteFile toFullPath(conf, module.position.FileIndex))
  1613. proc newModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule =
  1614. # we should create only one cgen module for each module sym
  1615. result = rawNewModule(g, module, conf)
  1616. if module.position >= g.modules.len:
  1617. setLen(g.modules, module.position + 1)
  1618. #growCache g.modules, module.position
  1619. g.modules[module.position] = result
  1620. template injectG() {.dirty.} =
  1621. if graph.backend == nil:
  1622. graph.backend = newModuleList(graph)
  1623. let g = BModuleList(graph.backend)
  1624. when not defined(nimHasSinkInference):
  1625. {.pragma: nosinks.}
  1626. proc myOpen(graph: ModuleGraph; module: PSym): PPassContext {.nosinks.} =
  1627. injectG()
  1628. result = newModule(g, module, graph.config)
  1629. if optGenIndex in graph.config.globalOptions and g.generatedHeader == nil:
  1630. let f = if graph.config.headerFile.len > 0: AbsoluteFile graph.config.headerFile
  1631. else: graph.config.projectFull
  1632. g.generatedHeader = rawNewModule(g, module,
  1633. changeFileExt(completeCfilePath(graph.config, f), hExt))
  1634. incl g.generatedHeader.flags, isHeaderFile
  1635. proc writeHeader(m: BModule) =
  1636. var result = ("/* Generated by Nim Compiler v$1 */$N" &
  1637. "/* (c) 2017 Andreas Rumpf */$N" &
  1638. "/* The generated code is subject to the original license. */$N") %
  1639. [rope(VersionAsString)]
  1640. var guard = "__$1__" % [m.filename.splitFile.name.rope]
  1641. result.addf("#ifndef $1$n#define $1$n", [guard])
  1642. addNimDefines(result, m.config)
  1643. generateHeaders(m)
  1644. generateThreadLocalStorage(m)
  1645. for i in cfsHeaders..cfsProcs:
  1646. result.add(genSectionStart(i, m.config))
  1647. result.add(m.s[i])
  1648. result.add(genSectionEnd(i, m.config))
  1649. if m.config.cppCustomNamespace.len > 0 and i == cfsHeaders: result.add openNamespaceNim(m.config.cppCustomNamespace)
  1650. result.add(m.s[cfsInitProc])
  1651. if optGenDynLib in m.config.globalOptions:
  1652. result.add("N_LIB_IMPORT ")
  1653. result.addf("N_CDECL(void, NimMain)(void);$n", [])
  1654. if m.config.cppCustomNamespace.len > 0: result.add closeNamespaceNim()
  1655. result.addf("#endif /* $1 */$n", [guard])
  1656. if not writeRope(result, m.filename):
  1657. rawMessage(m.config, errCannotOpenFile, m.filename.string)
  1658. proc getCFile(m: BModule): AbsoluteFile =
  1659. let ext =
  1660. if m.compileToCpp: ".nim.cpp"
  1661. elif m.config.backend == backendObjc or sfCompileToObjc in m.module.flags: ".nim.m"
  1662. else: ".nim.c"
  1663. result = changeFileExt(completeCfilePath(m.config, withPackageName(m.config, m.cfilename)), ext)
  1664. when false:
  1665. proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
  1666. injectG()
  1667. var m = newModule(g, module, graph.config)
  1668. readMergeInfo(getCFile(m), m)
  1669. result = m
  1670. proc addHcrInitGuards(p: BProc, n: PNode, inInitGuard: var bool) =
  1671. if n.kind == nkStmtList:
  1672. for child in n:
  1673. addHcrInitGuards(p, child, inInitGuard)
  1674. else:
  1675. let stmtShouldExecute = n.kind in {nkVarSection, nkLetSection} or
  1676. nfExecuteOnReload in n.flags
  1677. if inInitGuard:
  1678. if stmtShouldExecute:
  1679. endBlock(p)
  1680. inInitGuard = false
  1681. else:
  1682. if not stmtShouldExecute:
  1683. line(p, cpsStmts, "if (nim_hcr_do_init_)\n")
  1684. startBlock(p)
  1685. inInitGuard = true
  1686. genStmts(p, n)
  1687. proc myProcess(b: PPassContext, n: PNode): PNode =
  1688. result = n
  1689. if b == nil: return
  1690. var m = BModule(b)
  1691. if passes.skipCodegen(m.config, n) or
  1692. not moduleHasChanged(m.g.graph, m.module):
  1693. return
  1694. m.initProc.options = initProcOptions(m)
  1695. #softRnl = if optLineDir in m.config.options: noRnl else: rnl
  1696. # XXX replicate this logic!
  1697. var transformedN = transformStmt(m.g.graph, m.module, n)
  1698. if sfInjectDestructors in m.module.flags:
  1699. transformedN = injectDestructorCalls(m.g.graph, m.module, transformedN)
  1700. if m.hcrOn:
  1701. addHcrInitGuards(m.initProc, transformedN, m.inHcrInitGuard)
  1702. else:
  1703. genProcBody(m.initProc, transformedN)
  1704. proc shouldRecompile(m: BModule; code: Rope, cfile: Cfile): bool =
  1705. if optForceFullMake notin m.config.globalOptions:
  1706. if not moduleHasChanged(m.g.graph, m.module):
  1707. result = false
  1708. elif not equalsFile(code, cfile.cname):
  1709. when false:
  1710. #m.config.symbolFiles == readOnlySf: #isDefined(m.config, "nimdiff"):
  1711. if fileExists(cfile.cname):
  1712. copyFile(cfile.cname.string, cfile.cname.string & ".backup")
  1713. echo "diff ", cfile.cname.string, ".backup ", cfile.cname.string
  1714. else:
  1715. echo "new file ", cfile.cname.string
  1716. if not writeRope(code, cfile.cname):
  1717. rawMessage(m.config, errCannotOpenFile, cfile.cname.string)
  1718. result = true
  1719. elif fileExists(cfile.obj) and os.fileNewer(cfile.obj.string, cfile.cname.string):
  1720. result = false
  1721. else:
  1722. result = true
  1723. else:
  1724. if not writeRope(code, cfile.cname):
  1725. rawMessage(m.config, errCannotOpenFile, cfile.cname.string)
  1726. result = true
  1727. # We need 2 different logics here: pending modules (including
  1728. # 'nim__dat') may require file merging for the combination of dead code
  1729. # elimination and incremental compilation! Non pending modules need no
  1730. # such logic and in fact the logic hurts for the main module at least;
  1731. # it would generate multiple 'main' procs, for instance.
  1732. proc writeModule(m: BModule, pending: bool) =
  1733. template onExit() = close(m.ndi, m.config)
  1734. let cfile = getCFile(m)
  1735. if true or optForceFullMake in m.config.globalOptions:
  1736. if moduleHasChanged(m.g.graph, m.module):
  1737. genInitCode(m)
  1738. finishTypeDescriptions(m)
  1739. if sfMainModule in m.module.flags:
  1740. # generate main file:
  1741. genMainProc(m)
  1742. m.s[cfsProcHeaders].add(m.g.mainModProcs)
  1743. generateThreadVarsSize(m)
  1744. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1745. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1746. var code = genModule(m, cf)
  1747. if code != nil or m.config.symbolFiles != disabledSf:
  1748. when hasTinyCBackend:
  1749. if m.config.cmd == cmdRun:
  1750. tccgen.compileCCode($code, m.config)
  1751. onExit()
  1752. return
  1753. if not shouldRecompile(m, code, cf): cf.flags = {CfileFlag.Cached}
  1754. addFileToCompile(m.config, cf)
  1755. elif pending and mergeRequired(m) and sfMainModule notin m.module.flags:
  1756. let cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1757. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1758. mergeFiles(cfile, m)
  1759. genInitCode(m)
  1760. finishTypeDescriptions(m)
  1761. var code = genModule(m, cf)
  1762. if code != nil:
  1763. if not writeRope(code, cfile):
  1764. rawMessage(m.config, errCannotOpenFile, cfile.string)
  1765. addFileToCompile(m.config, cf)
  1766. else:
  1767. # Consider: first compilation compiles ``system.nim`` and produces
  1768. # ``system.c`` but then compilation fails due to an error. This means
  1769. # that ``system.o`` is missing, so we need to call the C compiler for it:
  1770. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1771. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1772. if not fileExists(cf.obj): cf.flags = {CfileFlag.Cached}
  1773. addFileToCompile(m.config, cf)
  1774. onExit()
  1775. proc updateCachedModule(m: BModule) =
  1776. let cfile = getCFile(m)
  1777. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1778. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1779. if mergeRequired(m) and sfMainModule notin m.module.flags:
  1780. mergeFiles(cfile, m)
  1781. genInitCode(m)
  1782. finishTypeDescriptions(m)
  1783. var code = genModule(m, cf)
  1784. if code != nil:
  1785. if not writeRope(code, cfile):
  1786. rawMessage(m.config, errCannotOpenFile, cfile.string)
  1787. addFileToCompile(m.config, cf)
  1788. else:
  1789. if sfMainModule notin m.module.flags:
  1790. genMainProc(m)
  1791. cf.flags = {CfileFlag.Cached}
  1792. addFileToCompile(m.config, cf)
  1793. proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
  1794. result = n
  1795. if b == nil: return
  1796. var m = BModule(b)
  1797. if sfMainModule in m.module.flags:
  1798. # phase ordering problem here: We need to announce this
  1799. # dependency to 'nimTestErrorFlag' before system.c has been written to disk.
  1800. if m.config.exc == excGoto and getCompilerProc(graph, "nimTestErrorFlag") != nil:
  1801. discard cgsym(m, "nimTestErrorFlag")
  1802. if {optGenStaticLib, optGenDynLib} * m.config.globalOptions == {}:
  1803. for i in countdown(high(graph.globalDestructors), 0):
  1804. n.add graph.globalDestructors[i]
  1805. if passes.skipCodegen(m.config, n): return
  1806. if moduleHasChanged(graph, m.module):
  1807. # if the module is cached, we don't regenerate the main proc
  1808. # nor the dispatchers? But if the dispatchers changed?
  1809. # XXX emit the dispatchers into its own .c file?
  1810. if n != nil:
  1811. m.initProc.options = initProcOptions(m)
  1812. genProcBody(m.initProc, n)
  1813. if m.hcrOn:
  1814. # make sure this is pulled in (meaning hcrGetGlobal() is called for it during init)
  1815. discard cgsym(m, "programResult")
  1816. if m.inHcrInitGuard:
  1817. endBlock(m.initProc)
  1818. if sfMainModule in m.module.flags:
  1819. if m.hcrOn:
  1820. # pull ("define" since they are inline when HCR is on) these functions in the main file
  1821. # so it can load the HCR runtime and later pass the library handle to the HCR runtime which
  1822. # will in turn pass it to the other modules it initializes so they can initialize the
  1823. # register/get procs so they don't have to have the definitions of these functions as well
  1824. discard cgsym(m, "nimLoadLibrary")
  1825. discard cgsym(m, "nimLoadLibraryError")
  1826. discard cgsym(m, "nimGetProcAddr")
  1827. discard cgsym(m, "procAddrError")
  1828. discard cgsym(m, "rawWrite")
  1829. # raise dependencies on behalf of genMainProc
  1830. if m.config.target.targetOS != osStandalone and m.config.selectedGC != gcNone:
  1831. discard cgsym(m, "initStackBottomWith")
  1832. if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone:
  1833. discard cgsym(m, "initThreadVarsEmulation")
  1834. if m.g.forwardedProcs.len == 0:
  1835. incl m.flags, objHasKidsValid
  1836. let disp = generateMethodDispatchers(graph)
  1837. for x in disp: genProcAux(m, x.sym)
  1838. let mm = m
  1839. m.g.modulesClosed.add mm
  1840. proc genForwardedProcs(g: BModuleList) =
  1841. # Forward declared proc:s lack bodies when first encountered, so they're given
  1842. # a second pass here
  1843. # Note: ``genProcNoForward`` may add to ``forwardedProcs``
  1844. while g.forwardedProcs.len > 0:
  1845. let
  1846. prc = g.forwardedProcs.pop()
  1847. ms = getModule(prc)
  1848. m = g.modules[ms.position]
  1849. if sfForward in prc.flags:
  1850. internalError(m.config, prc.info, "still forwarded: " & prc.name.s)
  1851. genProcNoForward(m, prc)
  1852. proc cgenWriteModules*(backend: RootRef, config: ConfigRef) =
  1853. let g = BModuleList(backend)
  1854. g.config = config
  1855. # we need to process the transitive closure because recursive module
  1856. # deps are allowed (and the system module is processed in the wrong
  1857. # order anyway)
  1858. genForwardedProcs(g)
  1859. for m in cgenModules(g):
  1860. m.writeModule(pending=true)
  1861. writeMapping(config, g.mapping)
  1862. if g.generatedHeader != nil: writeHeader(g.generatedHeader)
  1863. const cgenPass* = makePass(myOpen, myProcess, myClose)