ccgexprs.nim 132 KB

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