ccgexprs.nim 104 KB

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