ccgexprs.nim 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461
  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 genReset(p: BProc, n: PNode) =
  1260. var a: TLoc = initLocExpr(p, n[1])
  1261. specializeReset(p, a)
  1262. when false:
  1263. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  1264. [addrLoc(p.config, a),
  1265. genTypeInfoV1(p.module, skipTypes(a.t, {tyVar}), n.info)])
  1266. proc genDefault(p: BProc; n: PNode; d: var TLoc) =
  1267. if d.k == locNone: d = getTemp(p, n.typ, needsInit=true)
  1268. else: resetLoc(p, d)
  1269. proc rawGenNew(p: BProc, a: var TLoc, sizeExpr: Rope; needsInit: bool) =
  1270. var sizeExpr = sizeExpr
  1271. let typ = a.t
  1272. var b: TLoc = initLoc(locExpr, a.lode, OnHeap)
  1273. let refType = typ.skipTypes(abstractInstOwned)
  1274. assert refType.kind == tyRef
  1275. let bt = refType.elementType
  1276. if sizeExpr == "":
  1277. sizeExpr = "sizeof($1)" % [getTypeDesc(p.module, bt)]
  1278. if optTinyRtti in p.config.globalOptions:
  1279. if needsInit:
  1280. b.r = ropecg(p.module, "($1) #nimNewObj($2, NIM_ALIGNOF($3))",
  1281. [getTypeDesc(p.module, typ), sizeExpr, getTypeDesc(p.module, bt)])
  1282. else:
  1283. b.r = ropecg(p.module, "($1) #nimNewObjUninit($2, NIM_ALIGNOF($3))",
  1284. [getTypeDesc(p.module, typ), sizeExpr, getTypeDesc(p.module, bt)])
  1285. genAssignment(p, a, b, {})
  1286. else:
  1287. let ti = genTypeInfoV1(p.module, typ, a.lode.info)
  1288. let op = getAttachedOp(p.module.g.graph, bt, attachedDestructor)
  1289. if op != nil and not isTrivialProc(p.module.g.graph, op):
  1290. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1291. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1292. # convention at least:
  1293. if op.typ == nil or op.typ.callConv != ccNimCall:
  1294. localError(p.module.config, a.lode.info,
  1295. "the destructor that is turned into a finalizer needs " &
  1296. "to have the 'nimcall' calling convention")
  1297. var f: TLoc = initLocExpr(p, newSymNode(op))
  1298. p.module.s[cfsTypeInit3].addf("$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1299. if a.storage == OnHeap and usesWriteBarrier(p.config):
  1300. if canFormAcycle(p.module.g.graph, a.t):
  1301. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", [a.rdLoc])
  1302. else:
  1303. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", [a.rdLoc])
  1304. if p.config.selectedGC == gcGo:
  1305. # newObjRC1() would clash with unsureAsgnRef() - which is used by gcGo to
  1306. # implement the write barrier
  1307. b.r = ropecg(p.module, "($1) #newObj($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1308. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  1309. [addrLoc(p.config, a), b.rdLoc])
  1310. else:
  1311. # use newObjRC1 as an optimization
  1312. b.r = ropecg(p.module, "($1) #newObjRC1($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1313. linefmt(p, cpsStmts, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1314. else:
  1315. b.r = ropecg(p.module, "($1) #newObj($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1316. genAssignment(p, a, b, {})
  1317. # set the object type:
  1318. genObjectInit(p, cpsStmts, bt, a, constructRefObj)
  1319. proc genNew(p: BProc, e: PNode) =
  1320. var a: TLoc = initLocExpr(p, e[1])
  1321. # 'genNew' also handles 'unsafeNew':
  1322. if e.len == 3:
  1323. var se: TLoc = initLocExpr(p, e[2])
  1324. rawGenNew(p, a, se.rdLoc, needsInit = true)
  1325. else:
  1326. rawGenNew(p, a, "", needsInit = true)
  1327. gcUsage(p.config, e)
  1328. proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope; lenIsZero: bool) =
  1329. let seqtype = skipTypes(dest.t, abstractVarRange)
  1330. var call: TLoc = initLoc(locExpr, dest.lode, OnHeap)
  1331. if dest.storage == OnHeap and usesWriteBarrier(p.config):
  1332. if canFormAcycle(p.module.g.graph, dest.t):
  1333. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", [dest.rdLoc])
  1334. else:
  1335. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", [dest.rdLoc])
  1336. if not lenIsZero:
  1337. if p.config.selectedGC == gcGo:
  1338. # we need the write barrier
  1339. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", [getTypeDesc(p.module, seqtype),
  1340. genTypeInfoV1(p.module, seqtype, dest.lode.info), length])
  1341. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n", [addrLoc(p.config, dest), call.rdLoc])
  1342. else:
  1343. call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", [getTypeDesc(p.module, seqtype),
  1344. genTypeInfoV1(p.module, seqtype, dest.lode.info), length])
  1345. linefmt(p, cpsStmts, "$1 = $2;$n", [dest.rdLoc, call.rdLoc])
  1346. else:
  1347. if lenIsZero:
  1348. call.r = rope"NIM_NIL"
  1349. else:
  1350. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", [getTypeDesc(p.module, seqtype),
  1351. genTypeInfoV1(p.module, seqtype, dest.lode.info), length])
  1352. genAssignment(p, dest, call, {})
  1353. proc genNewSeq(p: BProc, e: PNode) =
  1354. var a = initLocExpr(p, e[1])
  1355. var b = initLocExpr(p, e[2])
  1356. if optSeqDestructors in p.config.globalOptions:
  1357. let seqtype = skipTypes(e[1].typ, abstractVarRange)
  1358. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3), NIM_ALIGNOF($3));$n",
  1359. [a.rdLoc, b.rdLoc,
  1360. getTypeDesc(p.module, seqtype.elementType),
  1361. getSeqPayloadType(p.module, seqtype)])
  1362. else:
  1363. let lenIsZero = e[2].kind == nkIntLit and e[2].intVal == 0
  1364. genNewSeqAux(p, a, b.rdLoc, lenIsZero)
  1365. gcUsage(p.config, e)
  1366. proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) =
  1367. let seqtype = skipTypes(e.typ, abstractVarRange)
  1368. var a: TLoc = initLocExpr(p, e[1])
  1369. if optSeqDestructors in p.config.globalOptions:
  1370. if d.k == locNone: d = getTemp(p, e.typ, needsInit=false)
  1371. linefmt(p, cpsStmts, "$1.len = 0; $1.p = ($4*) #newSeqPayloadUninit($2, sizeof($3), NIM_ALIGNOF($3));$n",
  1372. [d.rdLoc, a.rdLoc, getTypeDesc(p.module, seqtype.elementType),
  1373. getSeqPayloadType(p.module, seqtype),
  1374. ])
  1375. else:
  1376. if d.k == locNone: d = getTemp(p, e.typ, needsInit=false) # bug #22560
  1377. putIntoDest(p, d, e, ropecg(p.module,
  1378. "($1)#nimNewSeqOfCap($2, $3)", [
  1379. getTypeDesc(p.module, seqtype),
  1380. genTypeInfoV1(p.module, seqtype, e.info), a.rdLoc]))
  1381. gcUsage(p.config, e)
  1382. proc rawConstExpr(p: BProc, n: PNode; d: var TLoc) =
  1383. let t = n.typ
  1384. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1385. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1386. fillLoc(d, locData, n, p.module.tmpBase & rope(id), OnStatic)
  1387. if id == p.module.labels:
  1388. # expression not found in the cache:
  1389. inc(p.module.labels)
  1390. p.module.s[cfsData].addf("static NIM_CONST $1 $2 = ", [getTypeDesc(p.module, t), d.r])
  1391. genBracedInit(p, n, isConst = true, t, p.module.s[cfsData])
  1392. p.module.s[cfsData].addf(";$n", [])
  1393. proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  1394. if d.k == locNone and n.len > ord(n.kind == nkObjConstr) and n.isDeepConstExpr:
  1395. rawConstExpr(p, n, d)
  1396. result = true
  1397. else:
  1398. result = false
  1399. proc genFieldObjConstr(p: BProc; ty: PType; useTemp, isRef: bool; nField, val, check: PNode; d: var TLoc; r: Rope; info: TLineInfo) =
  1400. var tmp2: TLoc = default(TLoc)
  1401. tmp2.r = r
  1402. let field = lookupFieldAgain(p, ty, nField.sym, tmp2.r)
  1403. if field.loc.r == "": fillObjectFields(p.module, ty)
  1404. if field.loc.r == "": internalError(p.config, info, "genFieldObjConstr")
  1405. if check != nil and optFieldCheck in p.options:
  1406. genFieldCheck(p, check, r, field)
  1407. tmp2.r.add(".")
  1408. tmp2.r.add(field.loc.r)
  1409. if useTemp:
  1410. tmp2.k = locTemp
  1411. tmp2.storage = if isRef: OnHeap else: OnStack
  1412. else:
  1413. tmp2.k = d.k
  1414. tmp2.storage = if isRef: OnHeap else: d.storage
  1415. tmp2.lode = val
  1416. expr(p, val, tmp2)
  1417. proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
  1418. # inheritance in C++ does not allow struct initialization so
  1419. # we skip this step here:
  1420. if not p.module.compileToCpp and optSeqDestructors notin p.config.globalOptions:
  1421. # disabled optimization: it is wrong for C++ and now also
  1422. # causes trouble for --gc:arc, see bug #13240
  1423. #[
  1424. var box: seq[Thing]
  1425. for i in 0..3:
  1426. box.add Thing(s1: "121") # pass by sink can mutate Thing.
  1427. ]#
  1428. if handleConstExpr(p, e, d): return
  1429. var t = e.typ.skipTypes(abstractInstOwned)
  1430. let isRef = t.kind == tyRef
  1431. # check if we need to construct the object in a temporary
  1432. var useTemp =
  1433. isRef or
  1434. (d.k notin {locTemp,locLocalVar,locGlobalVar,locParam,locField}) or
  1435. (isPartOf(d.lode, e) != arNo)
  1436. var tmp: TLoc = default(TLoc)
  1437. var r: Rope
  1438. let needsZeroMem = p.config.selectedGC notin {gcArc, gcAtomicArc, gcOrc} or nfAllFieldsSet notin e.flags
  1439. if useTemp:
  1440. tmp = getTemp(p, t)
  1441. r = rdLoc(tmp)
  1442. if isRef:
  1443. rawGenNew(p, tmp, "", needsInit = nfAllFieldsSet notin e.flags)
  1444. t = t.elementType.skipTypes(abstractInstOwned)
  1445. r = "(*$1)" % [r]
  1446. gcUsage(p.config, e)
  1447. elif needsZeroMem:
  1448. constructLoc(p, tmp)
  1449. else:
  1450. genObjectInit(p, cpsStmts, t, tmp, constructObj)
  1451. else:
  1452. if needsZeroMem: resetLoc(p, d)
  1453. else: genObjectInit(p, cpsStmts, d.t, d, if isRef: constructRefObj else: constructObj)
  1454. r = rdLoc(d)
  1455. discard getTypeDesc(p.module, t)
  1456. let ty = getUniqueType(t)
  1457. for i in 1..<e.len:
  1458. var check: PNode = nil
  1459. if e[i].len == 3 and optFieldCheck in p.options:
  1460. check = e[i][2]
  1461. genFieldObjConstr(p, ty, useTemp, isRef, e[i][0], e[i][1], check, d, r, e.info)
  1462. if useTemp:
  1463. if d.k == locNone:
  1464. d = tmp
  1465. else:
  1466. genAssignment(p, d, tmp, {})
  1467. proc lhsDoesAlias(a, b: PNode): bool =
  1468. result = false
  1469. for y in b:
  1470. if isPartOf(a, y) != arNo: return true
  1471. proc genSeqConstr(p: BProc, n: PNode, d: var TLoc) =
  1472. var arr: TLoc
  1473. var tmp: TLoc = default(TLoc)
  1474. # bug #668
  1475. let doesAlias = lhsDoesAlias(d.lode, n)
  1476. let dest = if doesAlias: addr(tmp) else: addr(d)
  1477. if doesAlias:
  1478. tmp = getTemp(p, n.typ)
  1479. elif d.k == locNone:
  1480. d = getTemp(p, n.typ)
  1481. var lit = newRopeAppender()
  1482. intLiteral(n.len, lit)
  1483. if optSeqDestructors in p.config.globalOptions:
  1484. let seqtype = n.typ
  1485. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3), NIM_ALIGNOF($3));$n",
  1486. [rdLoc dest[], lit, getTypeDesc(p.module, seqtype.elementType),
  1487. getSeqPayloadType(p.module, seqtype)])
  1488. else:
  1489. # generate call to newSeq before adding the elements per hand:
  1490. genNewSeqAux(p, dest[], lit, n.len == 0)
  1491. for i in 0..<n.len:
  1492. arr = initLoc(locExpr, n[i], OnHeap)
  1493. var lit = newRopeAppender()
  1494. intLiteral(i, lit)
  1495. arr.r = ropecg(p.module, "$1$3[$2]", [rdLoc(dest[]), lit, dataField(p)])
  1496. arr.storage = OnHeap # we know that sequences are on the heap
  1497. expr(p, n[i], arr)
  1498. gcUsage(p.config, n)
  1499. if doesAlias:
  1500. if d.k == locNone:
  1501. d = tmp
  1502. else:
  1503. genAssignment(p, d, tmp, {})
  1504. proc genArrToSeq(p: BProc, n: PNode, d: var TLoc) =
  1505. var elem, arr: TLoc
  1506. if n[1].kind == nkBracket:
  1507. n[1].typ = n.typ
  1508. genSeqConstr(p, n[1], d)
  1509. return
  1510. if d.k == locNone:
  1511. d = getTemp(p, n.typ)
  1512. var a = initLocExpr(p, n[1])
  1513. # generate call to newSeq before adding the elements per hand:
  1514. let L = toInt(lengthOrd(p.config, n[1].typ))
  1515. if optSeqDestructors in p.config.globalOptions:
  1516. let seqtype = n.typ
  1517. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3), NIM_ALIGNOF($3));$n",
  1518. [rdLoc d, L, getTypeDesc(p.module, seqtype.elementType),
  1519. getSeqPayloadType(p.module, seqtype)])
  1520. else:
  1521. var lit = newRopeAppender()
  1522. intLiteral(L, lit)
  1523. genNewSeqAux(p, d, lit, L == 0)
  1524. # bug #5007; do not produce excessive C source code:
  1525. if L < 10:
  1526. for i in 0..<L:
  1527. elem = initLoc(locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1528. var lit = newRopeAppender()
  1529. intLiteral(i, lit)
  1530. elem.r = ropecg(p.module, "$1$3[$2]", [rdLoc(d), lit, dataField(p)])
  1531. elem.storage = OnHeap # we know that sequences are on the heap
  1532. arr = initLoc(locExpr, lodeTyp elemType(skipTypes(n[1].typ, abstractInst)), a.storage)
  1533. arr.r = ropecg(p.module, "$1[$2]", [rdLoc(a), lit])
  1534. genAssignment(p, elem, arr, {needToCopy})
  1535. else:
  1536. var i: TLoc = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt))
  1537. linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n", [i.r, L])
  1538. elem = initLoc(locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1539. elem.r = ropecg(p.module, "$1$3[$2]", [rdLoc(d), rdLoc(i), dataField(p)])
  1540. elem.storage = OnHeap # we know that sequences are on the heap
  1541. arr = initLoc(locExpr, lodeTyp elemType(skipTypes(n[1].typ, abstractInst)), a.storage)
  1542. arr.r = ropecg(p.module, "$1[$2]", [rdLoc(a), rdLoc(i)])
  1543. genAssignment(p, elem, arr, {needToCopy})
  1544. lineF(p, cpsStmts, "}$n", [])
  1545. proc genNewFinalize(p: BProc, e: PNode) =
  1546. var
  1547. b: TLoc
  1548. refType, bt: PType
  1549. ti: Rope
  1550. refType = skipTypes(e[1].typ, abstractVarRange)
  1551. var a = initLocExpr(p, e[1])
  1552. var f = initLocExpr(p, e[2])
  1553. b = initLoc(locExpr, a.lode, OnHeap)
  1554. ti = genTypeInfo(p.config, p.module, refType, e.info)
  1555. p.module.s[cfsTypeInit3].addf("$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1556. b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
  1557. getTypeDesc(p.module, refType),
  1558. ti, getTypeDesc(p.module, skipTypes(refType.elementType, abstractRange))])
  1559. genAssignment(p, a, b, {}) # set the object type:
  1560. bt = skipTypes(refType.elementType, abstractRange)
  1561. genObjectInit(p, cpsStmts, bt, a, constructRefObj)
  1562. gcUsage(p.config, e)
  1563. proc genOfHelper(p: BProc; dest: PType; a: Rope; info: TLineInfo; result: var Rope) =
  1564. if optTinyRtti in p.config.globalOptions:
  1565. let token = $genDisplayElem(MD5Digest(hashType(dest, p.config)))
  1566. appcg(p.module, result, "#isObjDisplayCheck($#.m_type, $#, $#)", [a, getObjDepth(dest), token])
  1567. else:
  1568. # unfortunately 'genTypeInfoV1' sets tfObjHasKids as a side effect, so we
  1569. # have to call it here first:
  1570. let ti = genTypeInfoV1(p.module, dest, info)
  1571. if tfFinal in dest.flags or (objHasKidsValid in p.module.flags and
  1572. tfObjHasKids notin dest.flags):
  1573. result.add "$1.m_type == $2" % [a, ti]
  1574. else:
  1575. cgsym(p.module, "TNimType")
  1576. inc p.module.labels
  1577. let cache = "Nim_OfCheck_CACHE" & p.module.labels.rope
  1578. p.module.s[cfsVars].addf("static TNimType* $#[2];$n", [cache])
  1579. appcg(p.module, result, "#isObjWithCache($#.m_type, $#, $#)", [a, ti, cache])
  1580. proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  1581. var a: TLoc = initLocExpr(p, x)
  1582. var dest = skipTypes(typ, typedescPtrs)
  1583. var r = rdLoc(a)
  1584. var nilCheck: Rope = ""
  1585. var t = skipTypes(a.t, abstractInstOwned)
  1586. while t.kind in {tyVar, tyLent, tyPtr, tyRef}:
  1587. if t.kind notin {tyVar, tyLent}: nilCheck = r
  1588. if t.kind notin {tyVar, tyLent} or not p.module.compileToCpp:
  1589. r = ropecg(p.module, "(*$1)", [r])
  1590. t = skipTypes(t.elementType, typedescInst+{tyOwned})
  1591. discard getTypeDesc(p.module, t)
  1592. if not p.module.compileToCpp:
  1593. while t.kind == tyObject and t.baseClass != nil:
  1594. r.add(".Sup")
  1595. t = skipTypes(t.baseClass, skipPtrs)
  1596. if isObjLackingTypeField(t):
  1597. globalError(p.config, x.info,
  1598. "no 'of' operator available for pure objects")
  1599. var ro = newRopeAppender()
  1600. genOfHelper(p, dest, r, x.info, ro)
  1601. var ofExpr = newRopeAppender()
  1602. ofExpr.add "("
  1603. if nilCheck != "":
  1604. ofExpr.add "("
  1605. ofExpr.add nilCheck
  1606. ofExpr.add ") && ("
  1607. ofExpr.add ro
  1608. ofExpr.add "))"
  1609. else:
  1610. ofExpr.add ro
  1611. ofExpr.add ")"
  1612. putIntoDest(p, d, x, ofExpr, a.storage)
  1613. proc genOf(p: BProc, n: PNode, d: var TLoc) =
  1614. genOf(p, n[1], n[2].typ, d)
  1615. proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  1616. if optTinyRtti in p.config.globalOptions:
  1617. localError(p.config, e.info, "'repr' is not available for --newruntime")
  1618. var a: TLoc = initLocExpr(p, e[1])
  1619. var t = skipTypes(e[1].typ, abstractVarRange)
  1620. case t.kind
  1621. of tyInt..tyInt64, tyUInt..tyUInt64:
  1622. putIntoDest(p, d, e,
  1623. ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]), a.storage)
  1624. of tyFloat..tyFloat128:
  1625. putIntoDest(p, d, e, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]), a.storage)
  1626. of tyBool:
  1627. putIntoDest(p, d, e, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]), a.storage)
  1628. of tyChar:
  1629. putIntoDest(p, d, e, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]), a.storage)
  1630. of tyEnum, tyOrdinal:
  1631. putIntoDest(p, d, e,
  1632. ropecg(p.module, "#reprEnum((NI)$1, $2)", [
  1633. rdLoc(a), genTypeInfoV1(p.module, t, e.info)]), a.storage)
  1634. of tyString:
  1635. putIntoDest(p, d, e, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]), a.storage)
  1636. of tySet:
  1637. putIntoDest(p, d, e, ropecg(p.module, "#reprSet($1, $2)", [
  1638. addrLoc(p.config, a), genTypeInfoV1(p.module, t, e.info)]), a.storage)
  1639. of tyOpenArray, tyVarargs:
  1640. var b: TLoc = default(TLoc)
  1641. case skipTypes(a.t, abstractVarRange).kind
  1642. of tyOpenArray, tyVarargs:
  1643. putIntoDest(p, b, e, "$1, $1Len_0" % [rdLoc(a)], a.storage)
  1644. of tyString, tySequence:
  1645. putIntoDest(p, b, e,
  1646. "($4) ? ($1$3) : NIM_NIL, $2" %
  1647. [rdLoc(a), lenExpr(p, a), dataField(p), dataFieldAccessor(p, a.rdLoc)],
  1648. a.storage)
  1649. of tyArray:
  1650. putIntoDest(p, b, e,
  1651. "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))], a.storage)
  1652. else: internalError(p.config, e[0].info, "genRepr()")
  1653. putIntoDest(p, d, e,
  1654. ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
  1655. genTypeInfoV1(p.module, elemType(t), e.info)]), a.storage)
  1656. of tyCstring, tyArray, tyRef, tyPtr, tyPointer, tyNil, tySequence:
  1657. putIntoDest(p, d, e,
  1658. ropecg(p.module, "#reprAny($1, $2)", [
  1659. rdLoc(a), genTypeInfoV1(p.module, t, e.info)]), a.storage)
  1660. of tyEmpty, tyVoid:
  1661. localError(p.config, e.info, "'repr' doesn't support 'void' type")
  1662. else:
  1663. putIntoDest(p, d, e, ropecg(p.module, "#reprAny($1, $2)",
  1664. [addrLoc(p.config, a), genTypeInfoV1(p.module, t, e.info)]),
  1665. a.storage)
  1666. gcUsage(p.config, e)
  1667. proc rdMType(p: BProc; a: TLoc; nilCheck: var Rope; result: var Rope; enforceV1 = false) =
  1668. var derefs = rdLoc(a)
  1669. var t = skipTypes(a.t, abstractInst)
  1670. while t.kind in {tyVar, tyLent, tyPtr, tyRef}:
  1671. if t.kind notin {tyVar, tyLent}: nilCheck = derefs
  1672. if t.kind notin {tyVar, tyLent} or not p.module.compileToCpp:
  1673. derefs = "(*$1)" % [derefs]
  1674. t = skipTypes(t.elementType, abstractInst)
  1675. result.add derefs
  1676. discard getTypeDesc(p.module, t)
  1677. if not p.module.compileToCpp:
  1678. while t.kind == tyObject and t.baseClass != nil:
  1679. result.add(".Sup")
  1680. t = skipTypes(t.baseClass, skipPtrs)
  1681. result.add ".m_type"
  1682. if optTinyRtti in p.config.globalOptions and enforceV1:
  1683. result.add "->typeInfoV1"
  1684. proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  1685. cgsym(p.module, "TNimType")
  1686. let t = e[1].typ
  1687. # ordinary static type information
  1688. putIntoDest(p, d, e, genTypeInfoV1(p.module, t, e.info))
  1689. proc genGetTypeInfoV2(p: BProc, e: PNode, d: var TLoc) =
  1690. let t = e[1].typ
  1691. if isFinal(t) or e[0].sym.name.s != "getDynamicTypeInfo":
  1692. # ordinary static type information
  1693. putIntoDest(p, d, e, genTypeInfoV2(p.module, t, e.info))
  1694. else:
  1695. var a: TLoc = initLocExpr(p, e[1])
  1696. var nilCheck = ""
  1697. # use the dynamic type stored at offset 0:
  1698. var rt = newRopeAppender()
  1699. rdMType(p, a, nilCheck, rt)
  1700. putIntoDest(p, d, e, rt)
  1701. proc genAccessTypeField(p: BProc; e: PNode; d: var TLoc) =
  1702. var a: TLoc = initLocExpr(p, e[1])
  1703. var nilCheck = ""
  1704. # use the dynamic type stored at offset 0:
  1705. var rt = newRopeAppender()
  1706. rdMType(p, a, nilCheck, rt)
  1707. putIntoDest(p, d, e, rt)
  1708. template genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  1709. var a: TLoc = initLocExpr(p, n[1])
  1710. a.r = ropecg(p.module, frmt, [rdLoc(a)])
  1711. a.flags.excl lfIndirect # this flag should not be propagated here (not just for HCR)
  1712. if d.k == locNone: d = getTemp(p, n.typ)
  1713. genAssignment(p, d, a, {})
  1714. gcUsage(p.config, n)
  1715. proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1716. var a = e[1]
  1717. if a.kind == nkHiddenAddr: a = a[0]
  1718. var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
  1719. case typ.kind
  1720. of tyOpenArray, tyVarargs:
  1721. # Bug #9279, len(toOpenArray()) has to work:
  1722. if a.kind in nkCallKinds and a[0].kind == nkSym and a[0].sym.magic == mSlice:
  1723. # magic: pass slice to openArray:
  1724. var m = initLocExpr(p, a[1])
  1725. var b = initLocExpr(p, a[2])
  1726. var c = initLocExpr(p, a[3])
  1727. if optBoundsCheck in p.options:
  1728. genBoundsCheck(p, m, b, c)
  1729. if op == mHigh:
  1730. putIntoDest(p, d, e, ropecg(p.module, "(($2)-($1))", [rdLoc(b), rdLoc(c)]))
  1731. else:
  1732. putIntoDest(p, d, e, ropecg(p.module, "(($2)-($1)+1)", [rdLoc(b), rdLoc(c)]))
  1733. else:
  1734. if not reifiedOpenArray(a):
  1735. if op == mHigh: unaryExpr(p, e, d, "($1Len_0-1)")
  1736. else: unaryExpr(p, e, d, "$1Len_0")
  1737. else:
  1738. let isDeref = a.kind in {nkHiddenDeref, nkDerefExpr}
  1739. if op == mHigh:
  1740. if isDeref:
  1741. unaryExpr(p, e, d, "($1->Field1-1)")
  1742. else:
  1743. unaryExpr(p, e, d, "($1.Field1-1)")
  1744. else:
  1745. if isDeref:
  1746. unaryExpr(p, e, d, "$1->Field1")
  1747. else:
  1748. unaryExpr(p, e, d, "$1.Field1")
  1749. of tyCstring:
  1750. if op == mHigh: unaryExpr(p, e, d, "(#nimCStrLen($1)-1)")
  1751. else: unaryExpr(p, e, d, "#nimCStrLen($1)")
  1752. of tyString:
  1753. var a: TLoc = initLocExpr(p, e[1])
  1754. var x = lenExpr(p, a)
  1755. if op == mHigh: x = "($1-1)" % [x]
  1756. putIntoDest(p, d, e, x)
  1757. of tySequence:
  1758. # we go through a temporary here because people write bullshit code.
  1759. var tmp: TLoc = getIntTemp(p)
  1760. var a = initLocExpr(p, e[1])
  1761. var x = lenExpr(p, a)
  1762. if op == mHigh: x = "($1-1)" % [x]
  1763. lineCg(p, cpsStmts, "$1 = $2;$n", [tmp.r, x])
  1764. putIntoDest(p, d, e, tmp.r)
  1765. of tyArray:
  1766. # YYY: length(sideeffect) is optimized away incorrectly?
  1767. if op == mHigh: putIntoDest(p, d, e, rope(lastOrd(p.config, typ)))
  1768. else: putIntoDest(p, d, e, rope(lengthOrd(p.config, typ)))
  1769. else: internalError(p.config, e.info, "genArrayLen()")
  1770. proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  1771. if optSeqDestructors in p.config.globalOptions:
  1772. e[1] = makeAddr(e[1], p.module.idgen)
  1773. genCall(p, e, d)
  1774. return
  1775. assert(d.k == locNone)
  1776. var x = e[1]
  1777. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  1778. var a = initLocExpr(p, x)
  1779. var b = initLocExpr(p, e[2])
  1780. let t = skipTypes(e[1].typ, {tyVar})
  1781. var call = initLoc(locCall, e, OnHeap)
  1782. if not p.module.compileToCpp:
  1783. const setLenPattern = "($3) #setLengthSeqV2(($1)?&($1)->Sup:NIM_NIL, $4, $2)"
  1784. call.r = ropecg(p.module, setLenPattern, [
  1785. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1786. genTypeInfoV1(p.module, t.skipTypes(abstractInst), e.info)])
  1787. else:
  1788. const setLenPattern = "($3) #setLengthSeqV2($1, $4, $2)"
  1789. call.r = ropecg(p.module, setLenPattern, [
  1790. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1791. genTypeInfoV1(p.module, t.skipTypes(abstractInst), e.info)])
  1792. genAssignment(p, a, call, {})
  1793. gcUsage(p.config, e)
  1794. proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  1795. if optSeqDestructors in p.config.globalOptions:
  1796. binaryStmtAddr(p, e, d, "setLengthStrV2")
  1797. else:
  1798. if d.k != locNone: internalError(p.config, e.info, "genSetLengthStr")
  1799. var a = initLocExpr(p, e[1])
  1800. var b = initLocExpr(p, e[2])
  1801. var call = initLoc(locCall, e, OnHeap)
  1802. call.r = ropecg(p.module, "#setLengthStr($1, $2)", [
  1803. rdLoc(a), rdLoc(b)])
  1804. genAssignment(p, a, call, {})
  1805. gcUsage(p.config, e)
  1806. proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  1807. # swap(a, b) -->
  1808. # temp = a
  1809. # a = b
  1810. # b = temp
  1811. cowBracket(p, e[1])
  1812. cowBracket(p, e[2])
  1813. var tmp: TLoc = getTemp(p, skipTypes(e[1].typ, abstractVar))
  1814. var a = initLocExpr(p, e[1]) # eval a
  1815. var b = initLocExpr(p, e[2]) # eval b
  1816. genAssignment(p, tmp, a, {})
  1817. genAssignment(p, a, b, {})
  1818. genAssignment(p, b, tmp, {})
  1819. proc rdSetElemLoc(conf: ConfigRef; a: TLoc, typ: PType; result: var Rope) =
  1820. # read a location of an set element; it may need a subtraction operation
  1821. # before the set operation
  1822. result.add "("
  1823. result.add rdCharLoc(a)
  1824. let setType = typ.skipTypes(abstractPtrs)
  1825. assert(setType.kind == tySet)
  1826. if firstOrd(conf, setType) != 0:
  1827. result.add " - "
  1828. result.add rope(firstOrd(conf, setType))
  1829. result.add ")"
  1830. proc fewCmps(conf: ConfigRef; s: PNode): bool =
  1831. # this function estimates whether it is better to emit code
  1832. # for constructing the set or generating a bunch of comparisons directly
  1833. if s.kind != nkCurly: return false
  1834. if (getSize(conf, s.typ) <= conf.target.intSize) and (nfAllConst in s.flags):
  1835. result = false # it is better to emit the set generation code
  1836. elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
  1837. result = true # better not emit the set if int is basetype!
  1838. else:
  1839. result = s.len <= 8 # 8 seems to be a good value
  1840. template binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  1841. var elem = newRopeAppender()
  1842. rdSetElemLoc(p.config, b, a.t, elem)
  1843. putIntoDest(p, d, e, frmt % [rdLoc(a), elem])
  1844. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  1845. case int(getSize(p.config, skipTypes(e[1].typ, abstractVar)))
  1846. of 1: binaryExprIn(p, e, a, b, d, "(($1 &((NU8)1<<((NU)($2)&7U)))!=0)")
  1847. of 2: binaryExprIn(p, e, a, b, d, "(($1 &((NU16)1<<((NU)($2)&15U)))!=0)")
  1848. of 4: binaryExprIn(p, e, a, b, d, "(($1 &((NU32)1<<((NU)($2)&31U)))!=0)")
  1849. of 8: binaryExprIn(p, e, a, b, d, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)")
  1850. else: binaryExprIn(p, e, a, b, d, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)")
  1851. template binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  1852. assert(d.k == locNone)
  1853. var a = initLocExpr(p, e[1])
  1854. var b = initLocExpr(p, e[2])
  1855. var elem = newRopeAppender()
  1856. rdSetElemLoc(p.config, b, a.t, elem)
  1857. lineF(p, cpsStmts, frmt, [rdLoc(a), elem])
  1858. proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  1859. var a, b, x, y: TLoc
  1860. if (e[1].kind == nkCurly) and fewCmps(p.config, e[1]):
  1861. # a set constructor but not a constant set:
  1862. # do not emit the set, but generate a bunch of comparisons; and if we do
  1863. # so, we skip the unnecessary range check: This is a semantical extension
  1864. # that code now relies on. :-/ XXX
  1865. let ea = if e[2].kind in {nkChckRange, nkChckRange64}:
  1866. e[2][0]
  1867. else:
  1868. e[2]
  1869. a = initLocExpr(p, ea)
  1870. b = initLoc(locExpr, e, OnUnknown)
  1871. if e[1].len > 0:
  1872. b.r = rope("(")
  1873. for i in 0..<e[1].len:
  1874. let it = e[1][i]
  1875. if it.kind == nkRange:
  1876. x = initLocExpr(p, it[0])
  1877. y = initLocExpr(p, it[1])
  1878. b.r.addf("$1 >= $2 && $1 <= $3",
  1879. [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
  1880. else:
  1881. x = initLocExpr(p, it)
  1882. b.r.addf("$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
  1883. if i < e[1].len - 1: b.r.add(" || ")
  1884. b.r.add(")")
  1885. else:
  1886. # handle the case of an empty set
  1887. b.r = rope("0")
  1888. putIntoDest(p, d, e, b.r)
  1889. else:
  1890. assert(e[1].typ != nil)
  1891. assert(e[2].typ != nil)
  1892. a = initLocExpr(p, e[1])
  1893. b = initLocExpr(p, e[2])
  1894. genInExprAux(p, e, a, b, d)
  1895. proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1896. const
  1897. lookupOpr: array[mLeSet..mMinusSet, string] = [
  1898. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1899. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1900. " if (!$3) break;}$n",
  1901. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1902. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1903. " if (!$3) break;}$n" &
  1904. "if ($3) $3 = (#nimCmpMem($4, $5, $2) != 0);$n",
  1905. "&",
  1906. "|",
  1907. "& ~"]
  1908. var a, b: TLoc
  1909. var i: TLoc
  1910. var setType = skipTypes(e[1].typ, abstractVar)
  1911. var size = int(getSize(p.config, setType))
  1912. case size
  1913. of 1, 2, 4, 8:
  1914. case op
  1915. of mIncl:
  1916. case size
  1917. of 1: binaryStmtInExcl(p, e, d, "$1 |= ((NU8)1)<<(($2) & 7);$n")
  1918. of 2: binaryStmtInExcl(p, e, d, "$1 |= ((NU16)1)<<(($2) & 15);$n")
  1919. of 4: binaryStmtInExcl(p, e, d, "$1 |= ((NU32)1)<<(($2) & 31);$n")
  1920. of 8: binaryStmtInExcl(p, e, d, "$1 |= ((NU64)1)<<(($2) & 63);$n")
  1921. else: assert(false, $size)
  1922. of mExcl:
  1923. case size
  1924. of 1: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU8)1) << (($2) & 7));$n")
  1925. of 2: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU16)1) << (($2) & 15));$n")
  1926. of 4: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU32)1) << (($2) & 31));$n")
  1927. of 8: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU64)1) << (($2) & 63));$n")
  1928. else: assert(false, $size)
  1929. of mCard:
  1930. if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
  1931. else: unaryExprChar(p, e, d, "#countBits64($1)")
  1932. of mLtSet: binaryExprChar(p, e, d, "((($1 & ~ $2)==0)&&($1 != $2))")
  1933. of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
  1934. of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
  1935. of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
  1936. of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
  1937. of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
  1938. of mInSet:
  1939. genInOp(p, e, d)
  1940. else: internalError(p.config, e.info, "genSetOp()")
  1941. else:
  1942. case op
  1943. of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n")
  1944. of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n")
  1945. of mCard:
  1946. var a: TLoc = initLocExpr(p, e[1])
  1947. putIntoDest(p, d, e, ropecg(p.module, "#cardSet($1, $2)", [rdCharLoc(a), size]))
  1948. of mLtSet, mLeSet:
  1949. i = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt)) # our counter
  1950. a = initLocExpr(p, e[1])
  1951. b = initLocExpr(p, e[2])
  1952. if d.k == locNone: d = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyBool))
  1953. if op == mLtSet:
  1954. linefmt(p, cpsStmts, lookupOpr[mLtSet],
  1955. [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)])
  1956. else:
  1957. linefmt(p, cpsStmts, lookupOpr[mLeSet],
  1958. [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)])
  1959. of mEqSet:
  1960. assert(e[1].typ != nil)
  1961. assert(e[2].typ != nil)
  1962. var a = initLocExpr(p, e[1])
  1963. var b = initLocExpr(p, e[2])
  1964. putIntoDest(p, d, e, ropecg(p.module, "(#nimCmpMem($1, $2, $3)==0)", [a.rdCharLoc, b.rdCharLoc, size]))
  1965. of mMulSet, mPlusSet, mMinusSet:
  1966. # we inline the simple for loop for better code generation:
  1967. i = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt)) # our counter
  1968. a = initLocExpr(p, e[1])
  1969. b = initLocExpr(p, e[2])
  1970. if d.k == locNone: d = getTemp(p, setType)
  1971. lineF(p, cpsStmts,
  1972. "for ($1 = 0; $1 < $2; $1++) $n" &
  1973. " $3[$1] = $4[$1] $6 $5[$1];$n", [
  1974. rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b),
  1975. rope(lookupOpr[op])])
  1976. of mInSet: genInOp(p, e, d)
  1977. else: internalError(p.config, e.info, "genSetOp")
  1978. proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  1979. unaryExprChar(p, e, d, "$1")
  1980. proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
  1981. const
  1982. ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs, tyUncheckedArray}
  1983. # we use whatever C gives us. Except if we have a value-type, we need to go
  1984. # through its address:
  1985. var a: TLoc = initLocExpr(p, e[1])
  1986. let etyp = skipTypes(e.typ, abstractRange+{tyOwned})
  1987. let srcTyp = skipTypes(e[1].typ, abstractRange)
  1988. if etyp.kind in ValueTypes and lfIndirect notin a.flags:
  1989. putIntoDest(p, d, e, "(*($1*) ($2))" %
  1990. [getTypeDesc(p.module, e.typ), addrLoc(p.config, a)], a.storage)
  1991. elif etyp.kind == tyProc and etyp.callConv == ccClosure and srcTyp.callConv != ccClosure:
  1992. putIntoDest(p, d, e, "(($1) ($2))" %
  1993. [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)], a.storage)
  1994. else:
  1995. # C++ does not like direct casts from pointer to shorter integral types
  1996. if srcTyp.kind in {tyPtr, tyPointer} and etyp.kind in IntegralTypes:
  1997. putIntoDest(p, d, e, "(($1) (ptrdiff_t) ($2))" %
  1998. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1999. elif optSeqDestructors in p.config.globalOptions and etyp.kind in {tySequence, tyString}:
  2000. putIntoDest(p, d, e, "(*($1*) (&$2))" %
  2001. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  2002. elif etyp.kind == tyBool and srcTyp.kind in IntegralTypes:
  2003. putIntoDest(p, d, e, "(($1) != 0)" % [rdCharLoc(a)], a.storage)
  2004. else:
  2005. if etyp.kind == tyPtr:
  2006. # generates the definition of structs for casts like cast[ptr object](addr x)[]
  2007. let internalType = etyp.skipTypes({tyPtr})
  2008. if internalType.kind == tyObject:
  2009. discard getTypeDesc(p.module, internalType)
  2010. putIntoDest(p, d, e, "(($1) ($2))" %
  2011. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  2012. proc genCast(p: BProc, e: PNode, d: var TLoc) =
  2013. const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  2014. let
  2015. destt = skipTypes(e.typ, abstractRange)
  2016. srct = skipTypes(e[1].typ, abstractRange)
  2017. if destt.kind in ValueTypes or srct.kind in ValueTypes:
  2018. # 'cast' and some float type involved? --> use a union.
  2019. inc(p.labels)
  2020. var lbl = p.labels.rope
  2021. var tmp: TLoc = default(TLoc)
  2022. tmp.r = "LOC$1.source" % [lbl]
  2023. let destsize = getSize(p.config, destt)
  2024. let srcsize = getSize(p.config, srct)
  2025. if destsize > srcsize:
  2026. linefmt(p, cpsLocals, "union { $1 dest; $2 source; } LOC$3;$n #nimZeroMem(&LOC$3, sizeof(LOC$3));$n",
  2027. [getTypeDesc(p.module, e.typ), getTypeDesc(p.module, e[1].typ), lbl])
  2028. else:
  2029. linefmt(p, cpsLocals, "union { $1 source; $2 dest; } LOC$3;$n",
  2030. [getTypeDesc(p.module, e[1].typ), getTypeDesc(p.module, e.typ), lbl])
  2031. tmp.k = locExpr
  2032. tmp.lode = lodeTyp srct
  2033. tmp.storage = OnStack
  2034. tmp.flags = {}
  2035. expr(p, e[1], tmp)
  2036. putIntoDest(p, d, e, "LOC$#.dest" % [lbl], tmp.storage)
  2037. else:
  2038. # I prefer the shorter cast version for pointer types -> generate less
  2039. # C code; plus it's the right thing to do for closures:
  2040. genSomeCast(p, e, d)
  2041. proc genRangeChck(p: BProc, n: PNode, d: var TLoc) =
  2042. var a: TLoc = initLocExpr(p, n[0])
  2043. var dest = skipTypes(n.typ, abstractVar)
  2044. if optRangeCheck notin p.options or (dest.kind in {tyUInt..tyUInt64} and
  2045. checkUnsignedConversions notin p.config.legacyFeatures):
  2046. discard "no need to generate a check because it was disabled"
  2047. else:
  2048. let n0t = n[0].typ
  2049. # emit range check:
  2050. if n0t.kind in {tyUInt, tyUInt64}:
  2051. var first = newRopeAppender()
  2052. genLiteral(p, n[1], dest, first)
  2053. var last = newRopeAppender()
  2054. genLiteral(p, n[2], dest, last)
  2055. linefmt(p, cpsStmts, "if ($1 > ($5)($3)){ #raiseRangeErrorNoArgs(); ",
  2056. [rdCharLoc(a), first, last,
  2057. raiser, getTypeDesc(p.module, n0t)])
  2058. raiseInstr(p, p.s(cpsStmts))
  2059. linefmt p, cpsStmts, "}$n", []
  2060. else:
  2061. let raiser =
  2062. case skipTypes(n.typ, abstractVarRange).kind
  2063. of tyUInt..tyUInt64, tyChar: "raiseRangeErrorU"
  2064. of tyFloat..tyFloat128: "raiseRangeErrorF"
  2065. else: "raiseRangeErrorI"
  2066. cgsym(p.module, raiser)
  2067. let boundaryCast =
  2068. if n0t.skipTypes(abstractVarRange).kind in {tyUInt, tyUInt32, tyUInt64}:
  2069. "(NI64)"
  2070. else:
  2071. ""
  2072. var first = newRopeAppender()
  2073. genLiteral(p, n[1], dest, first)
  2074. var last = newRopeAppender()
  2075. genLiteral(p, n[2], dest, last)
  2076. linefmt(p, cpsStmts, "if ($5($1) < $2 || $5($1) > $3){ $4($1, $2, $3); ",
  2077. [rdCharLoc(a), first, last,
  2078. raiser, boundaryCast])
  2079. raiseInstr(p, p.s(cpsStmts))
  2080. linefmt p, cpsStmts, "}$n", []
  2081. putIntoDest(p, d, n, "(($1) ($2))" %
  2082. [getTypeDesc(p.module, dest), rdCharLoc(a)], a.storage)
  2083. proc genConv(p: BProc, e: PNode, d: var TLoc) =
  2084. let destType = e.typ.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink})
  2085. if sameBackendType(destType, e[1].typ):
  2086. expr(p, e[1], d)
  2087. else:
  2088. genSomeCast(p, e, d)
  2089. proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  2090. var a: TLoc = initLocExpr(p, n[0])
  2091. putIntoDest(p, d, n,
  2092. ropecg(p.module, "#nimToCStringConv($1)", [rdLoc(a)]),
  2093. # "($1 ? $1->data : (NCSTRING)\"\")" % [a.rdLoc],
  2094. a.storage)
  2095. proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  2096. var a: TLoc = initLocExpr(p, n[0])
  2097. if p.module.compileToCpp:
  2098. # fixes for const qualifier; bug #12703; bug #19588
  2099. putIntoDest(p, d, n,
  2100. ropecg(p.module, "#cstrToNimstr((NCSTRING) $1)", [rdLoc(a)]),
  2101. a.storage)
  2102. else:
  2103. putIntoDest(p, d, n,
  2104. ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]),
  2105. a.storage)
  2106. gcUsage(p.config, n)
  2107. proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  2108. var x: TLoc
  2109. var a = e[1]
  2110. var b = e[2]
  2111. if a.kind in {nkStrLit..nkTripleStrLit} and a.strVal == "":
  2112. x = initLocExpr(p, e[2])
  2113. putIntoDest(p, d, e,
  2114. ropecg(p.module, "($1 == 0)", [lenExpr(p, x)]))
  2115. elif b.kind in {nkStrLit..nkTripleStrLit} and b.strVal == "":
  2116. x = initLocExpr(p, e[1])
  2117. putIntoDest(p, d, e,
  2118. ropecg(p.module, "($1 == 0)", [lenExpr(p, x)]))
  2119. else:
  2120. binaryExpr(p, e, d, "#eqStrings($1, $2)")
  2121. proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  2122. if {optNaNCheck, optInfCheck} * p.options != {}:
  2123. const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
  2124. assert(e[1].typ != nil)
  2125. assert(e[2].typ != nil)
  2126. var a = initLocExpr(p, e[1])
  2127. var b = initLocExpr(p, e[2])
  2128. putIntoDest(p, d, e, ropecg(p.module, "(($4)($2) $1 ($4)($3))",
  2129. [opr[m], rdLoc(a), rdLoc(b),
  2130. getSimpleTypeDesc(p.module, e[1].typ)]))
  2131. if optNaNCheck in p.options:
  2132. linefmt(p, cpsStmts, "if ($1 != $1){ #raiseFloatInvalidOp(); ", [rdLoc(d)])
  2133. raiseInstr(p, p.s(cpsStmts))
  2134. linefmt p, cpsStmts, "}$n", []
  2135. if optInfCheck in p.options:
  2136. linefmt(p, cpsStmts, "if ($1 != 0.0 && $1*0.5 == $1) { #raiseFloatOverflow($1); ", [rdLoc(d)])
  2137. raiseInstr(p, p.s(cpsStmts))
  2138. linefmt p, cpsStmts, "}$n", []
  2139. else:
  2140. binaryArith(p, e, d, m)
  2141. proc genWasMoved(p: BProc; n: PNode) =
  2142. var a: TLoc
  2143. let n1 = n[1].skipAddr
  2144. if p.withinBlockLeaveActions > 0 and notYetAlive(n1):
  2145. discard
  2146. else:
  2147. a = initLocExpr(p, n1, {lfEnforceDeref})
  2148. resetLoc(p, a)
  2149. #linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  2150. # [addrLoc(p.config, a), getTypeDesc(p.module, a.t)])
  2151. proc genMove(p: BProc; n: PNode; d: var TLoc) =
  2152. var a: TLoc = initLocExpr(p, n[1].skipAddr)
  2153. if n.len == 4:
  2154. # generated by liftdestructors:
  2155. var src: TLoc = initLocExpr(p, n[2])
  2156. linefmt(p, cpsStmts, "if ($1.p != $2.p) {", [rdLoc(a), rdLoc(src)])
  2157. genStmts(p, n[3])
  2158. linefmt(p, cpsStmts, "}$n$1.len = $2.len; $1.p = $2.p;$n", [rdLoc(a), rdLoc(src)])
  2159. else:
  2160. if d.k == locNone: d = getTemp(p, n.typ)
  2161. if p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  2162. genAssignment(p, d, a, {})
  2163. var op = getAttachedOp(p.module.g.graph, n.typ, attachedWasMoved)
  2164. if op == nil:
  2165. resetLoc(p, a)
  2166. else:
  2167. var b = initLocExpr(p, newSymNode(op))
  2168. case skipTypes(a.t, abstractVar+{tyStatic}).kind
  2169. of tyOpenArray, tyVarargs: # todo fixme generated `wasMoved` hooks for
  2170. # openarrays, but it probably shouldn't?
  2171. var s: string
  2172. if reifiedOpenArray(a.lode):
  2173. if a.t.kind in {tyVar, tyLent}:
  2174. s = "$1->Field0, $1->Field1" % [rdLoc(a)]
  2175. else:
  2176. s = "$1.Field0, $1.Field1" % [rdLoc(a)]
  2177. else:
  2178. s = "$1, $1Len_0" % [rdLoc(a)]
  2179. linefmt(p, cpsStmts, "$1($2);$n", [rdLoc(b), s])
  2180. else:
  2181. if p.module.compileToCpp:
  2182. linefmt(p, cpsStmts, "$1($2);$n", [rdLoc(b), rdLoc(a)])
  2183. else:
  2184. linefmt(p, cpsStmts, "$1($2);$n", [rdLoc(b), byRefLoc(p, a)])
  2185. else:
  2186. let flags = if not canMove(p, n[1], d): {needToCopy} else: {}
  2187. genAssignment(p, d, a, flags)
  2188. resetLoc(p, a)
  2189. proc genDestroy(p: BProc; n: PNode) =
  2190. if optSeqDestructors in p.config.globalOptions:
  2191. let arg = n[1].skipAddr
  2192. let t = arg.typ.skipTypes(abstractInst)
  2193. case t.kind
  2194. of tyString:
  2195. var a: TLoc = initLocExpr(p, arg)
  2196. if optThreads in p.config.globalOptions:
  2197. linefmt(p, cpsStmts, "if ($1.p && !($1.p->cap & NIM_STRLIT_FLAG)) {$n" &
  2198. " #deallocShared($1.p);$n" &
  2199. "}$n", [rdLoc(a)])
  2200. else:
  2201. linefmt(p, cpsStmts, "if ($1.p && !($1.p->cap & NIM_STRLIT_FLAG)) {$n" &
  2202. " #dealloc($1.p);$n" &
  2203. "}$n", [rdLoc(a)])
  2204. of tySequence:
  2205. var a: TLoc = initLocExpr(p, arg)
  2206. linefmt(p, cpsStmts, "if ($1.p && !($1.p->cap & NIM_STRLIT_FLAG)) {$n" &
  2207. " #alignedDealloc($1.p, NIM_ALIGNOF($2));$n" &
  2208. "}$n",
  2209. [rdLoc(a), getTypeDesc(p.module, t.elementType)])
  2210. else: discard "nothing to do"
  2211. else:
  2212. let t = n[1].typ.skipTypes(abstractVar)
  2213. let op = getAttachedOp(p.module.g.graph, t, attachedDestructor)
  2214. if op != nil and getBody(p.module.g.graph, op).len != 0:
  2215. internalError(p.config, n.info, "destructor turned out to be not trivial")
  2216. discard "ignore calls to the default destructor"
  2217. proc genDispose(p: BProc; n: PNode) =
  2218. when false:
  2219. let elemType = n[1].typ.skipTypes(abstractVar).elementType
  2220. var a: TLoc = initLocExpr(p, n[1].skipAddr)
  2221. if isFinal(elemType):
  2222. if elemType.destructor != nil:
  2223. var destroyCall = newNodeI(nkCall, n.info)
  2224. genStmts(p, destroyCall)
  2225. lineFmt(p, cpsStmts, "#nimRawDispose($1, NIM_ALIGNOF($2))", [rdLoc(a), getTypeDesc(p.module, elemType)])
  2226. else:
  2227. # ``nimRawDisposeVirtual`` calls the ``finalizer`` which is the same as the
  2228. # destructor, but it uses the runtime type. Afterwards the memory is freed:
  2229. lineCg(p, cpsStmts, ["#nimDestroyAndDispose($#)", rdLoc(a)])
  2230. proc genSlice(p: BProc; e: PNode; d: var TLoc) =
  2231. let (x, y) = genOpenArraySlice(p, e, e.typ, e.typ.elementType,
  2232. prepareForMutation = e[1].kind == nkHiddenDeref and
  2233. e[1].typ.skipTypes(abstractInst).kind == tyString and
  2234. p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc})
  2235. if d.k == locNone: d = getTemp(p, e.typ)
  2236. linefmt(p, cpsStmts, "$1.Field0 = $2; $1.Field1 = $3;$n", [rdLoc(d), x, y])
  2237. when false:
  2238. localError(p.config, e.info, "invalid context for 'toOpenArray'; " &
  2239. "'toOpenArray' is only valid within a call expression")
  2240. proc genEnumToStr(p: BProc, e: PNode, d: var TLoc) =
  2241. let t = e[1].typ.skipTypes(abstractInst+{tyRange})
  2242. let toStrProc = getToStringProc(p.module.g.graph, t)
  2243. # XXX need to modify this logic for IC.
  2244. var n = copyTree(e)
  2245. n[0] = newSymNode(toStrProc)
  2246. expr(p, n, d)
  2247. proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  2248. case op
  2249. of mOr, mAnd: genAndOr(p, e, d, op)
  2250. of mNot..mUnaryMinusF64: unaryArith(p, e, d, op)
  2251. of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  2252. of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  2253. of mShrI..mXor: binaryArith(p, e, d, op)
  2254. of mEqProc: genEqProc(p, e, d)
  2255. of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  2256. of mRepr: genRepr(p, e, d)
  2257. of mGetTypeInfo: genGetTypeInfo(p, e, d)
  2258. of mGetTypeInfoV2: genGetTypeInfoV2(p, e, d)
  2259. of mSwap: genSwap(p, e, d)
  2260. of mInc, mDec:
  2261. const opr: array[mInc..mDec, string] = ["+=", "-="]
  2262. const fun64: array[mInc..mDec, string] = ["nimAddInt64", "nimSubInt64"]
  2263. const fun: array[mInc..mDec, string] = ["nimAddInt","nimSubInt"]
  2264. let underlying = skipTypes(e[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent, tyRange, tyDistinct})
  2265. if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
  2266. binaryStmt(p, e, d, opr[op])
  2267. else:
  2268. assert(e[1].typ != nil)
  2269. assert(e[2].typ != nil)
  2270. var a = initLocExpr(p, e[1])
  2271. var b = initLocExpr(p, e[2])
  2272. let ranged = skipTypes(e[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent, tyDistinct})
  2273. let res = binaryArithOverflowRaw(p, ranged, a, b,
  2274. if underlying.kind == tyInt64: fun64[op] else: fun[op])
  2275. putIntoDest(p, a, e[1], "($#)($#)" % [
  2276. getTypeDesc(p.module, ranged), res])
  2277. of mConStrStr: genStrConcat(p, e, d)
  2278. of mAppendStrCh:
  2279. if optSeqDestructors in p.config.globalOptions:
  2280. binaryStmtAddr(p, e, d, "nimAddCharV1")
  2281. else:
  2282. var call = initLoc(locCall, e, OnHeap)
  2283. var dest = initLocExpr(p, e[1])
  2284. var b = initLocExpr(p, e[2])
  2285. call.r = ropecg(p.module, "#addChar($1, $2)", [rdLoc(dest), rdLoc(b)])
  2286. genAssignment(p, dest, call, {})
  2287. of mAppendStrStr: genStrAppend(p, e, d)
  2288. of mAppendSeqElem:
  2289. if optSeqDestructors in p.config.globalOptions:
  2290. e[1] = makeAddr(e[1], p.module.idgen)
  2291. genCall(p, e, d)
  2292. else:
  2293. genSeqElemAppend(p, e, d)
  2294. of mEqStr: genStrEquals(p, e, d)
  2295. of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  2296. of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  2297. of mIsNil: genIsNil(p, e, d)
  2298. of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  2299. of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  2300. of mCStrToStr:
  2301. if p.module.compileToCpp:
  2302. # fixes for const qualifier; bug #12703; bug #19588
  2303. genDollar(p, e, d, "#cstrToNimstr((NCSTRING) $1)")
  2304. else:
  2305. genDollar(p, e, d, "#cstrToNimstr($1)")
  2306. of mStrToStr, mUnown: expr(p, e[1], d)
  2307. of generatedMagics: genCall(p, e, d)
  2308. of mEnumToStr:
  2309. if optTinyRtti in p.config.globalOptions:
  2310. genEnumToStr(p, e, d)
  2311. else:
  2312. genRepr(p, e, d)
  2313. of mOf: genOf(p, e, d)
  2314. of mNew: genNew(p, e)
  2315. of mNewFinalize:
  2316. if optTinyRtti in p.config.globalOptions:
  2317. var a: TLoc = initLocExpr(p, e[1])
  2318. rawGenNew(p, a, "", needsInit = true)
  2319. gcUsage(p.config, e)
  2320. else:
  2321. genNewFinalize(p, e)
  2322. of mNewSeq:
  2323. if optSeqDestructors in p.config.globalOptions:
  2324. e[1] = makeAddr(e[1], p.module.idgen)
  2325. genCall(p, e, d)
  2326. else:
  2327. genNewSeq(p, e)
  2328. of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  2329. of mSizeOf:
  2330. let t = e[1].typ.skipTypes({tyTypeDesc})
  2331. putIntoDest(p, d, e, "((NI)sizeof($1))" % [getTypeDesc(p.module, t, dkVar)])
  2332. of mAlignOf:
  2333. let t = e[1].typ.skipTypes({tyTypeDesc})
  2334. putIntoDest(p, d, e, "((NI)NIM_ALIGNOF($1))" % [getTypeDesc(p.module, t, dkVar)])
  2335. of mOffsetOf:
  2336. var dotExpr: PNode
  2337. if e[1].kind == nkDotExpr:
  2338. dotExpr = e[1]
  2339. elif e[1].kind == nkCheckedFieldExpr:
  2340. dotExpr = e[1][0]
  2341. else:
  2342. dotExpr = nil
  2343. internalError(p.config, e.info, "unknown ast")
  2344. let t = dotExpr[0].typ.skipTypes({tyTypeDesc})
  2345. let tname = getTypeDesc(p.module, t, dkVar)
  2346. let member =
  2347. if t.kind == tyTuple:
  2348. "Field" & rope(dotExpr[1].sym.position)
  2349. else: dotExpr[1].sym.loc.r
  2350. putIntoDest(p,d,e, "((NI)offsetof($1, $2))" % [tname, member])
  2351. of mChr: genSomeCast(p, e, d)
  2352. of mOrd: genOrd(p, e, d)
  2353. of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
  2354. genArrayLen(p, e, d, op)
  2355. of mGCref:
  2356. # only a magic for the old GCs
  2357. unaryStmt(p, e, d, "if ($1) { #nimGCref($1); }$n")
  2358. of mGCunref:
  2359. # only a magic for the old GCs
  2360. unaryStmt(p, e, d, "if ($1) { #nimGCunref($1); }$n")
  2361. of mSetLengthStr: genSetLengthStr(p, e, d)
  2362. of mSetLengthSeq: genSetLengthSeq(p, e, d)
  2363. of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
  2364. mInSet:
  2365. genSetOp(p, e, d, op)
  2366. of mNewString, mNewStringOfCap, mExit, mParseBiggestFloat:
  2367. var opr = e[0].sym
  2368. # Why would anyone want to set nodecl to one of these hardcoded magics?
  2369. # - not sure, and it wouldn't work if the symbol behind the magic isn't
  2370. # somehow forward-declared from some other usage, but it is *possible*
  2371. if lfNoDecl notin opr.loc.flags:
  2372. let prc = magicsys.getCompilerProc(p.module.g.graph, $opr.loc.r)
  2373. assert prc != nil, $opr.loc.r
  2374. # HACK:
  2375. # Explicitly add this proc as declared here so the cgsym call doesn't
  2376. # add a forward declaration - without this we could end up with the same
  2377. # 2 forward declarations. That happens because the magic symbol and the original
  2378. # one that shall be used have different ids (even though a call to one is
  2379. # actually a call to the other) so checking into m.declaredProtos with the 2 different ids doesn't work.
  2380. # Why would 2 identical forward declarations be a problem?
  2381. # - in the case of hot code-reloading we generate function pointers instead
  2382. # of forward declarations and in C++ it is an error to redefine a global
  2383. let wasDeclared = containsOrIncl(p.module.declaredProtos, prc.id)
  2384. # Make the function behind the magic get actually generated - this will
  2385. # not lead to a forward declaration! The genCall will lead to one.
  2386. cgsym(p.module, $opr.loc.r)
  2387. # make sure we have pointer-initialising code for hot code reloading
  2388. if not wasDeclared and p.hcrOn:
  2389. p.module.s[cfsDynLibInit].addf("\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  2390. [mangleDynLibProc(prc), getTypeDesc(p.module, prc.loc.t), getModuleDllPath(p.module, prc)])
  2391. genCall(p, e, d)
  2392. of mDefault, mZeroDefault: genDefault(p, e, d)
  2393. of mReset: genReset(p, e)
  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)