ccgexprs.nim 131 KB

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