ccgexprs.nim 131 KB

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