ccgexprs.nim 130 KB

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