ccgexprs.nim 131 KB

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