ccgexprs.nim 133 KB

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