ccgexprs.nim 132 KB

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