ccgexprs.nim 131 KB

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