ccgexprs.nim 146 KB

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