ccgexprs.nim 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # included from cgen.nim
  10. # -------------------------- constant expressions ------------------------
  11. proc int64Literal(i: BiggestInt): Rope =
  12. if i > low(int64):
  13. result = "IL64($1)" % [rope(i)]
  14. else:
  15. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  16. proc uint64Literal(i: uint64): Rope = rope($i & "ULL")
  17. proc intLiteral(i: BiggestInt): Rope =
  18. if i > low(int32) and i <= high(int32):
  19. result = rope(i)
  20. elif i == low(int32):
  21. # Nim has the same bug for the same reasons :-)
  22. result = ~"(-2147483647 -1)"
  23. elif i > low(int64):
  24. result = "IL64($1)" % [rope(i)]
  25. else:
  26. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  27. proc intLiteral(i: Int128): Rope =
  28. intLiteral(toInt64(i))
  29. proc genLiteral(p: BProc, n: PNode, ty: PType): Rope =
  30. case n.kind
  31. of nkCharLit..nkUInt64Lit:
  32. var k: TTypeKind
  33. if ty != nil:
  34. k = skipTypes(ty, abstractVarRange).kind
  35. else:
  36. case n.kind
  37. of nkCharLit: k = tyChar
  38. of nkUInt64Lit: k = tyUInt64
  39. of nkInt64Lit: k = tyInt64
  40. else: k = tyNil # don't go into the case variant that uses 'ty'
  41. case k
  42. of tyChar, tyNil:
  43. result = intLiteral(n.intVal)
  44. of tyBool:
  45. if n.intVal != 0: result = ~"NIM_TRUE"
  46. else: result = ~"NIM_FALSE"
  47. of tyInt64: result = int64Literal(n.intVal)
  48. of tyUInt64: result = uint64Literal(uint64(n.intVal))
  49. else:
  50. result = "(($1) $2)" % [getTypeDesc(p.module,
  51. ty), intLiteral(n.intVal)]
  52. of nkNilLit:
  53. let k = if ty == nil: tyPointer else: skipTypes(ty, abstractVarRange).kind
  54. if k == tyProc and skipTypes(ty, abstractVarRange).callConv == ccClosure:
  55. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  56. result = p.module.tmpBase & rope(id)
  57. if id == p.module.labels:
  58. # not found in cache:
  59. inc(p.module.labels)
  60. addf(p.module.s[cfsData],
  61. "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n",
  62. [getTypeDesc(p.module, ty), result])
  63. else:
  64. result = rope("NIM_NIL")
  65. of nkStrLit..nkTripleStrLit:
  66. let k = if ty == nil: tyString
  67. else: skipTypes(ty, abstractVarRange + {tyStatic, tyUserTypeClass, tyUserTypeClassInst}).kind
  68. case k
  69. of tyNil:
  70. result = genNilStringLiteral(p.module, n.info)
  71. of tyString:
  72. # with the new semantics for 'nil' strings, we can map "" to nil and
  73. # save tons of allocations:
  74. if n.strVal.len == 0 and optNilSeqs notin p.options and
  75. p.config.selectedGC != gcDestructors:
  76. result = genNilStringLiteral(p.module, n.info)
  77. else:
  78. result = genStringLiteral(p.module, n)
  79. else:
  80. result = makeCString(n.strVal)
  81. of nkFloatLit, nkFloat64Lit:
  82. result = rope(n.floatVal.toStrMaxPrecision)
  83. of nkFloat32Lit:
  84. result = rope(n.floatVal.toStrMaxPrecision("f"))
  85. else:
  86. internalError(p.config, n.info, "genLiteral(" & $n.kind & ')')
  87. result = nil
  88. proc genLiteral(p: BProc, n: PNode): Rope =
  89. result = genLiteral(p, n, n.typ)
  90. proc bitSetToWord(s: TBitSet, size: int): BiggestUInt =
  91. result = 0
  92. for j in 0 ..< size:
  93. if j < len(s): result = result or (BiggestUInt(s[j]) shl (j * 8))
  94. proc genRawSetData(cs: TBitSet, size: int): Rope =
  95. if size > 8:
  96. var res = "{\n"
  97. for i in 0 ..< size:
  98. res.add "0x"
  99. res.add "0123456789abcdef"[cs[i] div 16]
  100. res.add "0123456789abcdef"[cs[i] mod 16]
  101. if i < size - 1:
  102. # not last iteration
  103. if i mod 8 == 7:
  104. res.add ",\n"
  105. else:
  106. res.add ", "
  107. else:
  108. res.add "}\n"
  109. result = rope(res)
  110. else:
  111. result = intLiteral(cast[BiggestInt](bitSetToWord(cs, size)))
  112. proc genSetNode(p: BProc, n: PNode): Rope =
  113. var cs: TBitSet
  114. var size = int(getSize(p.config, n.typ))
  115. toBitSet(p.config, n, cs)
  116. if size > 8:
  117. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  118. result = p.module.tmpBase & rope(id)
  119. if id == p.module.labels:
  120. # not found in cache:
  121. inc(p.module.labels)
  122. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  123. [getTypeDesc(p.module, n.typ), result, genRawSetData(cs, size)])
  124. else:
  125. result = genRawSetData(cs, size)
  126. proc getStorageLoc(n: PNode): TStorageLoc =
  127. case n.kind
  128. of nkSym:
  129. case n.sym.kind
  130. of skParam, skTemp:
  131. result = OnStack
  132. of skVar, skForVar, skResult, skLet:
  133. if sfGlobal in n.sym.flags: result = OnHeap
  134. else: result = OnStack
  135. of skConst:
  136. if sfGlobal in n.sym.flags: result = OnHeap
  137. else: result = OnUnknown
  138. else: result = OnUnknown
  139. of nkDerefExpr, nkHiddenDeref:
  140. case n.sons[0].typ.kind
  141. of tyVar, tyLent: result = OnUnknown
  142. of tyPtr: result = OnStack
  143. of tyRef: result = OnHeap
  144. else: doAssert(false, "getStorageLoc")
  145. of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv:
  146. result = getStorageLoc(n.sons[0])
  147. else: result = OnUnknown
  148. proc canMove(p: BProc, n: PNode; dest: TLoc): bool =
  149. # for now we're conservative here:
  150. if n.kind == nkBracket:
  151. # This needs to be kept consistent with 'const' seq code
  152. # generation!
  153. if not isDeepConstExpr(n) or n.len == 0:
  154. if skipTypes(n.typ, abstractVarRange).kind == tySequence:
  155. return true
  156. elif optNilSeqs notin p.options and
  157. n.kind in nkStrKinds and n.strVal.len == 0:
  158. # Empty strings are codegen'd as NIM_NIL so it's just a pointer copy
  159. return true
  160. result = n.kind in nkCallKinds
  161. #if not result and dest.k == locTemp:
  162. # return true
  163. #if result:
  164. # echo n.info, " optimized ", n
  165. # result = false
  166. proc genRefAssign(p: BProc, dest, src: TLoc) =
  167. if (dest.storage == OnStack and p.config.selectedGC != gcGo) or not usesWriteBarrier(p.config):
  168. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  169. elif dest.storage == OnHeap:
  170. linefmt(p, cpsStmts, "#asgnRef((void**) $1, $2);$n",
  171. [addrLoc(p.config, dest), rdLoc(src)])
  172. else:
  173. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  174. [addrLoc(p.config, dest), rdLoc(src)])
  175. proc asgnComplexity(n: PNode): int =
  176. if n != nil:
  177. case n.kind
  178. of nkSym: result = 1
  179. of nkRecCase:
  180. # 'case objects' are too difficult to inline their assignment operation:
  181. result = 100
  182. of nkRecList:
  183. for t in items(n):
  184. result += asgnComplexity(t)
  185. else: discard
  186. proc optAsgnLoc(a: TLoc, t: PType, field: Rope): TLoc =
  187. assert field != nil
  188. result.k = locField
  189. result.storage = a.storage
  190. result.lode = lodeTyp t
  191. result.r = rdLoc(a) & "." & field
  192. proc genOptAsgnTuple(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  193. let newflags =
  194. if src.storage == OnStatic:
  195. flags + {needToCopy}
  196. elif tfShallow in dest.t.flags:
  197. flags - {needToCopy}
  198. else:
  199. flags
  200. let t = skipTypes(dest.t, abstractInst).getUniqueType()
  201. for i in 0 ..< t.len:
  202. let t = t.sons[i]
  203. let field = "Field$1" % [i.rope]
  204. genAssignment(p, optAsgnLoc(dest, t, field),
  205. optAsgnLoc(src, t, field), newflags)
  206. proc genOptAsgnObject(p: BProc, dest, src: TLoc, flags: TAssignmentFlags,
  207. t: PNode, typ: PType) =
  208. if t == nil: return
  209. let newflags =
  210. if src.storage == OnStatic:
  211. flags + {needToCopy}
  212. elif tfShallow in dest.t.flags:
  213. flags - {needToCopy}
  214. else:
  215. flags
  216. case t.kind
  217. of nkSym:
  218. let field = t.sym
  219. if field.loc.r == nil: fillObjectFields(p.module, typ)
  220. genAssignment(p, optAsgnLoc(dest, field.typ, field.loc.r),
  221. optAsgnLoc(src, field.typ, field.loc.r), newflags)
  222. of nkRecList:
  223. for child in items(t): genOptAsgnObject(p, dest, src, newflags, child, typ)
  224. else: discard
  225. proc genGenericAsgn(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  226. # Consider:
  227. # type TMyFastString {.shallow.} = string
  228. # Due to the implementation of pragmas this would end up to set the
  229. # tfShallow flag for the built-in string type too! So we check only
  230. # here for this flag, where it is reasonably safe to do so
  231. # (for objects, etc.):
  232. if p.config.selectedGC == gcDestructors:
  233. linefmt(p, cpsStmts,
  234. "$1 = $2;$n",
  235. [rdLoc(dest), rdLoc(src)])
  236. elif needToCopy notin flags or
  237. tfShallow in skipTypes(dest.t, abstractVarRange).flags:
  238. if (dest.storage == OnStack and p.config.selectedGC != gcGo) or not usesWriteBarrier(p.config):
  239. linefmt(p, cpsStmts,
  240. "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  241. [addrLoc(p.config, dest), addrLoc(p.config, src), rdLoc(dest)])
  242. else:
  243. linefmt(p, cpsStmts, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n",
  244. [addrLoc(p.config, dest), addrLoc(p.config, src), genTypeInfo(p.module, dest.t, dest.lode.info)])
  245. else:
  246. linefmt(p, cpsStmts, "#genericAssign((void*)$1, (void*)$2, $3);$n",
  247. [addrLoc(p.config, dest), addrLoc(p.config, src), genTypeInfo(p.module, dest.t, dest.lode.info)])
  248. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  249. # This function replaces all other methods for generating
  250. # the assignment operation in C.
  251. if src.t != nil and src.t.kind == tyPtr:
  252. # little HACK to support the new 'var T' as return type:
  253. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  254. return
  255. let ty = skipTypes(dest.t, abstractRange + tyUserTypeClasses + {tyStatic})
  256. case ty.kind
  257. of tyRef:
  258. genRefAssign(p, dest, src)
  259. of tySequence:
  260. if p.config.selectedGC == gcDestructors:
  261. genGenericAsgn(p, dest, src, flags)
  262. elif (needToCopy notin flags and src.storage != OnStatic) or canMove(p, src.lode, dest):
  263. genRefAssign(p, dest, src)
  264. else:
  265. linefmt(p, cpsStmts, "#genericSeqAssign($1, $2, $3);$n",
  266. [addrLoc(p.config, dest), rdLoc(src),
  267. genTypeInfo(p.module, dest.t, dest.lode.info)])
  268. of tyString:
  269. if p.config.selectedGC == gcDestructors:
  270. genGenericAsgn(p, dest, src, flags)
  271. elif (needToCopy notin flags and src.storage != OnStatic) or canMove(p, src.lode, dest):
  272. genRefAssign(p, dest, src)
  273. else:
  274. if (dest.storage == OnStack and p.config.selectedGC != gcGo) or not usesWriteBarrier(p.config):
  275. linefmt(p, cpsStmts, "$1 = #copyString($2);$n", [dest.rdLoc, src.rdLoc])
  276. elif dest.storage == OnHeap:
  277. # we use a temporary to care for the dreaded self assignment:
  278. var tmp: TLoc
  279. getTemp(p, ty, tmp)
  280. linefmt(p, cpsStmts, "$3 = $1; $1 = #copyStringRC1($2);$n",
  281. [dest.rdLoc, src.rdLoc, tmp.rdLoc])
  282. linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", [tmp.rdLoc])
  283. else:
  284. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, #copyString($2));$n",
  285. [addrLoc(p.config, dest), rdLoc(src)])
  286. of tyProc:
  287. if containsGarbageCollectedRef(dest.t):
  288. # optimize closure assignment:
  289. let a = optAsgnLoc(dest, dest.t, "ClE_0".rope)
  290. let b = optAsgnLoc(src, dest.t, "ClE_0".rope)
  291. genRefAssign(p, a, b)
  292. linefmt(p, cpsStmts, "$1.ClP_0 = $2.ClP_0;$n", [rdLoc(dest), rdLoc(src)])
  293. else:
  294. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  295. of tyTuple:
  296. if containsGarbageCollectedRef(dest.t):
  297. if dest.t.len <= 4: genOptAsgnTuple(p, dest, src, flags)
  298. else: genGenericAsgn(p, dest, src, flags)
  299. else:
  300. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  301. of tyObject:
  302. # XXX: check for subtyping?
  303. if ty.isImportedCppType:
  304. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  305. elif not isObjLackingTypeField(ty):
  306. genGenericAsgn(p, dest, src, flags)
  307. elif containsGarbageCollectedRef(ty):
  308. if ty.sons[0].isNil and asgnComplexity(ty.n) <= 4:
  309. discard getTypeDesc(p.module, ty)
  310. internalAssert p.config, ty.n != nil
  311. genOptAsgnObject(p, dest, src, flags, ty.n, ty)
  312. else:
  313. genGenericAsgn(p, dest, src, flags)
  314. else:
  315. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  316. of tyArray:
  317. if containsGarbageCollectedRef(dest.t):
  318. genGenericAsgn(p, dest, src, flags)
  319. else:
  320. linefmt(p, cpsStmts,
  321. "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  322. [rdLoc(dest), rdLoc(src), getTypeDesc(p.module, dest.t)])
  323. of tyOpenArray, tyVarargs:
  324. # open arrays are always on the stack - really? What if a sequence is
  325. # passed to an open array?
  326. if containsGarbageCollectedRef(dest.t):
  327. linefmt(p, cpsStmts, # XXX: is this correct for arrays?
  328. "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  329. [addrLoc(p.config, dest), addrLoc(p.config, src),
  330. genTypeInfo(p.module, dest.t, dest.lode.info)])
  331. else:
  332. linefmt(p, cpsStmts,
  333. # bug #4799, keep the nimCopyMem for a while
  334. #"#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len_0);$n",
  335. "$1 = $2;$n",
  336. [rdLoc(dest), rdLoc(src)])
  337. of tySet:
  338. if mapType(p.config, ty) == ctArray:
  339. linefmt(p, cpsStmts, "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, $3);$n",
  340. [rdLoc(dest), rdLoc(src), getSize(p.config, dest.t)])
  341. else:
  342. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  343. of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString,
  344. tyInt..tyUInt64, tyRange, tyVar, tyLent, tyNil:
  345. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  346. else: internalError(p.config, "genAssignment: " & $ty.kind)
  347. if optMemTracker in p.options and dest.storage in {OnHeap, OnUnknown}:
  348. #writeStackTrace()
  349. #echo p.currLineInfo, " requesting"
  350. linefmt(p, cpsStmts, "#memTrackerWrite((void*)$1, $2, $3, $4);$n",
  351. [addrLoc(p.config, dest), getSize(p.config, dest.t),
  352. makeCString(toFullPath(p.config, p.currLineInfo)),
  353. p.currLineInfo.safeLineNm])
  354. proc genDeepCopy(p: BProc; dest, src: TLoc) =
  355. template addrLocOrTemp(a: TLoc): Rope =
  356. if a.k == locExpr:
  357. var tmp: TLoc
  358. getTemp(p, a.t, tmp)
  359. genAssignment(p, tmp, a, {})
  360. addrLoc(p.config, tmp)
  361. else:
  362. addrLoc(p.config, a)
  363. var ty = skipTypes(dest.t, abstractVarRange + {tyStatic})
  364. case ty.kind
  365. of tyPtr, tyRef, tyProc, tyTuple, tyObject, tyArray:
  366. # XXX optimize this
  367. linefmt(p, cpsStmts, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n",
  368. [addrLoc(p.config, dest), addrLocOrTemp(src),
  369. genTypeInfo(p.module, dest.t, dest.lode.info)])
  370. of tySequence, tyString:
  371. linefmt(p, cpsStmts, "#genericSeqDeepCopy($1, $2, $3);$n",
  372. [addrLoc(p.config, dest), rdLoc(src),
  373. genTypeInfo(p.module, dest.t, dest.lode.info)])
  374. of tyOpenArray, tyVarargs:
  375. linefmt(p, cpsStmts,
  376. "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  377. [addrLoc(p.config, dest), addrLocOrTemp(src),
  378. genTypeInfo(p.module, dest.t, dest.lode.info)])
  379. of tySet:
  380. if mapType(p.config, ty) == ctArray:
  381. linefmt(p, cpsStmts, "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, $3);$n",
  382. [rdLoc(dest), rdLoc(src), getSize(p.config, dest.t)])
  383. else:
  384. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  385. of tyPointer, tyChar, tyBool, tyEnum, tyCString,
  386. tyInt..tyUInt64, tyRange, tyVar, tyLent:
  387. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  388. else: internalError(p.config, "genDeepCopy: " & $ty.kind)
  389. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) =
  390. if d.k != locNone:
  391. if lfNoDeepCopy in d.flags: genAssignment(p, d, s, {})
  392. else: genAssignment(p, d, s, {needToCopy})
  393. else:
  394. d = s # ``d`` is free, so fill it with ``s``
  395. proc putDataIntoDest(p: BProc, d: var TLoc, n: PNode, r: Rope) =
  396. var a: TLoc
  397. if d.k != locNone:
  398. # need to generate an assignment here
  399. initLoc(a, locData, n, OnStatic)
  400. a.r = r
  401. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  402. else: genAssignment(p, d, a, {needToCopy})
  403. else:
  404. # we cannot call initLoc() here as that would overwrite
  405. # the flags field!
  406. d.k = locData
  407. d.lode = n
  408. d.r = r
  409. proc putIntoDest(p: BProc, d: var TLoc, n: PNode, r: Rope; s=OnUnknown) =
  410. var a: TLoc
  411. if d.k != locNone:
  412. # need to generate an assignment here
  413. initLoc(a, locExpr, n, s)
  414. a.r = r
  415. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  416. else: genAssignment(p, d, a, {needToCopy})
  417. else:
  418. # we cannot call initLoc() here as that would overwrite
  419. # the flags field!
  420. d.k = locExpr
  421. d.lode = n
  422. d.r = r
  423. proc binaryStmt(p: BProc, e: PNode, d: var TLoc, op: string) =
  424. var a, b: TLoc
  425. if d.k != locNone: internalError(p.config, e.info, "binaryStmt")
  426. initLocExpr(p, e.sons[1], a)
  427. initLocExpr(p, e.sons[2], b)
  428. lineCg(p, cpsStmts, "$1 $2 $3;$n", [rdLoc(a), op, rdLoc(b)])
  429. proc binaryStmtAddr(p: BProc, e: PNode, d: var TLoc, cpname: string) =
  430. var a, b: TLoc
  431. if d.k != locNone: internalError(p.config, e.info, "binaryStmtAddr")
  432. initLocExpr(p, e.sons[1], a)
  433. initLocExpr(p, e.sons[2], b)
  434. lineCg(p, cpsStmts, "#$1($2, $3);$n", [cpname, byRefLoc(p, a), rdLoc(b)])
  435. template unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  436. var a: TLoc
  437. if d.k != locNone: internalError(p.config, e.info, "unaryStmt")
  438. initLocExpr(p, e.sons[1], a)
  439. lineCg(p, cpsStmts, frmt, [rdLoc(a)])
  440. template binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  441. var a, b: TLoc
  442. assert(e.sons[1].typ != nil)
  443. assert(e.sons[2].typ != nil)
  444. initLocExpr(p, e.sons[1], a)
  445. initLocExpr(p, e.sons[2], b)
  446. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)]))
  447. template binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  448. var a, b: TLoc
  449. assert(e.sons[1].typ != nil)
  450. assert(e.sons[2].typ != nil)
  451. initLocExpr(p, e.sons[1], a)
  452. initLocExpr(p, e.sons[2], b)
  453. putIntoDest(p, d, e, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc]))
  454. template unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  455. var a: TLoc
  456. initLocExpr(p, e.sons[1], a)
  457. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdLoc(a)]))
  458. template unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  459. var a: TLoc
  460. initLocExpr(p, e.sons[1], a)
  461. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdCharLoc(a)]))
  462. template binaryArithOverflowRaw(p: BProc, t: PType, a, b: TLoc;
  463. cpname: string): Rope =
  464. var size = getSize(p.config, t)
  465. let storage = if size < p.config.target.intSize: rope("NI")
  466. else: getTypeDesc(p.module, t)
  467. var result = getTempName(p.module)
  468. linefmt(p, cpsLocals, "$1 $2;$n", [storage, result])
  469. lineCg(p, cpsStmts, "$1 = #$2($3, $4);$n", [result, cpname, rdCharLoc(a), rdCharLoc(b)])
  470. if size < p.config.target.intSize or t.kind in {tyRange, tyEnum}:
  471. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
  472. [result, intLiteral(firstOrd(p.config, t)), intLiteral(lastOrd(p.config, t))])
  473. result
  474. proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  475. const
  476. prc: array[mAddI..mPred, string] = [
  477. "addInt", "subInt",
  478. "mulInt", "divInt", "modInt",
  479. "addInt", "subInt"
  480. ]
  481. prc64: array[mAddI..mPred, string] = [
  482. "addInt64", "subInt64",
  483. "mulInt64", "divInt64", "modInt64",
  484. "addInt64", "subInt64"
  485. ]
  486. opr: array[mAddI..mPred, string] = ["+", "-", "*", "/", "%", "+", "-"]
  487. var a, b: TLoc
  488. assert(e.sons[1].typ != nil)
  489. assert(e.sons[2].typ != nil)
  490. initLocExpr(p, e.sons[1], a)
  491. initLocExpr(p, e.sons[2], b)
  492. # skipping 'range' is correct here as we'll generate a proper range check
  493. # later via 'chckRange'
  494. let t = e.typ.skipTypes(abstractRange)
  495. if optOverflowCheck notin p.options:
  496. let res = "($1)($2 $3 $4)" % [getTypeDesc(p.module, e.typ), rdLoc(a), rope(opr[m]), rdLoc(b)]
  497. putIntoDest(p, d, e, res)
  498. else:
  499. let res = binaryArithOverflowRaw(p, t, a, b,
  500. if t.kind == tyInt64: prc64[m] else: prc[m])
  501. putIntoDest(p, d, e, "($#)($#)" % [getTypeDesc(p.module, e.typ), res])
  502. proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  503. var
  504. a: TLoc
  505. t: PType
  506. assert(e.sons[1].typ != nil)
  507. initLocExpr(p, e.sons[1], a)
  508. t = skipTypes(e.typ, abstractRange)
  509. if optOverflowCheck in p.options:
  510. linefmt(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n",
  511. [rdLoc(a), intLiteral(firstOrd(p.config, t))])
  512. case m
  513. of mUnaryMinusI:
  514. putIntoDest(p, d, e, "((NI$2)-($1))" % [rdLoc(a), rope(getSize(p.config, t) * 8)])
  515. of mUnaryMinusI64:
  516. putIntoDest(p, d, e, "-($1)" % [rdLoc(a)])
  517. of mAbsI:
  518. putIntoDest(p, d, e, "($1 > 0? ($1) : -($1))" % [rdLoc(a)])
  519. else:
  520. assert(false, $m)
  521. proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  522. var
  523. a, b: TLoc
  524. s, k: BiggestInt
  525. assert(e.sons[1].typ != nil)
  526. assert(e.sons[2].typ != nil)
  527. initLocExpr(p, e.sons[1], a)
  528. initLocExpr(p, e.sons[2], b)
  529. # BUGFIX: cannot use result-type here, as it may be a boolean
  530. s = max(getSize(p.config, a.t), getSize(p.config, b.t)) * 8
  531. k = getSize(p.config, a.t) * 8
  532. template applyFormat(frmt: untyped) =
  533. putIntoDest(p, d, e, frmt % [
  534. rdLoc(a), rdLoc(b), rope(s),
  535. getSimpleTypeDesc(p.module, e.typ), rope(k)]
  536. )
  537. case op
  538. of mAddF64: applyFormat("(($4)($1) + ($4)($2))")
  539. of mSubF64: applyFormat("(($4)($1) - ($4)($2))")
  540. of mMulF64: applyFormat("(($4)($1) * ($4)($2))")
  541. of mDivF64: applyFormat("(($4)($1) / ($4)($2))")
  542. of mShrI: applyFormat("($4)((NU$5)($1) >> (NU$3)($2))")
  543. of mShlI: applyFormat("($4)((NU$3)($1) << (NU$3)($2))")
  544. of mAshrI: applyFormat("($4)((NI$3)($1) >> (NU$3)($2))")
  545. of mBitandI: applyFormat("($4)($1 & $2)")
  546. of mBitorI: applyFormat("($4)($1 | $2)")
  547. of mBitxorI: applyFormat("($4)($1 ^ $2)")
  548. of mMinI: applyFormat("(($1 <= $2) ? $1 : $2)")
  549. of mMaxI: applyFormat("(($1 >= $2) ? $1 : $2)")
  550. of mAddU: applyFormat("($4)((NU$3)($1) + (NU$3)($2))")
  551. of mSubU: applyFormat("($4)((NU$3)($1) - (NU$3)($2))")
  552. of mMulU: applyFormat("($4)((NU$3)($1) * (NU$3)($2))")
  553. of mDivU: applyFormat("($4)((NU$3)($1) / (NU$3)($2))")
  554. of mModU: applyFormat("($4)((NU$3)($1) % (NU$3)($2))")
  555. of mEqI: applyFormat("($1 == $2)")
  556. of mLeI: applyFormat("($1 <= $2)")
  557. of mLtI: applyFormat("($1 < $2)")
  558. of mEqF64: applyFormat("($1 == $2)")
  559. of mLeF64: applyFormat("($1 <= $2)")
  560. of mLtF64: applyFormat("($1 < $2)")
  561. of mLeU: applyFormat("((NU$3)($1) <= (NU$3)($2))")
  562. of mLtU: applyFormat("((NU$3)($1) < (NU$3)($2))")
  563. of mLeU64: applyFormat("((NU64)($1) <= (NU64)($2))")
  564. of mLtU64: applyFormat("((NU64)($1) < (NU64)($2))")
  565. of mEqEnum: applyFormat("($1 == $2)")
  566. of mLeEnum: applyFormat("($1 <= $2)")
  567. of mLtEnum: applyFormat("($1 < $2)")
  568. of mEqCh: applyFormat("((NU8)($1) == (NU8)($2))")
  569. of mLeCh: applyFormat("((NU8)($1) <= (NU8)($2))")
  570. of mLtCh: applyFormat("((NU8)($1) < (NU8)($2))")
  571. of mEqB: applyFormat("($1 == $2)")
  572. of mLeB: applyFormat("($1 <= $2)")
  573. of mLtB: applyFormat("($1 < $2)")
  574. of mEqRef: applyFormat("($1 == $2)")
  575. of mEqUntracedRef: applyFormat("($1 == $2)")
  576. of mLePtr: applyFormat("($1 <= $2)")
  577. of mLtPtr: applyFormat("($1 < $2)")
  578. of mXor: applyFormat("($1 != $2)")
  579. else:
  580. assert(false, $op)
  581. proc genEqProc(p: BProc, e: PNode, d: var TLoc) =
  582. var a, b: TLoc
  583. assert(e.sons[1].typ != nil)
  584. assert(e.sons[2].typ != nil)
  585. initLocExpr(p, e.sons[1], a)
  586. initLocExpr(p, e.sons[2], b)
  587. if a.t.skipTypes(abstractInstOwned).callConv == ccClosure:
  588. putIntoDest(p, d, e,
  589. "($1.ClP_0 == $2.ClP_0 && $1.ClE_0 == $2.ClE_0)" % [rdLoc(a), rdLoc(b)])
  590. else:
  591. putIntoDest(p, d, e, "($1 == $2)" % [rdLoc(a), rdLoc(b)])
  592. proc genIsNil(p: BProc, e: PNode, d: var TLoc) =
  593. let t = skipTypes(e.sons[1].typ, abstractRange)
  594. if t.kind == tyProc and t.callConv == ccClosure:
  595. unaryExpr(p, e, d, "($1.ClP_0 == 0)")
  596. else:
  597. unaryExpr(p, e, d, "($1 == 0)")
  598. proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  599. var
  600. a: TLoc
  601. t: PType
  602. assert(e.sons[1].typ != nil)
  603. initLocExpr(p, e.sons[1], a)
  604. t = skipTypes(e.typ, abstractRange)
  605. template applyFormat(frmt: untyped) =
  606. putIntoDest(p, d, e, frmt % [rdLoc(a), rope(getSize(p.config, t) * 8),
  607. getSimpleTypeDesc(p.module, e.typ)])
  608. case op
  609. of mNot:
  610. applyFormat("!($1)")
  611. of mUnaryPlusI:
  612. applyFormat("$1")
  613. of mBitnotI:
  614. applyFormat("($3)((NU$2) ~($1))")
  615. of mUnaryPlusF64:
  616. applyFormat("$1")
  617. of mUnaryMinusF64:
  618. applyFormat("-($1)")
  619. else:
  620. assert false, $op
  621. proc isCppRef(p: BProc; typ: PType): bool {.inline.} =
  622. result = p.module.compileToCpp and
  623. skipTypes(typ, abstractInstOwned).kind == tyVar and
  624. tfVarIsPtr notin skipTypes(typ, abstractInstOwned).flags
  625. proc genDeref(p: BProc, e: PNode, d: var TLoc) =
  626. let mt = mapType(p.config, e.sons[0].typ)
  627. if mt in {ctArray, ctPtrToArray} and lfEnforceDeref notin d.flags:
  628. # XXX the amount of hacks for C's arrays is incredible, maybe we should
  629. # simply wrap them in a struct? --> Losing auto vectorization then?
  630. expr(p, e.sons[0], d)
  631. if e.sons[0].typ.skipTypes(abstractInstOwned).kind == tyRef:
  632. d.storage = OnHeap
  633. else:
  634. var a: TLoc
  635. var typ = e.sons[0].typ
  636. if typ.kind in {tyUserTypeClass, tyUserTypeClassInst} and typ.isResolvedUserTypeClass:
  637. typ = typ.lastSon
  638. typ = typ.skipTypes(abstractInstOwned)
  639. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and p.module.compileToCpp and e.sons[0].kind == nkHiddenAddr:
  640. initLocExprSingleUse(p, e[0][0], d)
  641. return
  642. else:
  643. initLocExprSingleUse(p, e.sons[0], a)
  644. if d.k == locNone:
  645. # dest = *a; <-- We do not know that 'dest' is on the heap!
  646. # It is completely wrong to set 'd.storage' here, unless it's not yet
  647. # been assigned to.
  648. case typ.kind
  649. of tyRef:
  650. d.storage = OnHeap
  651. of tyVar, tyLent:
  652. d.storage = OnUnknown
  653. if tfVarIsPtr notin typ.flags and p.module.compileToCpp and
  654. e.kind == nkHiddenDeref:
  655. putIntoDest(p, d, e, rdLoc(a), a.storage)
  656. return
  657. of tyPtr:
  658. d.storage = OnUnknown # BUGFIX!
  659. else:
  660. internalError(p.config, e.info, "genDeref " & $typ.kind)
  661. elif p.module.compileToCpp:
  662. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and
  663. e.kind == nkHiddenDeref:
  664. putIntoDest(p, d, e, rdLoc(a), a.storage)
  665. return
  666. if mt == ctPtrToArray and lfEnforceDeref in d.flags:
  667. # we lie about the type for better C interop: 'ptr array[3,T]' is
  668. # translated to 'ptr T', but for deref'ing this produces wrong code.
  669. # See tmissingderef. So we get rid of the deref instead. The codegen
  670. # ends up using 'memcpy' for the array assignment,
  671. # so the '&' and '*' cancel out:
  672. putIntoDest(p, d, lodeTyp(a.t.sons[0]), rdLoc(a), a.storage)
  673. else:
  674. putIntoDest(p, d, e, "(*$1)" % [rdLoc(a)], a.storage)
  675. proc genAddr(p: BProc, e: PNode, d: var TLoc) =
  676. # careful 'addr(myptrToArray)' needs to get the ampersand:
  677. if e.sons[0].typ.skipTypes(abstractInstOwned).kind in {tyRef, tyPtr}:
  678. var a: TLoc
  679. initLocExpr(p, e.sons[0], a)
  680. putIntoDest(p, d, e, "&" & a.r, a.storage)
  681. #Message(e.info, warnUser, "HERE NEW &")
  682. elif mapType(p.config, e.sons[0].typ) == ctArray or isCppRef(p, e.typ):
  683. expr(p, e.sons[0], d)
  684. else:
  685. var a: TLoc
  686. initLocExpr(p, e.sons[0], a)
  687. putIntoDest(p, d, e, addrLoc(p.config, a), a.storage)
  688. template inheritLocation(d: var TLoc, a: TLoc) =
  689. if d.k == locNone: d.storage = a.storage
  690. proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc) =
  691. initLocExpr(p, e.sons[0], a)
  692. if e.sons[1].kind != nkSym: internalError(p.config, e.info, "genRecordFieldAux")
  693. d.inheritLocation(a)
  694. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  695. proc genTupleElem(p: BProc, e: PNode, d: var TLoc) =
  696. var
  697. a: TLoc
  698. i: int
  699. initLocExpr(p, e.sons[0], a)
  700. let tupType = a.t.skipTypes(abstractInst+{tyVar})
  701. assert tupType.kind == tyTuple
  702. d.inheritLocation(a)
  703. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  704. var r = rdLoc(a)
  705. case e.sons[1].kind
  706. of nkIntLit..nkUInt64Lit: i = int(e.sons[1].intVal)
  707. else: internalError(p.config, e.info, "genTupleElem")
  708. addf(r, ".Field$1", [rope(i)])
  709. putIntoDest(p, d, e, r, a.storage)
  710. proc lookupFieldAgain(p: BProc, ty: PType; field: PSym; r: var Rope;
  711. resTyp: ptr PType = nil): PSym =
  712. var ty = ty
  713. assert r != nil
  714. while ty != nil:
  715. ty = ty.skipTypes(skipPtrs)
  716. assert(ty.kind in {tyTuple, tyObject})
  717. result = lookupInRecord(ty.n, field.name)
  718. if result != nil:
  719. if resTyp != nil: resTyp[] = ty
  720. break
  721. if not p.module.compileToCpp: add(r, ".Sup")
  722. ty = ty.sons[0]
  723. if result == nil: internalError(p.config, field.info, "genCheckedRecordField")
  724. proc genRecordField(p: BProc, e: PNode, d: var TLoc) =
  725. var a: TLoc
  726. genRecordFieldAux(p, e, d, a)
  727. var r = rdLoc(a)
  728. var f = e.sons[1].sym
  729. let ty = skipTypes(a.t, abstractInstOwned + tyUserTypeClasses)
  730. if ty.kind == tyTuple:
  731. # we found a unique tuple type which lacks field information
  732. # so we use Field$i
  733. addf(r, ".Field$1", [rope(f.position)])
  734. putIntoDest(p, d, e, r, a.storage)
  735. else:
  736. var rtyp: PType
  737. let field = lookupFieldAgain(p, ty, f, r, addr rtyp)
  738. if field.loc.r == nil and rtyp != nil: fillObjectFields(p.module, rtyp)
  739. if field.loc.r == nil: internalError(p.config, e.info, "genRecordField 3 " & typeToString(ty))
  740. addf(r, ".$1", [field.loc.r])
  741. putIntoDest(p, d, e, r, a.storage)
  742. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc)
  743. proc genFieldCheck(p: BProc, e: PNode, obj: Rope, field: PSym) =
  744. var test, u, v: TLoc
  745. for i in 1 ..< len(e):
  746. var it = e.sons[i]
  747. assert(it.kind in nkCallKinds)
  748. assert(it.sons[0].kind == nkSym)
  749. let op = it.sons[0].sym
  750. if op.magic == mNot: it = it.sons[1]
  751. let disc = it.sons[2].skipConv
  752. assert(disc.kind == nkSym)
  753. initLoc(test, locNone, it, OnStack)
  754. initLocExpr(p, it.sons[1], u)
  755. initLoc(v, locExpr, disc, OnUnknown)
  756. v.r = obj
  757. v.r.add(".")
  758. v.r.add(disc.sym.loc.r)
  759. genInExprAux(p, it, u, v, test)
  760. let msg = genFieldError(field, disc.sym)
  761. let strLit = genStringLiteral(p.module, newStrNode(nkStrLit, msg))
  762. if op.magic == mNot:
  763. linefmt(p, cpsStmts,
  764. "if ($1) #raiseFieldError($2);$n",
  765. [rdLoc(test), strLit])
  766. else:
  767. linefmt(p, cpsStmts,
  768. "if (!($1)) #raiseFieldError($2);$n",
  769. [rdLoc(test), strLit])
  770. proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) =
  771. if optFieldCheck in p.options:
  772. var a: TLoc
  773. genRecordFieldAux(p, e.sons[0], d, a)
  774. let ty = skipTypes(a.t, abstractInst + tyUserTypeClasses)
  775. var r = rdLoc(a)
  776. let f = e.sons[0].sons[1].sym
  777. let field = lookupFieldAgain(p, ty, f, r)
  778. if field.loc.r == nil: fillObjectFields(p.module, ty)
  779. if field.loc.r == nil:
  780. internalError(p.config, e.info, "genCheckedRecordField") # generate the checks:
  781. genFieldCheck(p, e, r, field)
  782. add(r, ropecg(p.module, ".$1", [field.loc.r]))
  783. putIntoDest(p, d, e.sons[0], r, a.storage)
  784. else:
  785. genRecordField(p, e.sons[0], d)
  786. proc genUncheckedArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  787. var a, b: TLoc
  788. initLocExpr(p, x, a)
  789. initLocExpr(p, y, b)
  790. d.inheritLocation(a)
  791. putIntoDest(p, d, n, ropecg(p.module, "$1[$2]", [rdLoc(a), rdCharLoc(b)]),
  792. a.storage)
  793. proc genArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  794. var a, b: TLoc
  795. initLocExpr(p, x, a)
  796. initLocExpr(p, y, b)
  797. var ty = skipTypes(a.t, abstractVarRange + abstractPtrs + tyUserTypeClasses)
  798. var first = intLiteral(firstOrd(p.config, ty))
  799. # emit range check:
  800. if optBoundsCheck in p.options and ty.kind != tyUncheckedArray:
  801. if not isConstExpr(y):
  802. # semantic pass has already checked for const index expressions
  803. if firstOrd(p.config, ty) == 0 and lastOrd(p.config, ty) >= 0:
  804. if (firstOrd(p.config, b.t) < firstOrd(p.config, ty)) or (lastOrd(p.config, b.t) > lastOrd(p.config, ty)):
  805. linefmt(p, cpsStmts, "if ((NU)($1) > (NU)($2)) #raiseIndexError2($1, $2);$n",
  806. [rdCharLoc(b), intLiteral(lastOrd(p.config, ty))])
  807. else:
  808. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseIndexError3($1, $2, $3);$n",
  809. [rdCharLoc(b), first, intLiteral(lastOrd(p.config, ty))])
  810. else:
  811. let idx = getOrdValue(y)
  812. if idx < firstOrd(p.config, ty) or idx > lastOrd(p.config, ty):
  813. localError(p.config, x.info, formatErrorIndexBound(idx, firstOrd(p.config, ty), lastOrd(p.config, ty)))
  814. d.inheritLocation(a)
  815. putIntoDest(p, d, n,
  816. ropecg(p.module, "$1[($2)- $3]", [rdLoc(a), rdCharLoc(b), first]), a.storage)
  817. proc genCStringElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  818. var a, b: TLoc
  819. initLocExpr(p, x, a)
  820. initLocExpr(p, y, b)
  821. inheritLocation(d, a)
  822. putIntoDest(p, d, n,
  823. ropecg(p.module, "$1[$2]", [rdLoc(a), rdCharLoc(b)]), a.storage)
  824. proc genBoundsCheck(p: BProc; arr, a, b: TLoc) =
  825. let ty = skipTypes(arr.t, abstractVarRange)
  826. case ty.kind
  827. of tyOpenArray, tyVarargs:
  828. linefmt(p, cpsStmts,
  829. "if ($2-$1 != -1 && " &
  830. "((NU)($1) >= (NU)($3Len_0) || (NU)($2) >= (NU)($3Len_0))) #raiseIndexError();$n",
  831. [rdLoc(a), rdLoc(b), rdLoc(arr)])
  832. of tyArray:
  833. let first = intLiteral(firstOrd(p.config, ty))
  834. linefmt(p, cpsStmts,
  835. "if ($2-$1 != -1 && " &
  836. "($2-$1 < -1 || $1 < $3 || $1 > $4 || $2 < $3 || $2 > $4)) #raiseIndexError();$n",
  837. [rdCharLoc(a), rdCharLoc(b), first, intLiteral(lastOrd(p.config, ty))])
  838. of tySequence, tyString:
  839. linefmt(p, cpsStmts,
  840. "if ($2-$1 != -1 && " &
  841. "((NU)($1) >= (NU)$3 || (NU)($2) >= (NU)$3)) #raiseIndexError();$n",
  842. [rdLoc(a), rdLoc(b), lenExpr(p, arr)])
  843. else: discard
  844. proc genOpenArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  845. var a, b: TLoc
  846. initLocExpr(p, x, a)
  847. initLocExpr(p, y, b) # emit range check:
  848. if optBoundsCheck in p.options:
  849. linefmt(p, cpsStmts, "if ((NU)($1) >= (NU)($2Len_0)) #raiseIndexError2($1,$2Len_0-1);$n",
  850. [rdLoc(b), rdLoc(a)]) # BUGFIX: ``>=`` and not ``>``!
  851. inheritLocation(d, a)
  852. putIntoDest(p, d, n,
  853. ropecg(p.module, "$1[$2]", [rdLoc(a), rdCharLoc(b)]), a.storage)
  854. proc genSeqElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  855. var a, b: TLoc
  856. initLocExpr(p, x, a)
  857. initLocExpr(p, y, b)
  858. var ty = skipTypes(a.t, abstractVarRange)
  859. if ty.kind in {tyRef, tyPtr}:
  860. ty = skipTypes(ty.lastSon, abstractVarRange) # emit range check:
  861. if optBoundsCheck in p.options:
  862. if ty.kind == tyString and (not defined(nimNoZeroTerminator) or optLaxStrings in p.options):
  863. linefmt(p, cpsStmts,
  864. "if ((NU)($1) > (NU)$2) #raiseIndexError2($1,$2);$n",
  865. [rdLoc(b), lenExpr(p, a)])
  866. else:
  867. linefmt(p, cpsStmts,
  868. "if ((NU)($1) >= (NU)$2) #raiseIndexError2($1,$2-1);$n",
  869. [rdLoc(b), lenExpr(p, a)])
  870. if d.k == locNone: d.storage = OnHeap
  871. if skipTypes(a.t, abstractVar).kind in {tyRef, tyPtr}:
  872. a.r = ropecg(p.module, "(*$1)", [a.r])
  873. if lfPrepareForMutation in d.flags and ty.kind == tyString and
  874. p.config.selectedGC == gcDestructors:
  875. linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
  876. putIntoDest(p, d, n,
  877. ropecg(p.module, "$1$3[$2]", [rdLoc(a), rdCharLoc(b), dataField(p)]), a.storage)
  878. proc genBracketExpr(p: BProc; n: PNode; d: var TLoc) =
  879. var ty = skipTypes(n.sons[0].typ, abstractVarRange + tyUserTypeClasses)
  880. if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange)
  881. case ty.kind
  882. of tyUncheckedArray: genUncheckedArrayElem(p, n, n.sons[0], n.sons[1], d)
  883. of tyArray: genArrayElem(p, n, n.sons[0], n.sons[1], d)
  884. of tyOpenArray, tyVarargs: genOpenArrayElem(p, n, n.sons[0], n.sons[1], d)
  885. of tySequence, tyString: genSeqElem(p, n, n.sons[0], n.sons[1], d)
  886. of tyCString: genCStringElem(p, n, n.sons[0], n.sons[1], d)
  887. of tyTuple: genTupleElem(p, n, d)
  888. else: internalError(p.config, n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  889. discard getTypeDesc(p.module, n.typ)
  890. proc isSimpleExpr(n: PNode): bool =
  891. # calls all the way down --> can stay expression based
  892. case n.kind
  893. of nkCallKinds, nkDotExpr, nkPar, nkTupleConstr,
  894. nkObjConstr, nkBracket, nkCurly, nkHiddenDeref, nkDerefExpr, nkHiddenAddr,
  895. nkHiddenStdConv, nkHiddenSubConv, nkConv, nkAddr:
  896. for c in n:
  897. if not isSimpleExpr(c): return false
  898. result = true
  899. of nkStmtListExpr:
  900. for i in 0..n.len-2:
  901. if n[i].kind notin {nkCommentStmt, nkEmpty}: return false
  902. result = isSimpleExpr(n.lastSon)
  903. else:
  904. if n.isAtom:
  905. result = true
  906. proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  907. # how to generate code?
  908. # 'expr1 and expr2' becomes:
  909. # result = expr1
  910. # fjmp result, end
  911. # result = expr2
  912. # end:
  913. # ... (result computed)
  914. # BUGFIX:
  915. # a = b or a
  916. # used to generate:
  917. # a = b
  918. # if a: goto end
  919. # a = a
  920. # end:
  921. # now it generates:
  922. # tmp = b
  923. # if tmp: goto end
  924. # tmp = a
  925. # end:
  926. # a = tmp
  927. when false:
  928. #if isSimpleExpr(e) and p.module.compileToCpp:
  929. var tmpA, tmpB: TLoc
  930. #getTemp(p, e.typ, tmpA)
  931. #getTemp(p, e.typ, tmpB)
  932. initLocExprSingleUse(p, e.sons[1], tmpA)
  933. initLocExprSingleUse(p, e.sons[2], tmpB)
  934. tmpB.k = locExpr
  935. if m == mOr:
  936. tmpB.r = "((" & rdLoc(tmpA) & ")||(" & rdLoc(tmpB) & "))"
  937. else:
  938. tmpB.r = "((" & rdLoc(tmpA) & ")&&(" & rdLoc(tmpB) & "))"
  939. if d.k == locNone:
  940. d = tmpB
  941. else:
  942. genAssignment(p, d, tmpB, {})
  943. else:
  944. var
  945. L: TLabel
  946. tmp: TLoc
  947. getTemp(p, e.typ, tmp) # force it into a temp!
  948. inc p.splitDecls
  949. expr(p, e.sons[1], tmp)
  950. L = getLabel(p)
  951. if m == mOr:
  952. lineF(p, cpsStmts, "if ($1) goto $2;$n", [rdLoc(tmp), L])
  953. else:
  954. lineF(p, cpsStmts, "if (!($1)) goto $2;$n", [rdLoc(tmp), L])
  955. expr(p, e.sons[2], tmp)
  956. fixLabel(p, L)
  957. if d.k == locNone:
  958. d = tmp
  959. else:
  960. genAssignment(p, d, tmp, {}) # no need for deep copying
  961. dec p.splitDecls
  962. proc genEcho(p: BProc, n: PNode) =
  963. # this unusual way of implementing it ensures that e.g. ``echo("hallo", 45)``
  964. # is threadsafe.
  965. internalAssert p.config, n.kind == nkBracket
  966. if p.config.target.targetOS == osGenode:
  967. # echo directly to the Genode LOG session
  968. var args: Rope = nil
  969. var a: TLoc
  970. for it in n.sons:
  971. if it.skipConv.kind == nkNilLit:
  972. add(args, ", \"\"")
  973. else:
  974. initLocExpr(p, it, a)
  975. add(args, ropecg(p.module, ", Genode::Cstring($1->data, $1->len)", [rdLoc(a)]))
  976. p.module.includeHeader("<base/log.h>")
  977. p.module.includeHeader("<util/string.h>")
  978. linefmt(p, cpsStmts, """Genode::log(""$1);$n""", [args])
  979. else:
  980. if n.len == 0:
  981. linefmt(p, cpsStmts, "#echoBinSafe(NIM_NIL, $1);$n", [n.len])
  982. else:
  983. var a: TLoc
  984. initLocExpr(p, n, a)
  985. linefmt(p, cpsStmts, "#echoBinSafe($1, $2);$n", [a.rdLoc, n.len])
  986. when false:
  987. p.module.includeHeader("<stdio.h>")
  988. linefmt(p, cpsStmts, "printf($1$2);$n",
  989. makeCString(repeat("%s", n.len) & "\L"), [args])
  990. linefmt(p, cpsStmts, "fflush(stdout);$n", [])
  991. proc gcUsage(conf: ConfigRef; n: PNode) =
  992. if conf.selectedGC == gcNone: message(conf, n.info, warnGcMem, n.renderTree)
  993. proc strLoc(p: BProc; d: TLoc): Rope =
  994. if p.config.selectedGC == gcDestructors:
  995. result = byRefLoc(p, d)
  996. else:
  997. result = rdLoc(d)
  998. proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
  999. # <Nim code>
  1000. # s = 'Hello ' & name & ', how do you feel?' & 'z'
  1001. #
  1002. # <generated C code>
  1003. # {
  1004. # string tmp0;
  1005. # ...
  1006. # tmp0 = rawNewString(6 + 17 + 1 + s2->len);
  1007. # // we cannot generate s = rawNewString(...) here, because
  1008. # // ``s`` may be used on the right side of the expression
  1009. # appendString(tmp0, strlit_1);
  1010. # appendString(tmp0, name);
  1011. # appendString(tmp0, strlit_2);
  1012. # appendChar(tmp0, 'z');
  1013. # asgn(s, tmp0);
  1014. # }
  1015. var a, tmp: TLoc
  1016. getTemp(p, e.typ, tmp)
  1017. var L = 0
  1018. var appends: Rope = nil
  1019. var lens: Rope = nil
  1020. for i in 0 .. len(e) - 2:
  1021. # compute the length expression:
  1022. initLocExpr(p, e.sons[i + 1], a)
  1023. if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar:
  1024. inc(L)
  1025. add(appends, ropecg(p.module, "#appendChar($1, $2);$n", [strLoc(p, tmp), rdLoc(a)]))
  1026. else:
  1027. if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}:
  1028. inc(L, len(e.sons[i + 1].strVal))
  1029. else:
  1030. add(lens, lenExpr(p, a))
  1031. add(lens, " + ")
  1032. add(appends, ropecg(p.module, "#appendString($1, $2);$n", [strLoc(p, tmp), rdLoc(a)]))
  1033. linefmt(p, cpsStmts, "$1 = #rawNewString($2$3);$n", [tmp.r, lens, L])
  1034. add(p.s(cpsStmts), appends)
  1035. if d.k == locNone:
  1036. d = tmp
  1037. else:
  1038. genAssignment(p, d, tmp, {}) # no need for deep copying
  1039. gcUsage(p.config, e)
  1040. proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
  1041. # <Nim code>
  1042. # s &= 'Hello ' & name & ', how do you feel?' & 'z'
  1043. # // BUG: what if s is on the left side too?
  1044. # <generated C code>
  1045. # {
  1046. # s = resizeString(s, 6 + 17 + 1 + name->len);
  1047. # appendString(s, strlit_1);
  1048. # appendString(s, name);
  1049. # appendString(s, strlit_2);
  1050. # appendChar(s, 'z');
  1051. # }
  1052. var
  1053. a, dest, call: TLoc
  1054. appends, lens: Rope
  1055. assert(d.k == locNone)
  1056. var L = 0
  1057. initLocExpr(p, e.sons[1], dest)
  1058. for i in 0 .. len(e) - 3:
  1059. # compute the length expression:
  1060. initLocExpr(p, e.sons[i + 2], a)
  1061. if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar:
  1062. inc(L)
  1063. add(appends, ropecg(p.module, "#appendChar($1, $2);$n",
  1064. [strLoc(p, dest), rdLoc(a)]))
  1065. else:
  1066. if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}:
  1067. inc(L, len(e.sons[i + 2].strVal))
  1068. else:
  1069. add(lens, lenExpr(p, a))
  1070. add(lens, " + ")
  1071. add(appends, ropecg(p.module, "#appendString($1, $2);$n",
  1072. [strLoc(p, dest), rdLoc(a)]))
  1073. if p.config.selectedGC == gcDestructors:
  1074. linefmt(p, cpsStmts, "#prepareAdd($1, $2$3);$n",
  1075. [byRefLoc(p, dest), lens, L])
  1076. else:
  1077. initLoc(call, locCall, e, OnHeap)
  1078. call.r = ropecg(p.module, "#resizeString($1, $2$3)", [rdLoc(dest), lens, L])
  1079. genAssignment(p, dest, call, {})
  1080. gcUsage(p.config, e)
  1081. add(p.s(cpsStmts), appends)
  1082. proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
  1083. # seq &= x -->
  1084. # seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x));
  1085. # seq->data[seq->len-1] = x;
  1086. var a, b, dest, tmpL, call: TLoc
  1087. initLocExpr(p, e.sons[1], a)
  1088. initLocExpr(p, e.sons[2], b)
  1089. let seqType = skipTypes(e.sons[1].typ, {tyVar})
  1090. initLoc(call, locCall, e, OnHeap)
  1091. if not p.module.compileToCpp:
  1092. const seqAppendPattern = "($2) #incrSeqV3((TGenericSeq*)($1), $3)"
  1093. call.r = ropecg(p.module, seqAppendPattern, [rdLoc(a),
  1094. getTypeDesc(p.module, e.sons[1].typ),
  1095. genTypeInfo(p.module, seqType, e.info)])
  1096. else:
  1097. const seqAppendPattern = "($2) #incrSeqV3($1, $3)"
  1098. call.r = ropecg(p.module, seqAppendPattern, [rdLoc(a),
  1099. getTypeDesc(p.module, e.sons[1].typ),
  1100. genTypeInfo(p.module, seqType, e.info)])
  1101. # emit the write barrier if required, but we can always move here, so
  1102. # use 'genRefAssign' for the seq.
  1103. genRefAssign(p, a, call)
  1104. #if bt != b.t:
  1105. # echo "YES ", e.info, " new: ", typeToString(bt), " old: ", typeToString(b.t)
  1106. initLoc(dest, locExpr, e.sons[2], OnHeap)
  1107. getIntTemp(p, tmpL)
  1108. lineCg(p, cpsStmts, "$1 = $2->$3++;$n", [tmpL.r, rdLoc(a), lenField(p)])
  1109. dest.r = ropecg(p.module, "$1$3[$2]", [rdLoc(a), tmpL.r, dataField(p)])
  1110. genAssignment(p, dest, b, {needToCopy})
  1111. gcUsage(p.config, e)
  1112. proc genReset(p: BProc, n: PNode) =
  1113. var a: TLoc
  1114. initLocExpr(p, n.sons[1], a)
  1115. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  1116. [addrLoc(p.config, a),
  1117. genTypeInfo(p.module, skipTypes(a.t, {tyVar}), n.info)])
  1118. proc genDefault(p: BProc; n: PNode; d: var TLoc) =
  1119. if d.k == locNone: getTemp(p, n.typ, d, needsInit=true)
  1120. else: resetLoc(p, d)
  1121. proc trivialDestructor(s: PSym): bool {.inline.} = s.ast[bodyPos].len == 0
  1122. proc rawGenNew(p: BProc, a: TLoc, sizeExpr: Rope) =
  1123. var sizeExpr = sizeExpr
  1124. let typ = a.t
  1125. var b: TLoc
  1126. initLoc(b, locExpr, a.lode, OnHeap)
  1127. let refType = typ.skipTypes(abstractInstOwned)
  1128. assert refType.kind == tyRef
  1129. let bt = refType.lastSon
  1130. if sizeExpr.isNil:
  1131. sizeExpr = "sizeof($1)" % [getTypeDesc(p.module, bt)]
  1132. if optOwnedRefs in p.config.globalOptions:
  1133. b.r = ropecg(p.module, "($1) #nimNewObj($2)",
  1134. [getTypeDesc(p.module, typ), sizeExpr])
  1135. genAssignment(p, a, b, {})
  1136. else:
  1137. let ti = genTypeInfo(p.module, typ, a.lode.info)
  1138. if bt.destructor != nil and not trivialDestructor(bt.destructor):
  1139. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1140. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1141. # convention at least:
  1142. if bt.destructor.typ == nil or bt.destructor.typ.callConv != ccDefault:
  1143. localError(p.module.config, a.lode.info,
  1144. "the destructor that is turned into a finalizer needs " &
  1145. "to have the 'nimcall' calling convention")
  1146. var f: TLoc
  1147. initLocExpr(p, newSymNode(bt.destructor), f)
  1148. addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1149. if a.storage == OnHeap and usesWriteBarrier(p.config):
  1150. if canFormAcycle(a.t):
  1151. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", [a.rdLoc])
  1152. else:
  1153. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", [a.rdLoc])
  1154. if p.config.selectedGC == gcGo:
  1155. # newObjRC1() would clash with unsureAsgnRef() - which is used by gcGo to
  1156. # implement the write barrier
  1157. b.r = ropecg(p.module, "($1) #newObj($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1158. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  1159. [addrLoc(p.config, a), b.rdLoc])
  1160. else:
  1161. # use newObjRC1 as an optimization
  1162. b.r = ropecg(p.module, "($1) #newObjRC1($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1163. linefmt(p, cpsStmts, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1164. else:
  1165. b.r = ropecg(p.module, "($1) #newObj($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1166. genAssignment(p, a, b, {})
  1167. # set the object type:
  1168. genObjectInit(p, cpsStmts, bt, a, false)
  1169. proc genNew(p: BProc, e: PNode) =
  1170. var a: TLoc
  1171. initLocExpr(p, e.sons[1], a)
  1172. # 'genNew' also handles 'unsafeNew':
  1173. if e.len == 3:
  1174. var se: TLoc
  1175. initLocExpr(p, e.sons[2], se)
  1176. rawGenNew(p, a, se.rdLoc)
  1177. else:
  1178. rawGenNew(p, a, nil)
  1179. gcUsage(p.config, e)
  1180. proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope; lenIsZero: bool) =
  1181. let seqtype = skipTypes(dest.t, abstractVarRange)
  1182. var call: TLoc
  1183. initLoc(call, locExpr, dest.lode, OnHeap)
  1184. if dest.storage == OnHeap and usesWriteBarrier(p.config):
  1185. if canFormAcycle(dest.t):
  1186. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", [dest.rdLoc])
  1187. else:
  1188. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", [dest.rdLoc])
  1189. if not lenIsZero:
  1190. if p.config.selectedGC == gcGo:
  1191. # we need the write barrier
  1192. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", [getTypeDesc(p.module, seqtype),
  1193. genTypeInfo(p.module, seqtype, dest.lode.info), length])
  1194. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n", [addrLoc(p.config, dest), call.rdLoc])
  1195. else:
  1196. call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", [getTypeDesc(p.module, seqtype),
  1197. genTypeInfo(p.module, seqtype, dest.lode.info), length])
  1198. linefmt(p, cpsStmts, "$1 = $2;$n", [dest.rdLoc, call.rdLoc])
  1199. else:
  1200. if lenIsZero:
  1201. call.r = rope"NIM_NIL"
  1202. else:
  1203. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", [getTypeDesc(p.module, seqtype),
  1204. genTypeInfo(p.module, seqtype, dest.lode.info), length])
  1205. genAssignment(p, dest, call, {})
  1206. proc genNewSeq(p: BProc, e: PNode) =
  1207. var a, b: TLoc
  1208. initLocExpr(p, e.sons[1], a)
  1209. initLocExpr(p, e.sons[2], b)
  1210. if p.config.selectedGC == gcDestructors:
  1211. let seqtype = skipTypes(e.sons[1].typ, abstractVarRange)
  1212. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1213. [a.rdLoc, b.rdLoc, getTypeDesc(p.module, seqtype.lastSon),
  1214. getSeqPayloadType(p.module, seqtype)])
  1215. else:
  1216. let lenIsZero = optNilSeqs notin p.options and
  1217. e[2].kind == nkIntLit and e[2].intVal == 0
  1218. genNewSeqAux(p, a, b.rdLoc, lenIsZero)
  1219. gcUsage(p.config, e)
  1220. proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) =
  1221. let seqtype = skipTypes(e.typ, abstractVarRange)
  1222. var a: TLoc
  1223. initLocExpr(p, e.sons[1], a)
  1224. if p.config.selectedGC == gcDestructors:
  1225. if d.k == locNone: getTemp(p, e.typ, d, needsInit=false)
  1226. linefmt(p, cpsStmts, "$1.len = 0; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1227. [d.rdLoc, a.rdLoc, getTypeDesc(p.module, seqtype.lastSon),
  1228. getSeqPayloadType(p.module, seqtype)])
  1229. else:
  1230. putIntoDest(p, d, e, ropecg(p.module,
  1231. "($1)#nimNewSeqOfCap($2, $3)", [
  1232. getTypeDesc(p.module, seqtype),
  1233. genTypeInfo(p.module, seqtype, e.info), a.rdLoc]))
  1234. gcUsage(p.config, e)
  1235. proc genConstExpr(p: BProc, n: PNode): Rope
  1236. proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  1237. if d.k == locNone and n.len > ord(n.kind == nkObjConstr) and n.isDeepConstExpr:
  1238. let t = n.typ
  1239. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1240. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1241. fillLoc(d, locData, n, p.module.tmpBase & rope(id), OnStatic)
  1242. if id == p.module.labels:
  1243. # expression not found in the cache:
  1244. inc(p.module.labels)
  1245. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  1246. [getTypeDesc(p.module, t), d.r, genConstExpr(p, n)])
  1247. result = true
  1248. else:
  1249. result = false
  1250. proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
  1251. #echo rendertree e, " ", e.isDeepConstExpr
  1252. # inheritance in C++ does not allow struct initialization so
  1253. # we skip this step here:
  1254. if not p.module.compileToCpp:
  1255. if handleConstExpr(p, e, d): return
  1256. var t = e.typ.skipTypes(abstractInstOwned)
  1257. let isRef = t.kind == tyRef
  1258. # check if we need to construct the object in a temporary
  1259. var useTemp =
  1260. isRef or
  1261. (d.k notin {locTemp,locLocalVar,locGlobalVar,locParam,locField}) or
  1262. (isPartOf(d.lode, e) != arNo)
  1263. var tmp: TLoc
  1264. var r: Rope
  1265. if useTemp:
  1266. getTemp(p, t, tmp)
  1267. r = rdLoc(tmp)
  1268. if isRef:
  1269. rawGenNew(p, tmp, nil)
  1270. t = t.lastSon.skipTypes(abstractInstOwned)
  1271. r = "(*$1)" % [r]
  1272. gcUsage(p.config, e)
  1273. else:
  1274. constructLoc(p, tmp)
  1275. else:
  1276. resetLoc(p, d)
  1277. r = rdLoc(d)
  1278. discard getTypeDesc(p.module, t)
  1279. let ty = getUniqueType(t)
  1280. for i in 1 ..< e.len:
  1281. let it = e.sons[i]
  1282. var tmp2: TLoc
  1283. tmp2.r = r
  1284. let field = lookupFieldAgain(p, ty, it.sons[0].sym, tmp2.r)
  1285. if field.loc.r == nil: fillObjectFields(p.module, ty)
  1286. if field.loc.r == nil: internalError(p.config, e.info, "genObjConstr")
  1287. if it.len == 3 and optFieldCheck in p.options:
  1288. genFieldCheck(p, it.sons[2], r, field)
  1289. add(tmp2.r, ".")
  1290. add(tmp2.r, field.loc.r)
  1291. if useTemp:
  1292. tmp2.k = locTemp
  1293. tmp2.storage = if isRef: OnHeap else: OnStack
  1294. else:
  1295. tmp2.k = d.k
  1296. tmp2.storage = if isRef: OnHeap else: d.storage
  1297. tmp2.lode = it.sons[1]
  1298. expr(p, it.sons[1], tmp2)
  1299. if useTemp:
  1300. if d.k == locNone:
  1301. d = tmp
  1302. else:
  1303. genAssignment(p, d, tmp, {})
  1304. proc lhsDoesAlias(a, b: PNode): bool =
  1305. for y in b:
  1306. if isPartOf(a, y) != arNo: return true
  1307. proc genSeqConstr(p: BProc, n: PNode, d: var TLoc) =
  1308. var arr, tmp: TLoc
  1309. # bug #668
  1310. let doesAlias = lhsDoesAlias(d.lode, n)
  1311. let dest = if doesAlias: addr(tmp) else: addr(d)
  1312. if doesAlias:
  1313. getTemp(p, n.typ, tmp)
  1314. elif d.k == locNone:
  1315. getTemp(p, n.typ, d)
  1316. let l = intLiteral(len(n))
  1317. if p.config.selectedGC == gcDestructors:
  1318. let seqtype = n.typ
  1319. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1320. [rdLoc dest[], l, getTypeDesc(p.module, seqtype.lastSon),
  1321. getSeqPayloadType(p.module, seqtype)])
  1322. else:
  1323. # generate call to newSeq before adding the elements per hand:
  1324. genNewSeqAux(p, dest[], l,
  1325. optNilSeqs notin p.options and n.len == 0)
  1326. for i in 0 ..< len(n):
  1327. initLoc(arr, locExpr, n[i], OnHeap)
  1328. arr.r = ropecg(p.module, "$1$3[$2]", [rdLoc(dest[]), intLiteral(i), dataField(p)])
  1329. arr.storage = OnHeap # we know that sequences are on the heap
  1330. expr(p, n[i], arr)
  1331. gcUsage(p.config, n)
  1332. if doesAlias:
  1333. if d.k == locNone:
  1334. d = tmp
  1335. else:
  1336. genAssignment(p, d, tmp, {})
  1337. proc genArrToSeq(p: BProc, n: PNode, d: var TLoc) =
  1338. var elem, a, arr: TLoc
  1339. if n.sons[1].kind == nkBracket:
  1340. n.sons[1].typ = n.typ
  1341. genSeqConstr(p, n.sons[1], d)
  1342. return
  1343. if d.k == locNone:
  1344. getTemp(p, n.typ, d)
  1345. # generate call to newSeq before adding the elements per hand:
  1346. let L = toInt(lengthOrd(p.config, n.sons[1].typ))
  1347. if p.config.selectedGC == gcDestructors:
  1348. let seqtype = n.typ
  1349. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1350. [rdLoc d, L, getTypeDesc(p.module, seqtype.lastSon),
  1351. getSeqPayloadType(p.module, seqtype)])
  1352. else:
  1353. genNewSeqAux(p, d, intLiteral(L), optNilSeqs notin p.options and L == 0)
  1354. initLocExpr(p, n.sons[1], a)
  1355. # bug #5007; do not produce excessive C source code:
  1356. if L < 10:
  1357. for i in 0 ..< L:
  1358. initLoc(elem, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1359. elem.r = ropecg(p.module, "$1$3[$2]", [rdLoc(d), intLiteral(i), dataField(p)])
  1360. elem.storage = OnHeap # we know that sequences are on the heap
  1361. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.sons[1].typ, abstractInst)), a.storage)
  1362. arr.r = ropecg(p.module, "$1[$2]", [rdLoc(a), intLiteral(i)])
  1363. genAssignment(p, elem, arr, {needToCopy})
  1364. else:
  1365. var i: TLoc
  1366. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), i)
  1367. linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n", [i.r, L])
  1368. initLoc(elem, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1369. elem.r = ropecg(p.module, "$1$3[$2]", [rdLoc(d), rdLoc(i), dataField(p)])
  1370. elem.storage = OnHeap # we know that sequences are on the heap
  1371. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.sons[1].typ, abstractInst)), a.storage)
  1372. arr.r = ropecg(p.module, "$1[$2]", [rdLoc(a), rdLoc(i)])
  1373. genAssignment(p, elem, arr, {needToCopy})
  1374. lineF(p, cpsStmts, "}$n", [])
  1375. proc genNewFinalize(p: BProc, e: PNode) =
  1376. var
  1377. a, b, f: TLoc
  1378. refType, bt: PType
  1379. ti: Rope
  1380. refType = skipTypes(e.sons[1].typ, abstractVarRange)
  1381. initLocExpr(p, e.sons[1], a)
  1382. initLocExpr(p, e.sons[2], f)
  1383. initLoc(b, locExpr, a.lode, OnHeap)
  1384. ti = genTypeInfo(p.module, refType, e.info)
  1385. addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1386. b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
  1387. getTypeDesc(p.module, refType),
  1388. ti, getTypeDesc(p.module, skipTypes(refType.lastSon, abstractRange))])
  1389. genAssignment(p, a, b, {}) # set the object type:
  1390. bt = skipTypes(refType.lastSon, abstractRange)
  1391. genObjectInit(p, cpsStmts, bt, a, false)
  1392. gcUsage(p.config, e)
  1393. proc genOfHelper(p: BProc; dest: PType; a: Rope; info: TLineInfo): Rope =
  1394. if optTinyRtti in p.config.globalOptions:
  1395. result = ropecg(p.module, "#isObj($1.m_type, $2)",
  1396. [a, genTypeInfo2Name(p.module, dest)])
  1397. else:
  1398. # unfortunately 'genTypeInfo' sets tfObjHasKids as a side effect, so we
  1399. # have to call it here first:
  1400. let ti = genTypeInfo(p.module, dest, info)
  1401. if tfFinal in dest.flags or (objHasKidsValid in p.module.flags and
  1402. tfObjHasKids notin dest.flags):
  1403. result = "$1.m_type == $2" % [a, ti]
  1404. else:
  1405. discard cgsym(p.module, "TNimType")
  1406. inc p.module.labels
  1407. let cache = "Nim_OfCheck_CACHE" & p.module.labels.rope
  1408. addf(p.module.s[cfsVars], "static TNimType* $#[2];$n", [cache])
  1409. result = ropecg(p.module, "#isObjWithCache($#.m_type, $#, $#)", [a, ti, cache])
  1410. when false:
  1411. # former version:
  1412. result = ropecg(p.module, "#isObj($1.m_type, $2)",
  1413. [a, genTypeInfo(p.module, dest, info)])
  1414. proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  1415. var a: TLoc
  1416. initLocExpr(p, x, a)
  1417. var dest = skipTypes(typ, typedescPtrs)
  1418. var r = rdLoc(a)
  1419. var nilCheck: Rope = nil
  1420. var t = skipTypes(a.t, abstractInstOwned)
  1421. while t.kind in {tyVar, tyLent, tyPtr, tyRef}:
  1422. if t.kind notin {tyVar, tyLent}: nilCheck = r
  1423. if t.kind notin {tyVar, tyLent} or not p.module.compileToCpp:
  1424. r = ropecg(p.module, "(*$1)", [r])
  1425. t = skipTypes(t.lastSon, typedescInst+{tyOwned})
  1426. discard getTypeDesc(p.module, t)
  1427. if not p.module.compileToCpp:
  1428. while t.kind == tyObject and t.sons[0] != nil:
  1429. add(r, ~".Sup")
  1430. t = skipTypes(t.sons[0], skipPtrs)
  1431. if isObjLackingTypeField(t):
  1432. globalError(p.config, x.info,
  1433. "no 'of' operator available for pure objects")
  1434. if nilCheck != nil:
  1435. r = ropecg(p.module, "(($1) && ($2))", [nilCheck, genOfHelper(p, dest, r, x.info)])
  1436. else:
  1437. r = ropecg(p.module, "($1)", [genOfHelper(p, dest, r, x.info)])
  1438. putIntoDest(p, d, x, r, a.storage)
  1439. proc genOf(p: BProc, n: PNode, d: var TLoc) =
  1440. genOf(p, n.sons[1], n.sons[2].typ, d)
  1441. proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  1442. if optTinyRtti in p.config.globalOptions:
  1443. localError(p.config, e.info, "'repr' is not available for --newruntime")
  1444. var a: TLoc
  1445. initLocExpr(p, e.sons[1], a)
  1446. var t = skipTypes(e.sons[1].typ, abstractVarRange)
  1447. case t.kind
  1448. of tyInt..tyInt64, tyUInt..tyUInt64:
  1449. putIntoDest(p, d, e,
  1450. ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]), a.storage)
  1451. of tyFloat..tyFloat128:
  1452. putIntoDest(p, d, e, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]), a.storage)
  1453. of tyBool:
  1454. putIntoDest(p, d, e, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]), a.storage)
  1455. of tyChar:
  1456. putIntoDest(p, d, e, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]), a.storage)
  1457. of tyEnum, tyOrdinal:
  1458. putIntoDest(p, d, e,
  1459. ropecg(p.module, "#reprEnum((NI)$1, $2)", [
  1460. rdLoc(a), genTypeInfo(p.module, t, e.info)]), a.storage)
  1461. of tyString:
  1462. putIntoDest(p, d, e, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]), a.storage)
  1463. of tySet:
  1464. putIntoDest(p, d, e, ropecg(p.module, "#reprSet($1, $2)", [
  1465. addrLoc(p.config, a), genTypeInfo(p.module, t, e.info)]), a.storage)
  1466. of tyOpenArray, tyVarargs:
  1467. var b: TLoc
  1468. case skipTypes(a.t, abstractVarRange).kind
  1469. of tyOpenArray, tyVarargs:
  1470. putIntoDest(p, b, e, "$1, $1Len_0" % [rdLoc(a)], a.storage)
  1471. of tyString, tySequence:
  1472. putIntoDest(p, b, e,
  1473. "$1$3, $2" % [rdLoc(a), lenExpr(p, a), dataField(p)], a.storage)
  1474. of tyArray:
  1475. putIntoDest(p, b, e,
  1476. "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))], a.storage)
  1477. else: internalError(p.config, e.sons[0].info, "genRepr()")
  1478. putIntoDest(p, d, e,
  1479. ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
  1480. genTypeInfo(p.module, elemType(t), e.info)]), a.storage)
  1481. of tyCString, tyArray, tyRef, tyPtr, tyPointer, tyNil, tySequence:
  1482. putIntoDest(p, d, e,
  1483. ropecg(p.module, "#reprAny($1, $2)", [
  1484. rdLoc(a), genTypeInfo(p.module, t, e.info)]), a.storage)
  1485. of tyEmpty, tyVoid:
  1486. localError(p.config, e.info, "'repr' doesn't support 'void' type")
  1487. else:
  1488. putIntoDest(p, d, e, ropecg(p.module, "#reprAny($1, $2)",
  1489. [addrLoc(p.config, a), genTypeInfo(p.module, t, e.info)]),
  1490. a.storage)
  1491. gcUsage(p.config, e)
  1492. proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  1493. let t = e.sons[1].typ
  1494. putIntoDest(p, d, e, genTypeInfo(p.module, t, e.info))
  1495. template genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  1496. var a: TLoc
  1497. initLocExpr(p, n.sons[1], a)
  1498. a.r = ropecg(p.module, frmt, [rdLoc(a)])
  1499. a.flags = a.flags - {lfIndirect} # this flag should not be propagated here (not just for HCR)
  1500. if d.k == locNone: getTemp(p, n.typ, d)
  1501. genAssignment(p, d, a, {})
  1502. gcUsage(p.config, n)
  1503. proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1504. var a = e.sons[1]
  1505. if a.kind == nkHiddenAddr: a = a.sons[0]
  1506. var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
  1507. case typ.kind
  1508. of tyOpenArray, tyVarargs:
  1509. # Bug #9279, len(toOpenArray()) has to work:
  1510. if a.kind in nkCallKinds and a[0].kind == nkSym and a[0].sym.magic == mSlice:
  1511. # magic: pass slice to openArray:
  1512. var b, c: TLoc
  1513. initLocExpr(p, a[2], b)
  1514. initLocExpr(p, a[3], c)
  1515. if op == mHigh:
  1516. putIntoDest(p, d, e, ropecg(p.module, "($2)-($1)", [rdLoc(b), rdLoc(c)]))
  1517. else:
  1518. putIntoDest(p, d, e, ropecg(p.module, "($2)-($1)+1", [rdLoc(b), rdLoc(c)]))
  1519. else:
  1520. if op == mHigh: unaryExpr(p, e, d, "($1Len_0-1)")
  1521. else: unaryExpr(p, e, d, "$1Len_0")
  1522. of tyCString:
  1523. if op == mHigh: unaryExpr(p, e, d, "($1 ? (#nimCStrLen($1)-1) : -1)")
  1524. else: unaryExpr(p, e, d, "($1 ? #nimCStrLen($1) : 0)")
  1525. of tyString:
  1526. var a: TLoc
  1527. initLocExpr(p, e.sons[1], a)
  1528. var x = lenExpr(p, a)
  1529. if op == mHigh: x = "($1-1)" % [x]
  1530. putIntoDest(p, d, e, x)
  1531. of tySequence:
  1532. # we go through a temporary here because people write bullshit code.
  1533. var a, tmp: TLoc
  1534. initLocExpr(p, e[1], a)
  1535. getIntTemp(p, tmp)
  1536. var x = lenExpr(p, a)
  1537. if op == mHigh: x = "($1-1)" % [x]
  1538. lineCg(p, cpsStmts, "$1 = $2;$n", [tmp.r, x])
  1539. putIntoDest(p, d, e, tmp.r)
  1540. of tyArray:
  1541. # YYY: length(sideeffect) is optimized away incorrectly?
  1542. if op == mHigh: putIntoDest(p, d, e, rope(lastOrd(p.config, typ)))
  1543. else: putIntoDest(p, d, e, rope(lengthOrd(p.config, typ)))
  1544. else: internalError(p.config, e.info, "genArrayLen()")
  1545. proc makePtrType(baseType: PType): PType =
  1546. result = newType(tyPtr, baseType.owner)
  1547. addSonSkipIntLit(result, baseType)
  1548. proc makeAddr(n: PNode): PNode =
  1549. if n.kind == nkHiddenAddr:
  1550. result = n
  1551. else:
  1552. result = newTree(nkHiddenAddr, n)
  1553. result.typ = makePtrType(n.typ)
  1554. proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  1555. if p.config.selectedGC == gcDestructors:
  1556. e.sons[1] = makeAddr(e[1])
  1557. genCall(p, e, d)
  1558. return
  1559. var a, b, call: TLoc
  1560. assert(d.k == locNone)
  1561. var x = e.sons[1]
  1562. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  1563. initLocExpr(p, x, a)
  1564. initLocExpr(p, e.sons[2], b)
  1565. let t = skipTypes(e.sons[1].typ, {tyVar})
  1566. initLoc(call, locCall, e, OnHeap)
  1567. if not p.module.compileToCpp:
  1568. const setLenPattern = "($3) #setLengthSeqV2(&($1)->Sup, $4, $2)"
  1569. call.r = ropecg(p.module, setLenPattern, [
  1570. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1571. genTypeInfo(p.module, t.skipTypes(abstractInst), e.info)])
  1572. else:
  1573. const setLenPattern = "($3) #setLengthSeqV2($1, $4, $2)"
  1574. call.r = ropecg(p.module, setLenPattern, [
  1575. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1576. genTypeInfo(p.module, t.skipTypes(abstractInst), e.info)])
  1577. genAssignment(p, a, call, {})
  1578. gcUsage(p.config, e)
  1579. proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  1580. if p.config.selectedGC == gcDestructors:
  1581. binaryStmtAddr(p, e, d, "setLengthStrV2")
  1582. else:
  1583. var a, b, call: TLoc
  1584. if d.k != locNone: internalError(p.config, e.info, "genSetLengthStr")
  1585. initLocExpr(p, e.sons[1], a)
  1586. initLocExpr(p, e.sons[2], b)
  1587. initLoc(call, locCall, e, OnHeap)
  1588. call.r = ropecg(p.module, "#setLengthStr($1, $2)", [
  1589. rdLoc(a), rdLoc(b)])
  1590. genAssignment(p, a, call, {})
  1591. gcUsage(p.config, e)
  1592. proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  1593. # swap(a, b) -->
  1594. # temp = a
  1595. # a = b
  1596. # b = temp
  1597. var a, b, tmp: TLoc
  1598. getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp)
  1599. initLocExpr(p, e.sons[1], a) # eval a
  1600. initLocExpr(p, e.sons[2], b) # eval b
  1601. genAssignment(p, tmp, a, {})
  1602. genAssignment(p, a, b, {})
  1603. genAssignment(p, b, tmp, {})
  1604. proc rdSetElemLoc(conf: ConfigRef; a: TLoc, typ: PType): Rope =
  1605. # read a location of an set element; it may need a subtraction operation
  1606. # before the set operation
  1607. result = rdCharLoc(a)
  1608. let setType = typ.skipTypes(abstractPtrs)
  1609. assert(setType.kind == tySet)
  1610. if firstOrd(conf, setType) != 0:
  1611. result = "($1- $2)" % [result, rope(firstOrd(conf, setType))]
  1612. proc fewCmps(conf: ConfigRef; s: PNode): bool =
  1613. # this function estimates whether it is better to emit code
  1614. # for constructing the set or generating a bunch of comparisons directly
  1615. if s.kind != nkCurly: return false
  1616. if (getSize(conf, s.typ) <= conf.target.intSize) and (nfAllConst in s.flags):
  1617. result = false # it is better to emit the set generation code
  1618. elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
  1619. result = true # better not emit the set if int is basetype!
  1620. else:
  1621. result = len(s) <= 8 # 8 seems to be a good value
  1622. template binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  1623. putIntoDest(p, d, e, frmt % [rdLoc(a), rdSetElemLoc(p.config, b, a.t)])
  1624. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  1625. case int(getSize(p.config, skipTypes(e.sons[1].typ, abstractVar)))
  1626. of 1: binaryExprIn(p, e, a, b, d, "(($1 &((NU8)1<<((NU)($2)&7U)))!=0)")
  1627. of 2: binaryExprIn(p, e, a, b, d, "(($1 &((NU16)1<<((NU)($2)&15U)))!=0)")
  1628. of 4: binaryExprIn(p, e, a, b, d, "(($1 &((NU32)1<<((NU)($2)&31U)))!=0)")
  1629. of 8: binaryExprIn(p, e, a, b, d, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)")
  1630. else: binaryExprIn(p, e, a, b, d, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)")
  1631. template binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  1632. var a, b: TLoc
  1633. assert(d.k == locNone)
  1634. initLocExpr(p, e.sons[1], a)
  1635. initLocExpr(p, e.sons[2], b)
  1636. lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(p.config, b, a.t)])
  1637. proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  1638. var a, b, x, y: TLoc
  1639. if (e.sons[1].kind == nkCurly) and fewCmps(p.config, e.sons[1]):
  1640. # a set constructor but not a constant set:
  1641. # do not emit the set, but generate a bunch of comparisons; and if we do
  1642. # so, we skip the unnecessary range check: This is a semantical extension
  1643. # that code now relies on. :-/ XXX
  1644. let ea = if e.sons[2].kind in {nkChckRange, nkChckRange64}:
  1645. e.sons[2].sons[0]
  1646. else:
  1647. e.sons[2]
  1648. initLocExpr(p, ea, a)
  1649. initLoc(b, locExpr, e, OnUnknown)
  1650. var length = len(e.sons[1])
  1651. if length > 0:
  1652. b.r = rope("(")
  1653. for i in 0 ..< length:
  1654. let it = e.sons[1].sons[i]
  1655. if it.kind == nkRange:
  1656. initLocExpr(p, it.sons[0], x)
  1657. initLocExpr(p, it.sons[1], y)
  1658. addf(b.r, "$1 >= $2 && $1 <= $3",
  1659. [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
  1660. else:
  1661. initLocExpr(p, it, x)
  1662. addf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
  1663. if i < length - 1: add(b.r, " || ")
  1664. add(b.r, ")")
  1665. else:
  1666. # handle the case of an empty set
  1667. b.r = rope("0")
  1668. putIntoDest(p, d, e, b.r)
  1669. else:
  1670. assert(e.sons[1].typ != nil)
  1671. assert(e.sons[2].typ != nil)
  1672. initLocExpr(p, e.sons[1], a)
  1673. initLocExpr(p, e.sons[2], b)
  1674. genInExprAux(p, e, a, b, d)
  1675. proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1676. const
  1677. lookupOpr: array[mLeSet..mSymDiffSet, string] = [
  1678. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1679. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1680. " if (!$3) break;}$n",
  1681. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1682. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1683. " if (!$3) break;}$n" &
  1684. "if ($3) $3 = (#nimCmpMem($4, $5, $2) != 0);$n",
  1685. "&",
  1686. "|",
  1687. "& ~",
  1688. "^"]
  1689. var a, b, i: TLoc
  1690. var setType = skipTypes(e.sons[1].typ, abstractVar)
  1691. var size = int(getSize(p.config, setType))
  1692. case size
  1693. of 1, 2, 4, 8:
  1694. case op
  1695. of mIncl:
  1696. case size
  1697. of 1: binaryStmtInExcl(p, e, d, "$1 |= ((NU8)1)<<(($2) & 7);$n")
  1698. of 2: binaryStmtInExcl(p, e, d, "$1 |= ((NU16)1)<<(($2) & 15);$n")
  1699. of 4: binaryStmtInExcl(p, e, d, "$1 |= ((NU32)1)<<(($2) & 31);$n")
  1700. of 8: binaryStmtInExcl(p, e, d, "$1 |= ((NU64)1)<<(($2) & 63);$n")
  1701. else: assert(false, $size)
  1702. of mExcl:
  1703. case size
  1704. of 1: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU8)1) << (($2) & 7));$n")
  1705. of 2: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU16)1) << (($2) & 15));$n")
  1706. of 4: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU32)1) << (($2) & 31));$n")
  1707. of 8: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU64)1) << (($2) & 63));$n")
  1708. else: assert(false, $size)
  1709. of mCard:
  1710. if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
  1711. else: unaryExprChar(p, e, d, "#countBits64($1)")
  1712. of mLtSet: binaryExprChar(p, e, d, "((($1 & ~ $2)==0)&&($1 != $2))")
  1713. of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
  1714. of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
  1715. of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
  1716. of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
  1717. of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
  1718. of mSymDiffSet: binaryExpr(p, e, d, "($1 ^ $2)")
  1719. of mInSet:
  1720. genInOp(p, e, d)
  1721. else: internalError(p.config, e.info, "genSetOp()")
  1722. else:
  1723. case op
  1724. of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n")
  1725. of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n")
  1726. of mCard:
  1727. var a: TLoc
  1728. initLocExpr(p, e.sons[1], a)
  1729. putIntoDest(p, d, e, ropecg(p.module, "#cardSet($1, $2)", [rdCharLoc(a), size]))
  1730. of mLtSet, mLeSet:
  1731. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), i) # our counter
  1732. initLocExpr(p, e.sons[1], a)
  1733. initLocExpr(p, e.sons[2], b)
  1734. if d.k == locNone: getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyBool), d)
  1735. if op == mLtSet:
  1736. linefmt(p, cpsStmts, lookupOpr[mLtSet],
  1737. [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)])
  1738. else:
  1739. linefmt(p, cpsStmts, lookupOpr[mLeSet],
  1740. [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)])
  1741. of mEqSet:
  1742. var a, b: TLoc
  1743. assert(e.sons[1].typ != nil)
  1744. assert(e.sons[2].typ != nil)
  1745. initLocExpr(p, e.sons[1], a)
  1746. initLocExpr(p, e.sons[2], b)
  1747. putIntoDest(p, d, e, ropecg(p.module, "(#nimCmpMem($1, $2, $3)==0)", [a.rdCharLoc, b.rdCharLoc, size]))
  1748. of mMulSet, mPlusSet, mMinusSet, mSymDiffSet:
  1749. # we inline the simple for loop for better code generation:
  1750. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), i) # our counter
  1751. initLocExpr(p, e.sons[1], a)
  1752. initLocExpr(p, e.sons[2], b)
  1753. if d.k == locNone: getTemp(p, setType, d)
  1754. lineF(p, cpsStmts,
  1755. "for ($1 = 0; $1 < $2; $1++) $n" &
  1756. " $3[$1] = $4[$1] $6 $5[$1];$n", [
  1757. rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b),
  1758. rope(lookupOpr[op])])
  1759. of mInSet: genInOp(p, e, d)
  1760. else: internalError(p.config, e.info, "genSetOp")
  1761. proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  1762. unaryExprChar(p, e, d, "$1")
  1763. proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
  1764. const
  1765. ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs, tyUncheckedArray}
  1766. # we use whatever C gives us. Except if we have a value-type, we need to go
  1767. # through its address:
  1768. var a: TLoc
  1769. initLocExpr(p, e.sons[1], a)
  1770. let etyp = skipTypes(e.typ, abstractRange+{tyOwned})
  1771. let srcTyp = skipTypes(e.sons[1].typ, abstractRange)
  1772. if etyp.kind in ValueTypes and lfIndirect notin a.flags:
  1773. putIntoDest(p, d, e, "(*($1*) ($2))" %
  1774. [getTypeDesc(p.module, e.typ), addrLoc(p.config, a)], a.storage)
  1775. elif etyp.kind == tyProc and etyp.callConv == ccClosure and srcTyp.callConv != ccClosure:
  1776. putIntoDest(p, d, e, "(($1) ($2))" %
  1777. [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)], a.storage)
  1778. else:
  1779. # C++ does not like direct casts from pointer to shorter integral types
  1780. if srcTyp.kind in {tyPtr, tyPointer} and etyp.kind in IntegralTypes:
  1781. putIntoDest(p, d, e, "(($1) (ptrdiff_t) ($2))" %
  1782. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1783. elif p.config.selectedGC == gcDestructors and etyp.kind in {tySequence, tyString}:
  1784. putIntoDest(p, d, e, "(*($1*) (&$2))" %
  1785. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1786. else:
  1787. putIntoDest(p, d, e, "(($1) ($2))" %
  1788. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1789. proc genCast(p: BProc, e: PNode, d: var TLoc) =
  1790. const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  1791. let
  1792. destt = skipTypes(e.typ, abstractRange)
  1793. srct = skipTypes(e.sons[1].typ, abstractRange)
  1794. if destt.kind in ValueTypes or srct.kind in ValueTypes:
  1795. # 'cast' and some float type involved? --> use a union.
  1796. inc(p.labels)
  1797. var lbl = p.labels.rope
  1798. var tmp: TLoc
  1799. tmp.r = "LOC$1.source" % [lbl]
  1800. linefmt(p, cpsLocals, "union { $1 source; $2 dest; } LOC$3;$n",
  1801. [getTypeDesc(p.module, e.sons[1].typ), getTypeDesc(p.module, e.typ), lbl])
  1802. tmp.k = locExpr
  1803. tmp.lode = lodeTyp srct
  1804. tmp.storage = OnStack
  1805. tmp.flags = {}
  1806. expr(p, e.sons[1], tmp)
  1807. putIntoDest(p, d, e, "LOC$#.dest" % [lbl], tmp.storage)
  1808. else:
  1809. # I prefer the shorter cast version for pointer types -> generate less
  1810. # C code; plus it's the right thing to do for closures:
  1811. genSomeCast(p, e, d)
  1812. proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) =
  1813. var a: TLoc
  1814. var dest = skipTypes(n.typ, abstractVar)
  1815. if optRangeCheck notin p.options or (dest.kind in {tyUInt..tyUInt64} and
  1816. checkUnsignedConversions notin p.config.legacyFeatures):
  1817. initLocExpr(p, n.sons[0], a)
  1818. putIntoDest(p, d, n, "(($1) ($2))" %
  1819. [getTypeDesc(p.module, dest), rdCharLoc(a)], a.storage)
  1820. else:
  1821. let mm = if dest.kind in {tyUInt32, tyUInt64, tyUInt}: "chckRangeU" else: magic
  1822. initLocExpr(p, n.sons[0], a)
  1823. putIntoDest(p, d, lodeTyp dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [
  1824. getTypeDesc(p.module, dest), rdCharLoc(a),
  1825. genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest),
  1826. mm]), a.storage)
  1827. proc genConv(p: BProc, e: PNode, d: var TLoc) =
  1828. let destType = e.typ.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink})
  1829. if sameBackendType(destType, e.sons[1].typ):
  1830. expr(p, e.sons[1], d)
  1831. else:
  1832. genSomeCast(p, e, d)
  1833. proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  1834. var a: TLoc
  1835. initLocExpr(p, n.sons[0], a)
  1836. putIntoDest(p, d, n,
  1837. ropecg(p.module, "#nimToCStringConv($1)", [rdLoc(a)]),
  1838. # "($1 ? $1->data : (NCSTRING)\"\")" % [a.rdLoc],
  1839. a.storage)
  1840. proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  1841. var a: TLoc
  1842. initLocExpr(p, n.sons[0], a)
  1843. putIntoDest(p, d, n,
  1844. ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]),
  1845. a.storage)
  1846. gcUsage(p.config, n)
  1847. proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  1848. var x: TLoc
  1849. var a = e.sons[1]
  1850. var b = e.sons[2]
  1851. if a.kind in {nkStrLit..nkTripleStrLit} and a.strVal == "":
  1852. initLocExpr(p, e.sons[2], x)
  1853. putIntoDest(p, d, e,
  1854. ropecg(p.module, "($1 == 0)", [lenExpr(p, x)]))
  1855. elif b.kind in {nkStrLit..nkTripleStrLit} and b.strVal == "":
  1856. initLocExpr(p, e.sons[1], x)
  1857. putIntoDest(p, d, e,
  1858. ropecg(p.module, "($1 == 0)", [lenExpr(p, x)]))
  1859. else:
  1860. binaryExpr(p, e, d, "#eqStrings($1, $2)")
  1861. proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  1862. if {optNaNCheck, optInfCheck} * p.options != {}:
  1863. const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
  1864. var a, b: TLoc
  1865. assert(e.sons[1].typ != nil)
  1866. assert(e.sons[2].typ != nil)
  1867. initLocExpr(p, e.sons[1], a)
  1868. initLocExpr(p, e.sons[2], b)
  1869. putIntoDest(p, d, e, ropecg(p.module, "(($4)($2) $1 ($4)($3))",
  1870. [opr[m], rdLoc(a), rdLoc(b),
  1871. getSimpleTypeDesc(p.module, e[1].typ)]))
  1872. if optNaNCheck in p.options:
  1873. linefmt(p, cpsStmts, "#nanCheck($1);$n", [rdLoc(d)])
  1874. if optInfCheck in p.options:
  1875. linefmt(p, cpsStmts, "#infCheck($1);$n", [rdLoc(d)])
  1876. else:
  1877. binaryArith(p, e, d, m)
  1878. proc skipAddr(n: PNode): PNode =
  1879. result = if n.kind in {nkAddr, nkHiddenAddr}: n[0] else: n
  1880. proc genWasMoved(p: BProc; n: PNode) =
  1881. var a: TLoc
  1882. initLocExpr(p, n[1].skipAddr, a)
  1883. resetLoc(p, a)
  1884. #linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  1885. # [addrLoc(p.config, a), getTypeDesc(p.module, a.t)])
  1886. proc genMove(p: BProc; n: PNode; d: var TLoc) =
  1887. var a: TLoc
  1888. initLocExpr(p, n[1].skipAddr, a)
  1889. if n.len == 4:
  1890. # generated by liftdestructors:
  1891. var src: TLoc
  1892. initLocExpr(p, n[2], src)
  1893. linefmt(p, cpsStmts, "if ($1.len && $1.p != $2.p) {", [rdLoc(a), rdLoc(src)])
  1894. genStmts(p, n[3])
  1895. linefmt(p, cpsStmts, "}$n$1.len = $2.len; $1.p = $2.p;$n", [rdLoc(a), rdLoc(src)])
  1896. else:
  1897. if d.k == locNone: getTemp(p, n.typ, d)
  1898. genAssignment(p, d, a, {})
  1899. resetLoc(p, a)
  1900. proc genDestroy(p: BProc; n: PNode) =
  1901. if p.config.selectedGC == gcDestructors:
  1902. let arg = n[1].skipAddr
  1903. let t = arg.typ.skipTypes(abstractInst)
  1904. case t.kind
  1905. of tyString:
  1906. var a: TLoc
  1907. initLocExpr(p, arg, a)
  1908. linefmt(p, cpsStmts, "if ($1.p && $1.p->allocator) {$n" &
  1909. " $1.p->allocator->dealloc($1.p->allocator, $1.p, $1.p->cap + 1 + sizeof(NI) + sizeof(void*)); }$n",
  1910. [rdLoc(a)])
  1911. of tySequence:
  1912. var a: TLoc
  1913. initLocExpr(p, arg, a)
  1914. linefmt(p, cpsStmts, "if ($1.p && $1.p->allocator) {$n" &
  1915. " $1.p->allocator->dealloc($1.p->allocator, $1.p, ($1.p->cap * sizeof($2)) + sizeof(NI) + sizeof(void*)); }$n",
  1916. [rdLoc(a), getTypeDesc(p.module, t.lastSon)])
  1917. else: discard "nothing to do"
  1918. else:
  1919. let t = n[1].typ.skipTypes(abstractVar)
  1920. if t.destructor != nil and t.destructor.ast[bodyPos].len != 0:
  1921. internalError(p.config, n.info, "destructor turned out to be not trivial")
  1922. discard "ignore calls to the default destructor"
  1923. proc genDispose(p: BProc; n: PNode) =
  1924. when false:
  1925. let elemType = n[1].typ.skipTypes(abstractVar).lastSon
  1926. var a: TLoc
  1927. initLocExpr(p, n[1].skipAddr, a)
  1928. if isFinal(elemType):
  1929. if elemType.destructor != nil:
  1930. var destroyCall = newNodeI(nkCall, n.info)
  1931. genStmts(p, destroyCall)
  1932. lineCg(p, cpsStmts, ["#nimRawDispose($#)", rdLoc(a)])
  1933. else:
  1934. # ``nimRawDisposeVirtual`` calls the ``finalizer`` which is the same as the
  1935. # destructor, but it uses the runtime type. Afterwards the memory is freed:
  1936. lineCg(p, cpsStmts, ["#nimDestroyAndDispose($#)", rdLoc(a)])
  1937. proc genEnumToStr(p: BProc, e: PNode, d: var TLoc) =
  1938. const ToStringProcSlot = -4
  1939. let t = e[1].typ.skipTypes(abstractInst)
  1940. var toStrProc: PSym = nil
  1941. for idx, p in items(t.methods):
  1942. if idx == ToStringProcSlot:
  1943. toStrProc = p
  1944. break
  1945. if toStrProc == nil:
  1946. toStrProc = genEnumToStrProc(t, e.info, p.module.g.graph)
  1947. t.methods.add((ToStringProcSlot, toStrProc))
  1948. var n = copyTree(e)
  1949. n[0] = newSymNode(toStrProc)
  1950. expr(p, n, d)
  1951. proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1952. case op
  1953. of mOr, mAnd: genAndOr(p, e, d, op)
  1954. of mNot..mUnaryMinusF64: unaryArith(p, e, d, op)
  1955. of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  1956. of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  1957. of mShrI..mXor: binaryArith(p, e, d, op)
  1958. of mEqProc: genEqProc(p, e, d)
  1959. of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  1960. of mRepr: genRepr(p, e, d)
  1961. of mGetTypeInfo: genGetTypeInfo(p, e, d)
  1962. of mSwap: genSwap(p, e, d)
  1963. of mUnaryLt:
  1964. if optOverflowCheck notin p.options: unaryExpr(p, e, d, "($1 - 1)")
  1965. else: unaryExpr(p, e, d, "#subInt($1, 1)")
  1966. of mInc, mDec:
  1967. const opr: array[mInc..mDec, string] = ["+=", "-="]
  1968. const fun64: array[mInc..mDec, string] = ["addInt64",
  1969. "subInt64"]
  1970. const fun: array[mInc..mDec, string] = ["addInt",
  1971. "subInt"]
  1972. let underlying = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent, tyRange})
  1973. if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
  1974. binaryStmt(p, e, d, opr[op])
  1975. else:
  1976. var a, b: TLoc
  1977. assert(e.sons[1].typ != nil)
  1978. assert(e.sons[2].typ != nil)
  1979. initLocExpr(p, e.sons[1], a)
  1980. initLocExpr(p, e.sons[2], b)
  1981. let ranged = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent})
  1982. let res = binaryArithOverflowRaw(p, ranged, a, b,
  1983. if underlying.kind == tyInt64: fun64[op] else: fun[op])
  1984. putIntoDest(p, a, e.sons[1], "($#)($#)" % [
  1985. getTypeDesc(p.module, ranged), res])
  1986. of mConStrStr: genStrConcat(p, e, d)
  1987. of mAppendStrCh:
  1988. if p.config.selectedGC == gcDestructors:
  1989. binaryStmtAddr(p, e, d, "nimAddCharV1")
  1990. else:
  1991. var dest, b, call: TLoc
  1992. initLoc(call, locCall, e, OnHeap)
  1993. initLocExpr(p, e.sons[1], dest)
  1994. initLocExpr(p, e.sons[2], b)
  1995. call.r = ropecg(p.module, "#addChar($1, $2)", [rdLoc(dest), rdLoc(b)])
  1996. genAssignment(p, dest, call, {})
  1997. of mAppendStrStr: genStrAppend(p, e, d)
  1998. of mAppendSeqElem:
  1999. if p.config.selectedGC == gcDestructors:
  2000. e.sons[1] = makeAddr(e[1])
  2001. genCall(p, e, d)
  2002. else:
  2003. genSeqElemAppend(p, e, d)
  2004. of mEqStr: genStrEquals(p, e, d)
  2005. of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  2006. of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  2007. of mIsNil: genIsNil(p, e, d)
  2008. of mIntToStr: genDollar(p, e, d, "#nimIntToStr($1)")
  2009. of mInt64ToStr: genDollar(p, e, d, "#nimInt64ToStr($1)")
  2010. of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  2011. of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  2012. of mFloatToStr: genDollar(p, e, d, "#nimFloatToStr($1)")
  2013. of mCStrToStr: genDollar(p, e, d, "#cstrToNimstr($1)")
  2014. of mStrToStr, mUnown: expr(p, e.sons[1], d)
  2015. of mEnumToStr:
  2016. if optTinyRtti in p.config.globalOptions:
  2017. genEnumToStr(p, e, d)
  2018. else:
  2019. genRepr(p, e, d)
  2020. of mOf: genOf(p, e, d)
  2021. of mNew: genNew(p, e)
  2022. of mNewFinalize: genNewFinalize(p, e)
  2023. of mNewSeq: genNewSeq(p, e)
  2024. of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  2025. of mSizeOf:
  2026. let t = e.sons[1].typ.skipTypes({tyTypeDesc})
  2027. putIntoDest(p, d, e, "((NI)sizeof($1))" % [getTypeDesc(p.module, t)])
  2028. of mAlignOf:
  2029. let t = e.sons[1].typ.skipTypes({tyTypeDesc})
  2030. if not p.module.compileToCpp:
  2031. p.module.includeHeader("<stdalign.h>")
  2032. putIntoDest(p, d, e, "((NI)alignof($1))" % [getTypeDesc(p.module, t)])
  2033. of mOffsetOf:
  2034. var dotExpr: PNode
  2035. block findDotExpr:
  2036. if e[1].kind == nkDotExpr:
  2037. dotExpr = e[1]
  2038. elif e[1].kind == nkCheckedFieldExpr:
  2039. dotExpr = e[1][0]
  2040. else:
  2041. internalError(p.config, e.info, "unknown ast")
  2042. let t = dotExpr[0].typ.skipTypes({tyTypeDesc})
  2043. let member =
  2044. if t.kind == tyTuple:
  2045. "Field" & rope(dotExpr[1].sym.position)
  2046. else:
  2047. rope(dotExpr[1].sym.name.s)
  2048. putIntoDest(p,d,e, "((NI)offsetof($1, $2))" % [getTypeDesc(p.module, t), member])
  2049. of mChr: genSomeCast(p, e, d)
  2050. of mOrd: genOrd(p, e, d)
  2051. of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
  2052. genArrayLen(p, e, d, op)
  2053. of mXLenStr:
  2054. if not p.module.compileToCpp:
  2055. unaryExpr(p, e, d, "($1->Sup.len)")
  2056. else:
  2057. unaryExpr(p, e, d, "$1->len")
  2058. of mXLenSeq:
  2059. # see 'taddhigh.nim' for why we need to use a temporary here:
  2060. var a, tmp: TLoc
  2061. initLocExpr(p, e[1], a)
  2062. getIntTemp(p, tmp)
  2063. if not p.module.compileToCpp:
  2064. lineCg(p, cpsStmts, "$1 = $2->Sup.len;$n", [tmp.r, rdLoc(a)])
  2065. else:
  2066. lineCg(p, cpsStmts, "$1 = $2->len;$n", [tmp.r, rdLoc(a)])
  2067. putIntoDest(p, d, e, tmp.r)
  2068. of mGCref: unaryStmt(p, e, d, "if ($1) { #nimGCref($1); }$n")
  2069. of mGCunref: unaryStmt(p, e, d, "if ($1) { #nimGCunref($1); }$n")
  2070. of mSetLengthStr: genSetLengthStr(p, e, d)
  2071. of mSetLengthSeq: genSetLengthSeq(p, e, d)
  2072. of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
  2073. mInSet:
  2074. genSetOp(p, e, d, op)
  2075. of mCopyStr, mCopyStrLast:
  2076. genCall(p, e, d)
  2077. of mNewString, mNewStringOfCap, mExit, mParseBiggestFloat:
  2078. var opr = e.sons[0].sym
  2079. # Why would anyone want to set nodecl to one of these hardcoded magics?
  2080. # - not sure, and it wouldn't work if the symbol behind the magic isn't
  2081. # somehow forward-declared from some other usage, but it is *possible*
  2082. if lfNoDecl notin opr.loc.flags:
  2083. let prc = magicsys.getCompilerProc(p.module.g.graph, $opr.loc.r)
  2084. # HACK:
  2085. # Explicitly add this proc as declared here so the cgsym call doesn't
  2086. # add a forward declaration - without this we could end up with the same
  2087. # 2 forward declarations. That happens because the magic symbol and the original
  2088. # one that shall be used have different ids (even though a call to one is
  2089. # actually a call to the other) so checking into m.declaredProtos with the 2 different ids doesn't work.
  2090. # Why would 2 identical forward declarations be a problem?
  2091. # - in the case of hot code-reloading we generate function pointers instead
  2092. # of forward declarations and in C++ it is an error to redefine a global
  2093. let wasDeclared = containsOrIncl(p.module.declaredProtos, prc.id)
  2094. # Make the function behind the magic get actually generated - this will
  2095. # not lead to a forward declaration! The genCall will lead to one.
  2096. discard cgsym(p.module, $opr.loc.r)
  2097. # make sure we have pointer-initialising code for hot code reloading
  2098. if not wasDeclared and p.hcrOn:
  2099. addf(p.module.s[cfsDynLibInit], "\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  2100. [mangleDynLibProc(prc), getTypeDesc(p.module, prc.loc.t), getModuleDllPath(p.module, prc)])
  2101. genCall(p, e, d)
  2102. of mDefault: genDefault(p, e, d)
  2103. of mReset: genReset(p, e)
  2104. of mEcho: genEcho(p, e[1].skipConv)
  2105. of mArrToSeq: genArrToSeq(p, e, d)
  2106. of mNLen..mNError, mSlurp..mQuoteAst:
  2107. localError(p.config, e.info, strutils.`%`(errXMustBeCompileTime, e.sons[0].sym.name.s))
  2108. of mSpawn:
  2109. when defined(leanCompiler):
  2110. quit "compiler built without support for the 'spawn' statement"
  2111. else:
  2112. let n = spawn.wrapProcForSpawn(p.module.g.graph, p.module.module, e, e.typ, nil, nil)
  2113. expr(p, n, d)
  2114. of mParallel:
  2115. when defined(leanCompiler):
  2116. quit "compiler built without support for the 'parallel' statement"
  2117. else:
  2118. let n = semparallel.liftParallel(p.module.g.graph, p.module.module, e)
  2119. expr(p, n, d)
  2120. of mDeepCopy:
  2121. var a, b: TLoc
  2122. let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1]
  2123. initLocExpr(p, x, a)
  2124. initLocExpr(p, e.sons[2], b)
  2125. genDeepCopy(p, a, b)
  2126. of mDotDot, mEqCString: genCall(p, e, d)
  2127. of mWasMoved: genWasMoved(p, e)
  2128. of mMove: genMove(p, e, d)
  2129. of mDestroy: genDestroy(p, e)
  2130. of mAccessEnv: unaryExpr(p, e, d, "$1.ClE_0")
  2131. of mSlice:
  2132. localError(p.config, e.info, "invalid context for 'toOpenArray'; " &
  2133. "'toOpenArray' is only valid within a call expression")
  2134. else:
  2135. when defined(debugMagics):
  2136. echo p.prc.name.s, " ", p.prc.id, " ", p.prc.flags, " ", p.prc.ast[genericParamsPos].kind
  2137. internalError(p.config, e.info, "genMagicExpr: " & $op)
  2138. proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  2139. # example: { a..b, c, d, e, f..g }
  2140. # we have to emit an expression of the form:
  2141. # nimZeroMem(tmp, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  2142. # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  2143. var
  2144. a, b, idx: TLoc
  2145. if nfAllConst in e.flags:
  2146. putIntoDest(p, d, e, genSetNode(p, e))
  2147. else:
  2148. if d.k == locNone: getTemp(p, e.typ, d)
  2149. if getSize(p.config, e.typ) > 8:
  2150. # big set:
  2151. linefmt(p, cpsStmts, "#nimZeroMem($1, sizeof($2));$n",
  2152. [rdLoc(d), getTypeDesc(p.module, e.typ)])
  2153. for it in e.sons:
  2154. if it.kind == nkRange:
  2155. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), idx) # our counter
  2156. initLocExpr(p, it.sons[0], a)
  2157. initLocExpr(p, it.sons[1], b)
  2158. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  2159. "$2[(NU)($1)>>3] |=(1U<<((NU)($1)&7U));$n", [rdLoc(idx), rdLoc(d),
  2160. rdSetElemLoc(p.config, a, e.typ), rdSetElemLoc(p.config, b, e.typ)])
  2161. else:
  2162. initLocExpr(p, it, a)
  2163. lineF(p, cpsStmts, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n",
  2164. [rdLoc(d), rdSetElemLoc(p.config, a, e.typ)])
  2165. else:
  2166. # small set
  2167. var ts = "NU" & $(getSize(p.config, e.typ) * 8)
  2168. lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)])
  2169. for it in e.sons:
  2170. if it.kind == nkRange:
  2171. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), idx) # our counter
  2172. initLocExpr(p, it.sons[0], a)
  2173. initLocExpr(p, it.sons[1], b)
  2174. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  2175. "$2 |=(($5)(1)<<(($1)%(sizeof($5)*8)));$n", [
  2176. rdLoc(idx), rdLoc(d), rdSetElemLoc(p.config, a, e.typ),
  2177. rdSetElemLoc(p.config, b, e.typ), rope(ts)])
  2178. else:
  2179. initLocExpr(p, it, a)
  2180. lineF(p, cpsStmts,
  2181. "$1 |=(($3)(1)<<(($2)%(sizeof($3)*8)));$n",
  2182. [rdLoc(d), rdSetElemLoc(p.config, a, e.typ), rope(ts)])
  2183. proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  2184. var rec: TLoc
  2185. if not handleConstExpr(p, n, d):
  2186. let t = n.typ
  2187. discard getTypeDesc(p.module, t) # so that any fields are initialized
  2188. if d.k == locNone: getTemp(p, t, d)
  2189. for i in 0 ..< len(n):
  2190. var it = n.sons[i]
  2191. if it.kind == nkExprColonExpr: it = it.sons[1]
  2192. initLoc(rec, locExpr, it, d.storage)
  2193. rec.r = "$1.Field$2" % [rdLoc(d), rope(i)]
  2194. rec.flags.incl(lfEnforceDeref)
  2195. expr(p, it, rec)
  2196. proc isConstClosure(n: PNode): bool {.inline.} =
  2197. result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and
  2198. n.sons[1].kind == nkNilLit
  2199. proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  2200. assert n.kind in {nkPar, nkTupleConstr, nkClosure}
  2201. if isConstClosure(n):
  2202. inc(p.module.labels)
  2203. var tmp = "CNSTCLOSURE" & rope(p.module.labels)
  2204. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  2205. [getTypeDesc(p.module, n.typ), tmp, genConstExpr(p, n)])
  2206. putIntoDest(p, d, n, tmp, OnStatic)
  2207. else:
  2208. var tmp, a, b: TLoc
  2209. initLocExpr(p, n.sons[0], a)
  2210. initLocExpr(p, n.sons[1], b)
  2211. if n.sons[0].skipConv.kind == nkClosure:
  2212. internalError(p.config, n.info, "closure to closure created")
  2213. # tasyncawait.nim breaks with this optimization:
  2214. when false:
  2215. if d.k != locNone:
  2216. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  2217. [d.rdLoc, a.rdLoc, b.rdLoc])
  2218. else:
  2219. getTemp(p, n.typ, tmp)
  2220. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  2221. [tmp.rdLoc, a.rdLoc, b.rdLoc])
  2222. putLocIntoDest(p, d, tmp)
  2223. proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  2224. var arr: TLoc
  2225. if not handleConstExpr(p, n, d):
  2226. if d.k == locNone: getTemp(p, n.typ, d)
  2227. for i in 0 ..< len(n):
  2228. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), d.storage)
  2229. arr.r = "$1[$2]" % [rdLoc(d), intLiteral(i)]
  2230. expr(p, n.sons[i], arr)
  2231. proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  2232. requestConstImpl(p, sym)
  2233. assert((sym.loc.r != nil) and (sym.loc.t != nil))
  2234. putLocIntoDest(p, d, sym.loc)
  2235. template genStmtListExprImpl(exprOrStmt) {.dirty.} =
  2236. #let hasNimFrame = magicsys.getCompilerProc("nimFrame") != nil
  2237. let hasNimFrame = p.prc != nil and
  2238. sfSystemModule notin p.module.module.flags and
  2239. optStackTrace in p.prc.options
  2240. var frameName: Rope = nil
  2241. for i in 0 .. n.len - 2:
  2242. let it = n[i]
  2243. if it.kind == nkComesFrom:
  2244. if hasNimFrame and frameName == nil:
  2245. inc p.labels
  2246. frameName = "FR" & rope(p.labels) & "_"
  2247. let theMacro = it[0].sym
  2248. add p.s(cpsStmts), initFrameNoDebug(p, frameName,
  2249. makeCString theMacro.name.s,
  2250. quotedFilename(p.config, theMacro.info), it.info.line.int)
  2251. else:
  2252. genStmts(p, it)
  2253. if n.len > 0: exprOrStmt
  2254. if frameName != nil:
  2255. add p.s(cpsStmts), deinitFrameNoDebug(p, frameName)
  2256. proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  2257. genStmtListExprImpl:
  2258. expr(p, n[n.len - 1], d)
  2259. proc genStmtList(p: BProc, n: PNode) =
  2260. genStmtListExprImpl:
  2261. genStmts(p, n[n.len - 1])
  2262. proc upConv(p: BProc, n: PNode, d: var TLoc) =
  2263. var a: TLoc
  2264. initLocExpr(p, n.sons[0], a)
  2265. let dest = skipTypes(n.typ, abstractPtrs)
  2266. if optObjCheck in p.options and not isObjLackingTypeField(dest):
  2267. var r = rdLoc(a)
  2268. var nilCheck: Rope = nil
  2269. var t = skipTypes(a.t, abstractInst)
  2270. while t.kind in {tyVar, tyLent, tyPtr, tyRef}:
  2271. if t.kind notin {tyVar, tyLent}: nilCheck = r
  2272. if t.kind notin {tyVar, tyLent} or not p.module.compileToCpp:
  2273. r = "(*$1)" % [r]
  2274. t = skipTypes(t.lastSon, abstractInst)
  2275. discard getTypeDesc(p.module, t)
  2276. if not p.module.compileToCpp:
  2277. while t.kind == tyObject and t.sons[0] != nil:
  2278. add(r, ".Sup")
  2279. t = skipTypes(t.sons[0], skipPtrs)
  2280. let checkFor = if optTinyRtti in p.config.globalOptions:
  2281. genTypeInfo2Name(p.module, dest)
  2282. else:
  2283. genTypeInfo(p.module, dest, n.info)
  2284. if nilCheck != nil:
  2285. linefmt(p, cpsStmts, "if ($1) #chckObj($2.m_type, $3);$n",
  2286. [nilCheck, r, checkFor])
  2287. else:
  2288. linefmt(p, cpsStmts, "#chckObj($1.m_type, $2);$n",
  2289. [r, checkFor])
  2290. if n.sons[0].typ.kind != tyObject:
  2291. putIntoDest(p, d, n,
  2292. "(($1) ($2))" % [getTypeDesc(p.module, n.typ), rdLoc(a)], a.storage)
  2293. else:
  2294. putIntoDest(p, d, n, "(*($1*) ($2))" %
  2295. [getTypeDesc(p.module, dest), addrLoc(p.config, a)], a.storage)
  2296. proc downConv(p: BProc, n: PNode, d: var TLoc) =
  2297. if p.module.compileToCpp:
  2298. discard getTypeDesc(p.module, skipTypes(n[0].typ, abstractPtrs))
  2299. expr(p, n.sons[0], d) # downcast does C++ for us
  2300. else:
  2301. var dest = skipTypes(n.typ, abstractPtrs)
  2302. var arg = n.sons[0]
  2303. while arg.kind == nkObjDownConv: arg = arg.sons[0]
  2304. var src = skipTypes(arg.typ, abstractPtrs)
  2305. discard getTypeDesc(p.module, src)
  2306. var a: TLoc
  2307. initLocExpr(p, arg, a)
  2308. var r = rdLoc(a)
  2309. let isRef = skipTypes(arg.typ, abstractInstOwned).kind in {tyRef, tyPtr, tyVar, tyLent}
  2310. if isRef:
  2311. add(r, "->Sup")
  2312. else:
  2313. add(r, ".Sup")
  2314. for i in 2 .. abs(inheritanceDiff(dest, src)): add(r, ".Sup")
  2315. if isRef:
  2316. # it can happen that we end up generating '&&x->Sup' here, so we pack
  2317. # the '&x->Sup' into a temporary and then those address is taken
  2318. # (see bug #837). However sometimes using a temporary is not correct:
  2319. # init(TFigure(my)) # where it is passed to a 'var TFigure'. We test
  2320. # this by ensuring the destination is also a pointer:
  2321. if d.k == locNone and skipTypes(n.typ, abstractInstOwned).kind in {tyRef, tyPtr, tyVar, tyLent}:
  2322. getTemp(p, n.typ, d)
  2323. linefmt(p, cpsStmts, "$1 = &$2;$n", [rdLoc(d), r])
  2324. else:
  2325. r = "&" & r
  2326. putIntoDest(p, d, n, r, a.storage)
  2327. else:
  2328. putIntoDest(p, d, n, r, a.storage)
  2329. proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) =
  2330. let t = n.typ
  2331. discard getTypeDesc(p.module, t) # so that any fields are initialized
  2332. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  2333. let tmp = p.module.tmpBase & rope(id)
  2334. if id == p.module.labels:
  2335. # expression not found in the cache:
  2336. inc(p.module.labels)
  2337. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  2338. [getTypeDesc(p.module, t), tmp, genConstExpr(p, n)])
  2339. if d.k == locNone:
  2340. fillLoc(d, locData, n, tmp, OnStatic)
  2341. else:
  2342. putDataIntoDest(p, d, n, tmp)
  2343. # This fixes bug #4551, but we really need better dataflow
  2344. # analysis to make this 100% safe.
  2345. if t.kind notin {tySequence, tyString}:
  2346. d.storage = OnStatic
  2347. proc expr(p: BProc, n: PNode, d: var TLoc) =
  2348. p.currLineInfo = n.info
  2349. case n.kind
  2350. of nkSym:
  2351. var sym = n.sym
  2352. case sym.kind
  2353. of skMethod:
  2354. if {sfDispatcher, sfForward} * sym.flags != {}:
  2355. # we cannot produce code for the dispatcher yet:
  2356. fillProcLoc(p.module, n)
  2357. genProcPrototype(p.module, sym)
  2358. else:
  2359. genProc(p.module, sym)
  2360. putLocIntoDest(p, d, sym.loc)
  2361. of skProc, skConverter, skIterator, skFunc:
  2362. #if sym.kind == skIterator:
  2363. # echo renderTree(sym.getBody, {renderIds})
  2364. if sfCompileTime in sym.flags:
  2365. localError(p.config, n.info, "request to generate code for .compileTime proc: " &
  2366. sym.name.s)
  2367. genProc(p.module, sym)
  2368. if sym.loc.r == nil or sym.loc.lode == nil:
  2369. internalError(p.config, n.info, "expr: proc not init " & sym.name.s)
  2370. putLocIntoDest(p, d, sym.loc)
  2371. of skConst:
  2372. if isSimpleConst(sym.typ):
  2373. putIntoDest(p, d, n, genLiteral(p, sym.ast, sym.typ), OnStatic)
  2374. else:
  2375. genComplexConst(p, sym, d)
  2376. of skEnumField:
  2377. # we never reach this case - as of the time of this comment,
  2378. # skEnumField is folded to an int in semfold.nim, but this code
  2379. # remains for robustness
  2380. putIntoDest(p, d, n, rope(sym.position))
  2381. of skVar, skForVar, skResult, skLet:
  2382. if {sfGlobal, sfThread} * sym.flags != {}:
  2383. genVarPrototype(p.module, n)
  2384. if sfCompileTime in sym.flags:
  2385. genSingleVar(p, sym, n, astdef(sym))
  2386. if sym.loc.r == nil or sym.loc.t == nil:
  2387. #echo "FAILED FOR PRCO ", p.prc.name.s
  2388. #echo renderTree(p.prc.ast, {renderIds})
  2389. internalError p.config, n.info, "expr: var not init " & sym.name.s & "_" & $sym.id
  2390. if sfThread in sym.flags:
  2391. accessThreadLocalVar(p, sym)
  2392. if emulatedThreadVars(p.config):
  2393. putIntoDest(p, d, sym.loc.lode, "NimTV_->" & sym.loc.r)
  2394. else:
  2395. putLocIntoDest(p, d, sym.loc)
  2396. else:
  2397. putLocIntoDest(p, d, sym.loc)
  2398. of skTemp:
  2399. if sym.loc.r == nil or sym.loc.t == nil:
  2400. #echo "FAILED FOR PRCO ", p.prc.name.s
  2401. #echo renderTree(p.prc.ast, {renderIds})
  2402. internalError(p.config, n.info, "expr: temp not init " & sym.name.s & "_" & $sym.id)
  2403. putLocIntoDest(p, d, sym.loc)
  2404. of skParam:
  2405. if sym.loc.r == nil or sym.loc.t == nil:
  2406. # echo "FAILED FOR PRCO ", p.prc.name.s
  2407. # debug p.prc.typ.n
  2408. # echo renderTree(p.prc.ast, {renderIds})
  2409. internalError(p.config, n.info, "expr: param not init " & sym.name.s & "_" & $sym.id)
  2410. putLocIntoDest(p, d, sym.loc)
  2411. else: internalError(p.config, n.info, "expr(" & $sym.kind & "); unknown symbol")
  2412. of nkNilLit:
  2413. if not isEmptyType(n.typ):
  2414. putIntoDest(p, d, n, genLiteral(p, n))
  2415. of nkStrLit..nkTripleStrLit:
  2416. putDataIntoDest(p, d, n, genLiteral(p, n))
  2417. of nkIntLit..nkUInt64Lit,
  2418. nkFloatLit..nkFloat128Lit, nkCharLit:
  2419. putIntoDest(p, d, n, genLiteral(p, n))
  2420. of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkPostfix, nkCommand,
  2421. nkCallStrLit:
  2422. genLineDir(p, n) # may be redundant, it is generated in fixupCall as well
  2423. let op = n.sons[0]
  2424. if n.typ.isNil:
  2425. # discard the value:
  2426. var a: TLoc
  2427. if op.kind == nkSym and op.sym.magic != mNone:
  2428. genMagicExpr(p, n, a, op.sym.magic)
  2429. else:
  2430. genCall(p, n, a)
  2431. else:
  2432. # load it into 'd':
  2433. if op.kind == nkSym and op.sym.magic != mNone:
  2434. genMagicExpr(p, n, d, op.sym.magic)
  2435. else:
  2436. genCall(p, n, d)
  2437. of nkCurly:
  2438. if isDeepConstExpr(n) and n.len != 0:
  2439. putIntoDest(p, d, n, genSetNode(p, n))
  2440. else:
  2441. genSetConstr(p, n, d)
  2442. of nkBracket:
  2443. if isDeepConstExpr(n) and n.len != 0:
  2444. exprComplexConst(p, n, d)
  2445. elif skipTypes(n.typ, abstractVarRange).kind == tySequence:
  2446. genSeqConstr(p, n, d)
  2447. else:
  2448. genArrayConstr(p, n, d)
  2449. of nkPar, nkTupleConstr:
  2450. if n.typ != nil and n.typ.kind == tyProc and n.len == 2:
  2451. genClosure(p, n, d)
  2452. elif isDeepConstExpr(n) and n.len != 0:
  2453. exprComplexConst(p, n, d)
  2454. else:
  2455. genTupleConstr(p, n, d)
  2456. of nkObjConstr: genObjConstr(p, n, d)
  2457. of nkCast: genCast(p, n, d)
  2458. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, d)
  2459. of nkHiddenAddr, nkAddr: genAddr(p, n, d)
  2460. of nkBracketExpr: genBracketExpr(p, n, d)
  2461. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, d)
  2462. of nkDotExpr: genRecordField(p, n, d)
  2463. of nkCheckedFieldExpr: genCheckedRecordField(p, n, d)
  2464. of nkBlockExpr, nkBlockStmt: genBlock(p, n, d)
  2465. of nkStmtListExpr: genStmtListExpr(p, n, d)
  2466. of nkStmtList: genStmtList(p, n)
  2467. of nkIfExpr, nkIfStmt: genIf(p, n, d)
  2468. of nkWhen:
  2469. # This should be a "when nimvm" node.
  2470. expr(p, n.sons[1].sons[0], d)
  2471. of nkObjDownConv: downConv(p, n, d)
  2472. of nkObjUpConv: upConv(p, n, d)
  2473. of nkChckRangeF: genRangeChck(p, n, d, "chckRangeF")
  2474. of nkChckRange64: genRangeChck(p, n, d, "chckRange64")
  2475. of nkChckRange: genRangeChck(p, n, d, "chckRange")
  2476. of nkStringToCString: convStrToCStr(p, n, d)
  2477. of nkCStringToString: convCStrToStr(p, n, d)
  2478. of nkLambdaKinds:
  2479. var sym = n.sons[namePos].sym
  2480. genProc(p.module, sym)
  2481. if sym.loc.r == nil or sym.loc.lode == nil:
  2482. internalError(p.config, n.info, "expr: proc not init " & sym.name.s)
  2483. putLocIntoDest(p, d, sym.loc)
  2484. of nkClosure: genClosure(p, n, d)
  2485. of nkEmpty: discard
  2486. of nkWhileStmt: genWhileStmt(p, n)
  2487. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2488. of nkConstSection: discard # consts generated lazily on use
  2489. of nkForStmt: internalError(p.config, n.info, "for statement not eliminated")
  2490. of nkCaseStmt: genCase(p, n, d)
  2491. of nkReturnStmt: genReturnStmt(p, n)
  2492. of nkBreakStmt: genBreakStmt(p, n)
  2493. of nkAsgn:
  2494. if nfPreventCg notin n.flags:
  2495. genAsgn(p, n, fastAsgn=false)
  2496. of nkFastAsgn:
  2497. if nfPreventCg notin n.flags:
  2498. # transf is overly aggressive with 'nkFastAsgn', so we work around here.
  2499. # See tests/run/tcnstseq3 for an example that would fail otherwise.
  2500. genAsgn(p, n, fastAsgn=p.prc != nil)
  2501. of nkDiscardStmt:
  2502. let ex = n[0]
  2503. if ex.kind != nkEmpty:
  2504. genLineDir(p, n)
  2505. var a: TLoc
  2506. initLocExprSingleUse(p, ex, a)
  2507. line(p, cpsStmts, "(void)(" & a.r & ");\L")
  2508. of nkAsmStmt: genAsmStmt(p, n)
  2509. of nkTryStmt, nkHiddenTryStmt:
  2510. if p.module.compileToCpp and optNoCppExceptions notin p.config.globalOptions:
  2511. genTryCpp(p, n, d)
  2512. else:
  2513. genTry(p, n, d)
  2514. of nkRaiseStmt: genRaiseStmt(p, n)
  2515. of nkTypeSection:
  2516. # we have to emit the type information for object types here to support
  2517. # separate compilation:
  2518. genTypeSection(p.module, n)
  2519. of nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  2520. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2521. nkFromStmt, nkTemplateDef, nkMacroDef, nkStaticStmt:
  2522. discard
  2523. of nkPragma: genPragma(p, n)
  2524. of nkPragmaBlock: expr(p, n.lastSon, d)
  2525. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  2526. if n.sons[genericParamsPos].kind == nkEmpty:
  2527. var prc = n.sons[namePos].sym
  2528. # due to a bug/limitation in the lambda lifting, unused inner procs
  2529. # are not transformed correctly. We work around this issue (#411) here
  2530. # by ensuring it's no inner proc (owner is a module):
  2531. if prc.skipGenericOwner.kind == skModule and sfCompileTime notin prc.flags:
  2532. if ({sfExportc, sfCompilerProc} * prc.flags == {sfExportc}) or
  2533. (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or
  2534. (prc.kind == skMethod):
  2535. # Generate proc even if empty body, bugfix #11651.
  2536. genProc(p.module, prc)
  2537. of nkParForStmt: genParForStmt(p, n)
  2538. of nkState: genState(p, n)
  2539. of nkGotoState:
  2540. # simply never set it back to 0 here from here on...
  2541. inc p.splitDecls
  2542. genGotoState(p, n)
  2543. of nkBreakState: genBreakState(p, n, d)
  2544. else: internalError(p.config, n.info, "expr(" & $n.kind & "); unknown node kind")
  2545. proc genNamedConstExpr(p: BProc, n: PNode): Rope =
  2546. if n.kind == nkExprColonExpr: result = genConstExpr(p, n.sons[1])
  2547. else: result = genConstExpr(p, n)
  2548. proc getDefaultValue(p: BProc; typ: PType; info: TLineInfo): Rope =
  2549. var t = skipTypes(typ, abstractRange+{tyOwned}-{tyTypeDesc})
  2550. case t.kind
  2551. of tyBool: result = rope"NIM_FALSE"
  2552. of tyEnum, tyChar, tyInt..tyInt64, tyUInt..tyUInt64: result = rope"0"
  2553. of tyFloat..tyFloat128: result = rope"0.0"
  2554. of tyCString, tyVar, tyLent, tyPointer, tyPtr, tyUntyped,
  2555. tyTyped, tyTypeDesc, tyStatic, tyRef, tyNil:
  2556. result = rope"NIM_NIL"
  2557. of tyString, tySequence:
  2558. if p.config.selectedGC == gcDestructors:
  2559. result = rope"{0, NIM_NIL}"
  2560. else:
  2561. result = rope"NIM_NIL"
  2562. of tyProc:
  2563. if t.callConv != ccClosure:
  2564. result = rope"NIM_NIL"
  2565. else:
  2566. result = rope"{NIM_NIL, NIM_NIL}"
  2567. of tyObject:
  2568. if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2569. result = "{{$1}}" % [genTypeInfo(p.module, t, info)]
  2570. else:
  2571. result = rope"{}"
  2572. of tyTuple:
  2573. result = rope"{"
  2574. for i in 0 ..< typ.len:
  2575. if i > 0: result.add ", "
  2576. result.add getDefaultValue(p, typ.sons[i], info)
  2577. result.add "}"
  2578. of tyArray: result = rope"{}"
  2579. of tySet:
  2580. if mapType(p.config, t) == ctArray: result = rope"{}"
  2581. else: result = rope"0"
  2582. else:
  2583. globalError(p.config, info, "cannot create null element for: " & $t.kind)
  2584. proc getNullValueAux(p: BProc; t: PType; obj, cons: PNode,
  2585. result: var Rope; count: var int) =
  2586. case obj.kind
  2587. of nkRecList:
  2588. for it in obj.sons:
  2589. getNullValueAux(p, t, it, cons, result, count)
  2590. of nkRecCase:
  2591. getNullValueAux(p, t, obj.sons[0], cons, result, count)
  2592. for i in 1 ..< len(obj):
  2593. getNullValueAux(p, t, lastSon(obj.sons[i]), cons, result, count)
  2594. of nkSym:
  2595. if count > 0: result.add ", "
  2596. inc count
  2597. let field = obj.sym
  2598. for i in 1..<cons.len:
  2599. if cons[i].kind == nkExprColonExpr:
  2600. if cons[i][0].sym.name.id == field.name.id:
  2601. result.add genConstExpr(p, cons[i][1])
  2602. return
  2603. elif i == field.position:
  2604. result.add genConstExpr(p, cons[i])
  2605. return
  2606. # not found, produce default value:
  2607. result.add getDefaultValue(p, field.typ, cons.info)
  2608. else:
  2609. localError(p.config, cons.info, "cannot create null element for: " & $obj)
  2610. proc getNullValueAuxT(p: BProc; orig, t: PType; obj, cons: PNode,
  2611. result: var Rope; count: var int) =
  2612. var base = t.sons[0]
  2613. let oldRes = result
  2614. if not p.module.compileToCpp: result.add "{"
  2615. let oldcount = count
  2616. if base != nil:
  2617. base = skipTypes(base, skipPtrs)
  2618. getNullValueAuxT(p, orig, base, base.n, cons, result, count)
  2619. elif not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2620. addf(result, "$1", [genTypeInfo(p.module, orig, obj.info)])
  2621. inc count
  2622. getNullValueAux(p, t, obj, cons, result, count)
  2623. # do not emit '{}' as that is not valid C:
  2624. if oldcount == count: result = oldRes
  2625. elif not p.module.compileToCpp: result.add "}"
  2626. proc genConstObjConstr(p: BProc; n: PNode): Rope =
  2627. result = nil
  2628. let t = n.typ.skipTypes(abstractInstOwned)
  2629. var count = 0
  2630. #if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2631. # addf(result, "{$1}", [genTypeInfo(p.module, t)])
  2632. # inc count
  2633. getNullValueAuxT(p, t, t, t.n, n, result, count)
  2634. if p.module.compileToCpp:
  2635. result = "{$1}$n" % [result]
  2636. proc genConstSimpleList(p: BProc, n: PNode): Rope =
  2637. var length = len(n)
  2638. result = rope("{")
  2639. for i in 0 .. length - 2:
  2640. addf(result, "$1,$n", [genNamedConstExpr(p, n.sons[i])])
  2641. if length > 0:
  2642. add(result, genNamedConstExpr(p, n.sons[length - 1]))
  2643. addf(result, "}$n", [])
  2644. proc genConstSeq(p: BProc, n: PNode, t: PType): Rope =
  2645. var data = "{{$1, $1 | NIM_STRLIT_FLAG}" % [n.len.rope]
  2646. if n.len > 0:
  2647. # array part needs extra curlies:
  2648. data.add(", {")
  2649. for i in 0 ..< n.len:
  2650. if i > 0: data.addf(",$n", [])
  2651. data.add genConstExpr(p, n.sons[i])
  2652. data.add("}")
  2653. data.add("}")
  2654. result = getTempName(p.module)
  2655. let base = t.skipTypes(abstractInst).sons[0]
  2656. appcg(p.module, cfsData,
  2657. "NIM_CONST struct {$n" &
  2658. " #TGenericSeq Sup;$n" &
  2659. " $1 data[$2];$n" &
  2660. "} $3 = $4;$n", [
  2661. getTypeDesc(p.module, base), n.len, result, data])
  2662. result = "(($1)&$2)" % [getTypeDesc(p.module, t), result]
  2663. proc genConstSeqV2(p: BProc, n: PNode, t: PType): Rope =
  2664. var data = rope"{"
  2665. for i in 0 ..< n.len:
  2666. if i > 0: data.addf(",$n", [])
  2667. data.add genConstExpr(p, n.sons[i])
  2668. data.add("}")
  2669. let payload = getTempName(p.module)
  2670. let base = t.skipTypes(abstractInst).sons[0]
  2671. appcg(p.module, cfsData,
  2672. "static const struct {$n" &
  2673. " NI cap; void* allocator; $1 data[$2];$n" &
  2674. "} $3 = {$2, NIM_NIL, $4};$n", [
  2675. getTypeDesc(p.module, base), len(n), payload, data])
  2676. result = "{$1, ($2*)&$3}" % [rope(len(n)), getSeqPayloadType(p.module, t), payload]
  2677. proc genConstExpr(p: BProc, n: PNode): Rope =
  2678. case n.kind
  2679. of nkHiddenStdConv, nkHiddenSubConv:
  2680. result = genConstExpr(p, n.sons[1])
  2681. of nkCurly:
  2682. var cs: TBitSet
  2683. toBitSet(p.config, n, cs)
  2684. result = genRawSetData(cs, int(getSize(p.config, n.typ)))
  2685. of nkBracket, nkPar, nkTupleConstr, nkClosure:
  2686. var t = skipTypes(n.typ, abstractInstOwned)
  2687. if t.kind == tySequence:
  2688. if p.config.selectedGC == gcDestructors:
  2689. result = genConstSeqV2(p, n, n.typ)
  2690. else:
  2691. result = genConstSeq(p, n, n.typ)
  2692. elif t.kind == tyProc and t.callConv == ccClosure and n.len > 1 and
  2693. n.sons[1].kind == nkNilLit:
  2694. # Conversion: nimcall -> closure.
  2695. # this hack fixes issue that nkNilLit is expanded to {NIM_NIL,NIM_NIL}
  2696. # this behaviour is needed since closure_var = nil must be
  2697. # expanded to {NIM_NIL,NIM_NIL}
  2698. # in VM closures are initialized with nkPar(nkNilLit, nkNilLit)
  2699. # leading to duplicate code like this:
  2700. # "{NIM_NIL,NIM_NIL}, {NIM_NIL,NIM_NIL}"
  2701. if n[0].kind == nkNilLit:
  2702. result = ~"{NIM_NIL,NIM_NIL}"
  2703. else:
  2704. var d: TLoc
  2705. initLocExpr(p, n[0], d)
  2706. result = "{(($1) $2),NIM_NIL}" % [getClosureType(p.module, t, clHalfWithEnv), rdLoc(d)]
  2707. else:
  2708. result = genConstSimpleList(p, n)
  2709. of nkObjConstr:
  2710. result = genConstObjConstr(p, n)
  2711. of nkStrLit..nkTripleStrLit:
  2712. if p.config.selectedGC == gcDestructors:
  2713. result = genStringLiteralV2Const(p.module, n)
  2714. else:
  2715. var d: TLoc
  2716. initLocExpr(p, n, d)
  2717. result = rdLoc(d)
  2718. else:
  2719. var d: TLoc
  2720. initLocExpr(p, n, d)
  2721. result = rdLoc(d)