cgen.nim 82 KB

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