summary refs log tree commit diff stats
path: root/compiler/ccgexprs.nim
blob: d10b37432ab4ac11e4880a78181d1316295c1cf2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
#
#
#           The Nimrod Compiler
#        (c) Copyright 2012 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# included from cgen.nim

proc lenField: PRope {.inline.} = 
  result = toRope(if gCmd != cmdCompileToCpp: "Sup.len" else: "len")

# -------------------------- constant expressions ------------------------

proc intLiteral(i: biggestInt): PRope =
  if (i > low(int32)) and (i <= high(int32)):
    result = toRope(i)
  elif i == low(int32):
    # Nimrod has the same bug for the same reasons :-)
    result = toRope("(-2147483647 -1)")
  elif i > low(int64):
    result = ropef("IL64($1)", [toRope(i)])
  else:
    result = toRope("(IL64(-9223372036854775807) - IL64(1))")

proc int32Literal(i: Int): PRope =
  if i == int(low(int32)):
    result = toRope("(-2147483647 -1)")
  else:
    result = toRope(i)

proc genHexLiteral(v: PNode): PRope =
  # hex literals are unsigned in C
  # so we don't generate hex literals any longer.
  if not (v.kind in {nkIntLit..nkUInt64Lit}):
    internalError(v.info, "genHexLiteral")
  result = intLiteral(v.intVal)

proc getStrLit(m: BModule, s: string): PRope =
  discard cgsym(m, "TGenericSeq")
  result = con("TMP", toRope(backendId()))
  appf(m.s[cfsData], "STRING_LITERAL($1, $2, $3);$n",
       [result, makeCString(s), ToRope(len(s))])

proc genLiteral(p: BProc, n: PNode, ty: PType): PRope =
  if ty == nil: internalError(n.info, "genLiteral: ty is nil")
  case n.kind
  of nkCharLit..nkUInt64Lit:
    case skipTypes(ty, abstractVarRange).kind
    of tyChar, tyInt64, tyNil:
      result = intLiteral(n.intVal)
    of tyInt:
      if (n.intVal >= low(int32)) and (n.intVal <= high(int32)):
        result = int32Literal(int32(n.intVal))
      else:
        result = intLiteral(n.intVal)
    of tyBool:
      if n.intVal != 0: result = toRope("NIM_TRUE")
      else: result = toRope("NIM_FALSE")
    else:
      result = ropef("(($1) $2)", [getTypeDesc(p.module,
          skipTypes(ty, abstractVarRange)), intLiteral(n.intVal)])
  of nkNilLit:
    let t = skipTypes(ty, abstractVarRange)
    if t.kind == tyProc and t.callConv == ccClosure:
      var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId)
      result = con("TMP", toRope(id))
      if id == gBackendId:
        # not found in cache:
        inc(gBackendId)
        appf(p.module.s[cfsData],
             "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n",
             [getTypeDesc(p.module, t), result])
    else:
      result = toRope("NIM_NIL")
  of nkStrLit..nkTripleStrLit:
    if skipTypes(ty, abstractVarRange).kind == tyString:
      var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId)
      if id == gBackendId:
        # string literal not found in the cache:
        result = ropecg(p.module, "((#NimStringDesc*) &$1)", 
                        [getStrLit(p.module, n.strVal)])
      else:
        result = ropecg(p.module, "((#NimStringDesc*) &TMP$1)", [toRope(id)])
    else:
      result = makeCString(n.strVal)
  of nkFloatLit..nkFloat64Lit:
    result = toRope(n.floatVal.ToStrMaxPrecision)
  else:
    InternalError(n.info, "genLiteral(" & $n.kind & ')')
    result = nil

proc genLiteral(p: BProc, n: PNode): PRope =
  result = genLiteral(p, n, n.typ)

proc bitSetToWord(s: TBitSet, size: int): BiggestInt =
  result = 0
  when true:
    for j in countup(0, size - 1):
      if j < len(s): result = result or `shl`(Ze64(s[j]), j * 8)
  else:
    # not needed, too complex thinking:
    if CPU[platform.hostCPU].endian == CPU[targetCPU].endian:
      for j in countup(0, size - 1):
        if j < len(s): result = result or `shl`(Ze64(s[j]), j * 8)
    else:
      for j in countup(0, size - 1):
        if j < len(s): result = result or `shl`(Ze64(s[j]), (Size - 1 - j) * 8)

proc genRawSetData(cs: TBitSet, size: int): PRope =
  var frmt: TFormatStr
  if size > 8:
    result = ropef("{$n")
    for i in countup(0, size - 1):
      if i < size - 1:
        # not last iteration?
        if (i + 1) mod 8 == 0: frmt = "0x$1,$n"
        else: frmt = "0x$1, "
      else:
        frmt = "0x$1}$n"
      appf(result, frmt, [toRope(toHex(Ze64(cs[i]), 2))])
  else:
    result = intLiteral(bitSetToWord(cs, size))
    #  result := toRope('0x' + ToHex(bitSetToWord(cs, size), size * 2))

proc genSetNode(p: BProc, n: PNode): PRope =
  var cs: TBitSet
  var size = int(getSize(n.typ))
  toBitSet(n, cs)
  if size > 8:
    var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId)
    result = con("TMP", toRope(id))
    if id == gBackendId:
      # not found in cache:
      inc(gBackendId)
      appf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
           [getTypeDesc(p.module, n.typ), result, genRawSetData(cs, size)])
  else:
    result = genRawSetData(cs, size)

proc getStorageLoc(n: PNode): TStorageLoc =
  case n.kind
  of nkSym:
    case n.sym.kind
    of skParam, skTemp:
      result = OnStack
    of skVar, skForVar, skResult, skLet:
      if sfGlobal in n.sym.flags: result = OnHeap
      else: result = OnStack
    of skConst: 
      if sfGlobal in n.sym.flags: result = OnHeap
      else: result = OnUnknown
    else: result = OnUnknown
  of nkDerefExpr, nkHiddenDeref:
    case n.sons[0].typ.kind
    of tyVar: result = OnUnknown
    of tyPtr: result = OnStack
    of tyRef: result = OnHeap
    else: InternalError(n.info, "getStorageLoc")
  of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv:
    result = getStorageLoc(n.sons[0])
  else: result = OnUnknown

proc genRefAssign(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  if dest.s == OnStack or optRefcGC notin gGlobalOptions:
    lineF(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
    if needToKeepAlive in flags: keepAlive(p, dest)
  elif dest.s == OnHeap:
    # location is on heap
    # now the writer barrier is inlined for performance:
    #
    #    if afSrcIsNotNil in flags:
    #      UseMagic(p.module, 'nimGCref')
    #      lineF(p, cpsStmts, 'nimGCref($1);$n', [rdLoc(src)])
    #    elif afSrcIsNil notin flags:
    #      UseMagic(p.module, 'nimGCref')
    #      lineF(p, cpsStmts, 'if ($1) nimGCref($1);$n', [rdLoc(src)])
    #    if afDestIsNotNil in flags:
    #      UseMagic(p.module, 'nimGCunref')
    #      lineF(p, cpsStmts, 'nimGCunref($1);$n', [rdLoc(dest)])
    #    elif afDestIsNil notin flags:
    #      UseMagic(p.module, 'nimGCunref')
    #      lineF(p, cpsStmts, 'if ($1) nimGCunref($1);$n', [rdLoc(dest)])
    #    lineF(p, cpsStmts, '$1 = $2;$n', [rdLoc(dest), rdLoc(src)])
    if canFormAcycle(dest.t):
      lineCg(p, cpsStmts, "#asgnRef((void**) $1, $2);$n",
           [addrLoc(dest), rdLoc(src)])
    else:
      lineCg(p, cpsStmts, "#asgnRefNoCycle((void**) $1, $2);$n",
           [addrLoc(dest), rdLoc(src)])
  else:
    lineCg(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
         [addrLoc(dest), rdLoc(src)])
    if needToKeepAlive in flags: keepAlive(p, dest)

proc genGenericAsgn(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  # Consider: 
  # type TMyFastString {.shallow.} = string
  # Due to the implementation of pragmas this would end up to set the
  # tfShallow flag for the built-in string type too! So we check only
  # here for this flag, where it is reasonably safe to do so
  # (for objects, etc.):
  if needToCopy notin flags or 
      tfShallow in skipTypes(dest.t, abstractVarRange).flags:
    if dest.s == OnStack or optRefcGC notin gGlobalOptions:
      lineCg(p, cpsStmts,
           "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
           [addrLoc(dest), addrLoc(src), rdLoc(dest)])
      if needToKeepAlive in flags: keepAlive(p, dest)
    else:
      lineCg(p, cpsStmts, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n",
           [addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t)])
  else:
    lineCg(p, cpsStmts, "#genericAssign((void*)$1, (void*)$2, $3);$n",
         [addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t)])

proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  # This function replaces all other methods for generating
  # the assignment operation in C.
  if src.t != nil and src.t.kind == tyPtr:
    # little HACK to support the new 'var T' as return type:
    lineCg(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
    return
  var ty = skipTypes(dest.t, abstractVarRange)
  case ty.kind
  of tyRef:
    genRefAssign(p, dest, src, flags)
  of tySequence:
    if needToCopy notin flags:
      genRefAssign(p, dest, src, flags)
    else:
      lineCg(p, cpsStmts, "#genericSeqAssign($1, $2, $3);$n",
           [addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t)])
  of tyString:
    if needToCopy notin flags:
      genRefAssign(p, dest, src, flags)
    else:
      if dest.s == OnStack or optRefcGC notin gGlobalOptions:
        lineCg(p, cpsStmts, "$1 = #copyString($2);$n", [dest.rdLoc, src.rdLoc])
        if needToKeepAlive in flags: keepAlive(p, dest)
      elif dest.s == OnHeap:
        # we use a temporary to care for the dreaded self assignment:
        var tmp: TLoc
        getTemp(p, ty, tmp)
        lineCg(p, cpsStmts, "$3 = $1; $1 = #copyStringRC1($2);$n",
             [dest.rdLoc, src.rdLoc, tmp.rdLoc])
        lineCg(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", tmp.rdLoc)
      else:
        lineCg(p, cpsStmts, "#unsureAsgnRef((void**) $1, #copyString($2));$n",
             [addrLoc(dest), rdLoc(src)])
        if needToKeepAlive in flags: keepAlive(p, dest)
  of tyTuple, tyObject, tyProc:
    # XXX: check for subtyping?
    if needsComplexAssignment(dest.t):
      genGenericAsgn(p, dest, src, flags)
    else:
      lineCg(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  of tyArray, tyArrayConstr:
    if needsComplexAssignment(dest.t):
      genGenericAsgn(p, dest, src, flags)
    else:
      lineCg(p, cpsStmts,
           "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1));$n",
           [rdLoc(dest), rdLoc(src)])
  of tyOpenArray, tyVarargs:
    # open arrays are always on the stack - really? What if a sequence is
    # passed to an open array?
    if needsComplexAssignment(dest.t):
      lineCg(p, cpsStmts,     # XXX: is this correct for arrays?
           "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n",
           [addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t)])
    else:
      lineCg(p, cpsStmts,
           "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len0);$n",
           [rdLoc(dest), rdLoc(src)])
  of tySet:
    if mapType(ty) == ctArray:
      lineCg(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
           [rdLoc(dest), rdLoc(src), toRope(getSize(dest.t))])
    else:
      lineCg(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString,
     tyInt..tyUInt64, tyRange:
    lineCg(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  else: InternalError("genAssignment(" & $ty.kind & ')')

proc expr(p: BProc, e: PNode, d: var TLoc)
proc initLocExpr(p: BProc, e: PNode, result: var TLoc) =
  initLoc(result, locNone, e.typ, OnUnknown)
  expr(p, e, result)

proc getDestLoc(p: BProc, d: var TLoc, typ: PType) =
  if d.k == locNone: getTemp(p, typ, d)

proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) =
  if d.k != locNone:
    if lfNoDeepCopy in d.flags: genAssignment(p, d, s, {})
    else: genAssignment(p, d, s, {needToCopy})
  else:
    d = s # ``d`` is free, so fill it with ``s``

proc putIntoDest(p: BProc, d: var TLoc, t: PType, r: PRope) =
  var a: TLoc
  if d.k != locNone:
    # need to generate an assignment here
    initLoc(a, locExpr, getUniqueType(t), OnUnknown)
    a.r = r
    if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
    else: genAssignment(p, d, a, {needToCopy})
  else:
    # we cannot call initLoc() here as that would overwrite
    # the flags field!
    d.k = locExpr
    d.t = getUniqueType(t)
    d.r = r
    d.a = -1

proc binaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var b: TLoc
  if d.k != locNone: InternalError(e.info, "binaryStmt")
  InitLocExpr(p, e.sons[1], d)
  InitLocExpr(p, e.sons[2], b)
  lineCg(p, cpsStmts, frmt, [rdLoc(d), rdLoc(b)])

proc unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  if (d.k != locNone): InternalError(e.info, "unaryStmt")
  InitLocExpr(p, e.sons[1], a)
  lineCg(p, cpsStmts, frmt, [rdLoc(a)])

proc binaryStmtChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  if (d.k != locNone): InternalError(e.info, "binaryStmtChar")
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  lineCg(p, cpsStmts, frmt, [rdCharLoc(a), rdCharLoc(b)])

proc binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)]))

proc binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc]))

proc unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  InitLocExpr(p, e.sons[1], a)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a)]))

proc unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  InitLocExpr(p, e.sons[1], a)
  putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdCharLoc(a)]))

proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  const
    prc: array[mAddi..mModi64, string] = ["addInt", "subInt", "mulInt",
      "divInt", "modInt", "addInt64", "subInt64", "mulInt64", "divInt64",
      "modInt64"]
    opr: array[mAddi..mModi64, string] = ["+", "-", "*", "/", "%", "+", "-",
      "*", "/", "%"]
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  var t = skipTypes(e.typ, abstractRange)
  if optOverflowCheck notin p.options:
    putIntoDest(p, d, e.typ, ropef("(NI$4)($2 $1 $3)", [toRope(opr[m]),
        rdLoc(a), rdLoc(b), toRope(getSize(t) * 8)]))
  else:
    var storage: PRope
    var size = getSize(t)
    if size < platform.IntSize:
      storage = toRope("NI") 
    else:
      storage = getTypeDesc(p.module, t)
    var tmp = getTempName()
    lineCg(p, cpsLocals, "$1 $2;$n", [storage, tmp])
    lineCg(p, cpsStmts, "$1 = #$2($3, $4);$n", [tmp, toRope(prc[m]), 
                                             rdLoc(a), rdLoc(b)])
    if size < platform.IntSize or t.kind in {tyRange, tyEnum, tySet}:
      lineCg(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
           [tmp, intLiteral(firstOrd(t)), intLiteral(lastOrd(t))])
    putIntoDest(p, d, e.typ, ropef("(NI$1)($2)", [toRope(getSize(t)*8), tmp]))

proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  const
    opr: array[mUnaryMinusI..mAbsI64, string] = [
      mUnaryMinusI: "((NI$2)-($1))",
      mUnaryMinusI64: "-($1)",
      mAbsI: "(NI$2)abs($1)",
      mAbsI64: "($1 > 0? ($1) : -($1))"]
  var
    a: TLoc
    t: PType
  assert(e.sons[1].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  t = skipTypes(e.typ, abstractRange)
  if optOverflowCheck in p.options:
    lineCg(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n",
         [rdLoc(a), intLiteral(firstOrd(t))])
  putIntoDest(p, d, e.typ, ropef(opr[m], [rdLoc(a), toRope(getSize(t) * 8)]))

proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  const
    binArithTab: array[mAddF64..mXor, string] = [
      "($1 + $2)",            # AddF64
      "($1 - $2)",            # SubF64
      "($1 * $2)",            # MulF64
      "($1 / $2)",            # DivF64
      "($4)((NU$3)($1) >> (NU$3)($2))", # ShrI
      "($4)((NU$3)($1) << (NU$3)($2))", # ShlI
      "($4)($1 & $2)",      # BitandI
      "($4)($1 | $2)",      # BitorI
      "($4)($1 ^ $2)",      # BitxorI
      "(($1 <= $2) ? $1 : $2)", # MinI
      "(($1 >= $2) ? $1 : $2)", # MaxI
      "($4)((NU64)($1) >> (NU64)($2))", # ShrI64
      "($4)((NU64)($1) << (NU64)($2))", # ShlI64
      "($4)($1 & $2)",            # BitandI64
      "($4)($1 | $2)",            # BitorI64
      "($4)($1 ^ $2)",            # BitxorI64
      "(($1 <= $2) ? $1 : $2)", # MinI64
      "(($1 >= $2) ? $1 : $2)", # MaxI64
      "(($1 <= $2) ? $1 : $2)", # MinF64
      "(($1 >= $2) ? $1 : $2)", # MaxF64
      "($4)((NU$3)($1) + (NU$3)($2))", # AddU
      "($4)((NU$3)($1) - (NU$3)($2))", # SubU
      "($4)((NU$3)($1) * (NU$3)($2))", # MulU
      "($4)((NU$3)($1) / (NU$3)($2))", # DivU
      "($4)((NU$3)($1) % (NU$3)($2))", # ModU
      "($1 == $2)",           # EqI
      "($1 <= $2)",           # LeI
      "($1 < $2)",            # LtI
      "($1 == $2)",           # EqI64
      "($1 <= $2)",           # LeI64
      "($1 < $2)",            # LtI64
      "($1 == $2)",           # EqF64
      "($1 <= $2)",           # LeF64
      "($1 < $2)",            # LtF64
      "((NU$3)($1) <= (NU$3)($2))", # LeU
      "((NU$3)($1) < (NU$3)($2))", # LtU
      "((NU64)($1) <= (NU64)($2))", # LeU64
      "((NU64)($1) < (NU64)($2))", # LtU64
      "($1 == $2)",           # EqEnum
      "($1 <= $2)",           # LeEnum
      "($1 < $2)",            # LtEnum
      "((NU8)($1) == (NU8)($2))", # EqCh
      "((NU8)($1) <= (NU8)($2))", # LeCh
      "((NU8)($1) < (NU8)($2))", # LtCh
      "($1 == $2)",           # EqB
      "($1 <= $2)",           # LeB
      "($1 < $2)",            # LtB
      "($1 == $2)",           # EqRef
      "($1 == $2)",           # EqPtr
      "($1 <= $2)",           # LePtr
      "($1 < $2)",            # LtPtr
      "($1 == $2)",           # EqCString
      "($1 != $2)"]           # Xor
  var
    a, b: TLoc
    s: biggestInt
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  # BUGFIX: cannot use result-type here, as it may be a boolean
  s = max(getSize(a.t), getSize(b.t)) * 8
  putIntoDest(p, d, e.typ,
              ropef(binArithTab[op], [rdLoc(a), rdLoc(b), toRope(s),
                                      getSimpleTypeDesc(p.module, e.typ)]))

proc genEqProc(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  assert(e.sons[1].typ != nil)
  assert(e.sons[2].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  if a.t.callConv == ccClosure:
    putIntoDest(p, d, e.typ, 
      ropef("($1.ClPrc == $2.ClPrc && $1.ClEnv == $2.ClEnv)", [
      rdLoc(a), rdLoc(b)]))
  else:
    putIntoDest(p, d, e.typ, ropef("($1 == $2)", [rdLoc(a), rdLoc(b)]))

proc genIsNil(p: BProc, e: PNode, d: var TLoc) =
  let t = skipTypes(e.sons[1].typ, abstractRange)
  if t.kind == tyProc and t.callConv == ccClosure:
    unaryExpr(p, e, d, "$1.ClPrc == 0")
  else:
    unaryExpr(p, e, d, "$1 == 0")

proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  const
    unArithTab: array[mNot..mToBiggestInt, string] = ["!($1)", # Not
      "$1",                   # UnaryPlusI
      "($3)((NU$2) ~($1))",   # BitnotI
      "$1",                   # UnaryPlusI64
      "($3)((NU$2) ~($1))",   # BitnotI64
      "$1",                   # UnaryPlusF64
      "-($1)",                # UnaryMinusF64
      "($1 > 0? ($1) : -($1))", # AbsF64; BUGFIX: fabs() makes problems
                                # for Tiny C, so we don't use it
      "(($3)(NU)(NU8)($1))",  # mZe8ToI
      "(($3)(NU64)(NU8)($1))", # mZe8ToI64
      "(($3)(NU)(NU16)($1))", # mZe16ToI
      "(($3)(NU64)(NU16)($1))", # mZe16ToI64
      "(($3)(NU64)(NU32)($1))", # mZe32ToI64
      "(($3)(NU64)(NU)($1))", # mZeIToI64
      "(($3)(NU8)(NU)($1))", # ToU8
      "(($3)(NU16)(NU)($1))", # ToU16
      "(($3)(NU32)(NU64)($1))", # ToU32
      "((double) ($1))",      # ToFloat
      "((double) ($1))",      # ToBiggestFloat
      "float64ToInt32($1)",   # ToInt
      "float64ToInt64($1)"]   # ToBiggestInt
  var
    a: TLoc
    t: PType
  assert(e.sons[1].typ != nil)
  InitLocExpr(p, e.sons[1], a)
  t = skipTypes(e.typ, abstractRange)
  putIntoDest(p, d, e.typ,
              ropef(unArithTab[op], [rdLoc(a), toRope(getSize(t) * 8),
                    getSimpleTypeDesc(p.module, e.typ)]))

proc genDeref(p: BProc, e: PNode, d: var TLoc) =
  var a: TLoc
  if mapType(e.sons[0].typ) == ctArray:
    # XXX the amount of hacks for C's arrays is incredible, maybe we should
    # simply wrap them in a struct? --> Losing auto vectorization then?
    expr(p, e.sons[0], d)
  else:
    initLocExpr(p, e.sons[0], a)
    case skipTypes(a.t, abstractInst).kind
    of tyRef:
      d.s = OnHeap
    of tyVar:
      d.s = OnUnknown
    of tyPtr:
      d.s = OnUnknown         # BUGFIX!
    else: InternalError(e.info, "genDeref " & $a.t.kind)
    putIntoDest(p, d, a.t.sons[0], ropef("(*$1)", [rdLoc(a)]))

proc genAddr(p: BProc, e: PNode, d: var TLoc) =
  var a: TLoc
  if mapType(e.sons[0].typ) == ctArray:
    expr(p, e.sons[0], d)
  else:
    InitLocExpr(p, e.sons[0], a)
    putIntoDest(p, d, e.typ, addrLoc(a))

proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc): PType =
  initLocExpr(p, e.sons[0], a)
  if e.sons[1].kind != nkSym: InternalError(e.info, "genRecordFieldAux")
  if d.k == locNone: d.s = a.s
  discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  result = a.t

proc genRecordField(p: BProc, e: PNode, d: var TLoc) =
  var a: TLoc
  var ty = genRecordFieldAux(p, e, d, a)
  var r = rdLoc(a)
  var f = e.sons[1].sym
  if ty.kind == tyTuple:
    # we found a unique tuple type which lacks field information
    # so we use Field$i
    appf(r, ".Field$1", [toRope(f.position)])
    putIntoDest(p, d, f.typ, r)
  else:
    var field: PSym = nil
    while ty != nil:
      if ty.kind notin {tyTuple, tyObject}:
        InternalError(e.info, "genRecordField")
      field = lookupInRecord(ty.n, f.name)
      if field != nil: break
      if gCmd != cmdCompileToCpp: app(r, ".Sup")
      ty = GetUniqueType(ty.sons[0])
    if field == nil: InternalError(e.info, "genRecordField 2 ")
    if field.loc.r == nil: InternalError(e.info, "genRecordField 3")
    appf(r, ".$1", [field.loc.r])
    putIntoDest(p, d, field.typ, r)

proc genTupleElem(p: BProc, e: PNode, d: var TLoc) =
  var
    a: TLoc
    i: int
  initLocExpr(p, e.sons[0], a)
  if d.k == locNone: d.s = a.s
  discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  var ty = a.t
  var r = rdLoc(a)
  case e.sons[1].kind
  of nkIntLit..nkUInt64Lit: i = int(e.sons[1].intVal)
  else: internalError(e.info, "genTupleElem")
  when false:
    if ty.n != nil:
      var field = ty.n.sons[i].sym
      if field == nil: InternalError(e.info, "genTupleElem")
      if field.loc.r == nil: InternalError(e.info, "genTupleElem")
      appf(r, ".$1", [field.loc.r])
  else:
    appf(r, ".Field$1", [toRope(i)])
  putIntoDest(p, d, ty.sons[i], r)

proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc)
proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) =
  var
    a, u, v, test: TLoc
    f, field, op: PSym
    ty: PType
    r, strLit: PRope
    id: int
    it: PNode
  if optFieldCheck in p.options:
    ty = genRecordFieldAux(p, e.sons[0], d, a)
    r = rdLoc(a)
    f = e.sons[0].sons[1].sym
    field = nil
    while ty != nil:
      assert(ty.kind in {tyTuple, tyObject})
      field = lookupInRecord(ty.n, f.name)
      if field != nil: break
      if gCmd != cmdCompileToCpp: app(r, ".Sup")
      ty = getUniqueType(ty.sons[0])
    if field == nil: InternalError(e.info, "genCheckedRecordField")
    if field.loc.r == nil:
      InternalError(e.info, "genCheckedRecordField") # generate the checks:
    for i in countup(1, sonsLen(e) - 1):
      it = e.sons[i]
      assert(it.kind in nkCallKinds)
      assert(it.sons[0].kind == nkSym)
      op = it.sons[0].sym
      if op.magic == mNot: it = it.sons[1]
      assert(it.sons[2].kind == nkSym)
      initLoc(test, locNone, it.typ, OnStack)
      InitLocExpr(p, it.sons[1], u)
      initLoc(v, locExpr, it.sons[2].typ, OnUnknown)
      v.r = ropef("$1.$2", [r, it.sons[2].sym.loc.r])
      genInExprAux(p, it, u, v, test)
      id = NodeTableTestOrSet(p.module.dataCache,
                              newStrNode(nkStrLit, field.name.s), gBackendId)
      if id == gBackendId: strLit = getStrLit(p.module, field.name.s)
      else: strLit = con("TMP", toRope(id))
      if op.magic == mNot:
        lineCg(p, cpsStmts,
             "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n",
             [rdLoc(test), strLit])
      else:
        lineCg(p, cpsStmts,
             "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n",
             [rdLoc(test), strLit])
    appf(r, ".$1", [field.loc.r])
    putIntoDest(p, d, field.typ, r)
  else:
    genRecordField(p, e.sons[0], d)

proc genArrayElem(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, e.sons[0], a)
  initLocExpr(p, e.sons[1], b)
  var ty = skipTypes(skipTypes(a.t, abstractVarRange), abstractPtrs)
  var first = intLiteral(firstOrd(ty))
  # emit range check:
  if (optBoundsCheck in p.options):
    if not isConstExpr(e.sons[1]):
      # semantic pass has already checked for const index expressions
      if firstOrd(ty) == 0:
        if (firstOrd(b.t) < firstOrd(ty)) or (lastOrd(b.t) > lastOrd(ty)):
          lineCg(p, cpsStmts, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n",
               [rdCharLoc(b), intLiteral(lastOrd(ty))])
      else:
        lineCg(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n",
             [rdCharLoc(b), first, intLiteral(lastOrd(ty))])
  if d.k == locNone: d.s = a.s
  putIntoDest(p, d, elemType(skipTypes(ty, abstractVar)),
              ropef("$1[($2)- $3]", [rdLoc(a), rdCharLoc(b), first]))

proc genCStringElem(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, e.sons[0], a)
  initLocExpr(p, e.sons[1], b)
  var ty = skipTypes(a.t, abstractVarRange)
  if d.k == locNone: d.s = a.s
  putIntoDest(p, d, elemType(skipTypes(ty, abstractVar)),
              ropef("$1[$2]", [rdLoc(a), rdCharLoc(b)]))

proc genOpenArrayElem(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, e.sons[0], a)
  initLocExpr(p, e.sons[1], b) # emit range check:
  if optBoundsCheck in p.options:
    lineCg(p, cpsStmts, "if ((NU)($1) >= (NU)($2Len0)) #raiseIndexError();$n",
         [rdLoc(b), rdLoc(a)]) # BUGFIX: ``>=`` and not ``>``!
  if d.k == locNone: d.s = a.s
  putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)),
              ropef("$1[$2]", [rdLoc(a), rdCharLoc(b)]))

proc genSeqElem(p: BPRoc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  initLocExpr(p, e.sons[0], a)
  initLocExpr(p, e.sons[1], b)
  var ty = skipTypes(a.t, abstractVarRange)
  if ty.kind in {tyRef, tyPtr}:
    ty = skipTypes(ty.sons[0], abstractVarRange) # emit range check:
  if optBoundsCheck in p.options:
    if ty.kind == tyString:
      lineCg(p, cpsStmts,
           "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n",
           [rdLoc(b), rdLoc(a), lenField()])
    else:
      lineCg(p, cpsStmts,
           "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n",
           [rdLoc(b), rdLoc(a), lenField()])
  if d.k == locNone: d.s = OnHeap
  if skipTypes(a.t, abstractVar).kind in {tyRef, tyPtr}:
    a.r = ropef("(*$1)", [a.r])
  putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)),
              ropef("$1->data[$2]", [rdLoc(a), rdCharLoc(b)]))

proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  # how to generate code?
  #  'expr1 and expr2' becomes:
  #     result = expr1
  #     fjmp result, end
  #     result = expr2
  #  end:
  #  ... (result computed)
  # BUGFIX:
  #   a = b or a
  # used to generate:
  # a = b
  # if a: goto end
  # a = a
  # end:
  # now it generates:
  # tmp = b
  # if tmp: goto end
  # tmp = a
  # end:
  # a = tmp
  var
    L: TLabel
    tmp: TLoc
  getTemp(p, e.typ, tmp)      # force it into a temp!
  expr(p, e.sons[1], tmp)
  L = getLabel(p)
  if m == mOr:
    lineF(p, cpsStmts, "if ($1) goto $2;$n", [rdLoc(tmp), L])
  else:
    lineF(p, cpsStmts, "if (!($1)) goto $2;$n", [rdLoc(tmp), L])
  expr(p, e.sons[2], tmp)
  fixLabel(p, L)
  if d.k == locNone:
    d = tmp
  else:
    genAssignment(p, d, tmp, {}) # no need for deep copying

proc genIfExpr(p: BProc, n: PNode, d: var TLoc) =
  #
  #  if (!expr1) goto L1;
  #  thenPart
  #  goto LEnd
  #  L1:
  #  if (!expr2) goto L2;
  #  thenPart2
  #  goto LEnd
  #  L2:
  #  elsePart
  #  Lend:
  #
  var
    it: PNode
    a, tmp: TLoc
    Lend, Lelse: TLabel
  getTemp(p, n.typ, tmp)      # force it into a temp!
  Lend = getLabel(p)
  for i in countup(0, sonsLen(n) - 1):
    it = n.sons[i]
    case it.kind
    of nkElifExpr:
      initLocExpr(p, it.sons[0], a)
      Lelse = getLabel(p)
      lineF(p, cpsStmts, "if (!$1) goto $2;$n", [rdLoc(a), Lelse])
      expr(p, it.sons[1], tmp)
      lineF(p, cpsStmts, "goto $1;$n", [Lend])
      fixLabel(p, Lelse)
    of nkElseExpr:
      expr(p, it.sons[0], tmp)
    else: internalError(n.info, "genIfExpr()")
  fixLabel(p, Lend)
  if d.k == locNone:
    d = tmp
  else:
    genAssignment(p, d, tmp, {}) # no need for deep copying

proc genEcho(p: BProc, n: PNode) =
  # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)``
  # is threadsafe.
  var args: PRope = nil
  var a: TLoc
  for i in countup(1, n.len-1):
    initLocExpr(p, n.sons[i], a)
    appf(args, ", ($1)->data", [rdLoc(a)])
  lineCg(p, cpsStmts, "printf($1$2);$n", [
    makeCString(repeatStr(n.len-1, "%s") & tnl), args])

include ccgcalls

proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
  #   <Nimrod code>
  #   s = 'Hello ' & name & ', how do you feel?' & 'z'
  #
  #   <generated C code>
  #  {
  #    string tmp0;
  #    ...
  #    tmp0 = rawNewString(6 + 17 + 1 + s2->len);
  #    // we cannot generate s = rawNewString(...) here, because
  #    // ``s`` may be used on the right side of the expression
  #    appendString(tmp0, strlit_1);
  #    appendString(tmp0, name);
  #    appendString(tmp0, strlit_2);
  #    appendChar(tmp0, 'z');
  #    asgn(s, tmp0);
  #  }
  var a, tmp: TLoc
  getTemp(p, e.typ, tmp)
  var L = 0
  var appends: PRope = nil
  var lens: PRope = nil
  for i in countup(0, sonsLen(e) - 2):
    # compute the length expression:
    initLocExpr(p, e.sons[i + 1], a)
    if skipTypes(e.sons[i + 1].Typ, abstractVarRange).kind == tyChar:
      Inc(L)
      appLineCg(p, appends, "#appendChar($1, $2);$n", [tmp.r, rdLoc(a)])
    else:
      if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}:
        Inc(L, len(e.sons[i + 1].strVal))
      else:
        appf(lens, "$1->$2 + ", [rdLoc(a), lenField()])
      appLineCg(p, appends, "#appendString($1, $2);$n", [tmp.r, rdLoc(a)])
  lineCg(p, cpsStmts, "$1 = #rawNewString($2$3);$n", [tmp.r, lens, toRope(L)])
  app(p.s(cpsStmts), appends)
  if d.k == locNone:
    d = tmp
    keepAlive(p, tmp)
  else:
    genAssignment(p, d, tmp, {needToKeepAlive}) # no need for deep copying

proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
  #  <Nimrod code>
  #  s &= 'Hello ' & name & ', how do you feel?' & 'z'
  #  // BUG: what if s is on the left side too?
  #  <generated C code>
  #  {
  #    s = resizeString(s, 6 + 17 + 1 + name->len);
  #    appendString(s, strlit_1);
  #    appendString(s, name);
  #    appendString(s, strlit_2);
  #    appendChar(s, 'z');
  #  }
  var
    a, dest: TLoc
    appends, lens: PRope
  assert(d.k == locNone)
  var L = 0
  initLocExpr(p, e.sons[1], dest)
  for i in countup(0, sonsLen(e) - 3):
    # compute the length expression:
    initLocExpr(p, e.sons[i + 2], a)
    if skipTypes(e.sons[i + 2].Typ, abstractVarRange).kind == tyChar:
      Inc(L)
      appLineCg(p, appends, "#appendChar($1, $2);$n",
            [rdLoc(dest), rdLoc(a)])
    else:
      if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}:
        Inc(L, len(e.sons[i + 2].strVal))
      else:
        appf(lens, "$1->$2 + ", [rdLoc(a), lenField()])
      appLineCg(p, appends, "#appendString($1, $2);$n",
            [rdLoc(dest), rdLoc(a)])
  lineCg(p, cpsStmts, "$1 = #resizeString($1, $2$3);$n",
       [rdLoc(dest), lens, toRope(L)])
  keepAlive(p, dest)
  app(p.s(cpsStmts), appends)

proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
  # seq &= x  -->
  #    seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x));
  #    seq->data[seq->len-1] = x;
  let seqAppendPattern = if gCmd != cmdCompileToCpp:
      "$1 = ($2) #incrSeq(&($1)->Sup, sizeof($3));$n"
    else:
      "$1 = ($2) #incrSeq($1, sizeof($3));$n"

  var a, b, dest: TLoc
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  lineCg(p, cpsStmts, seqAppendPattern, [
      rdLoc(a),
      getTypeDesc(p.module, skipTypes(e.sons[1].typ, abstractVar)),
      getTypeDesc(p.module, skipTypes(e.sons[2].Typ, abstractVar))])
  keepAlive(p, a)
  initLoc(dest, locExpr, b.t, OnHeap)
  dest.r = ropef("$1->data[$1->$2-1]", [rdLoc(a), lenField()])
  genAssignment(p, dest, b, {needToCopy, afDestIsNil})

proc genReset(p: BProc, n: PNode) = 
  var a: TLoc
  InitLocExpr(p, n.sons[1], a)
  lineCg(p, cpsStmts, "#genericReset((void*)$1, $2);$n", 
       [addrLoc(a), genTypeInfo(p.module, skipTypes(a.t, abstractVarRange))])

proc genNew(p: BProc, e: PNode) =
  var
    a, b: TLoc
    reftype, bt: PType
  refType = skipTypes(e.sons[1].typ, abstractVarRange)
  InitLocExpr(p, e.sons[1], a)
  initLoc(b, locExpr, a.t, OnHeap)
  let args = [getTypeDesc(p.module, reftype),
              genTypeInfo(p.module, refType),
              getTypeDesc(p.module, skipTypes(reftype.sons[0], abstractRange))]
  if a.s == OnHeap and optRefcGc in gGlobalOptions:
    # use newObjRC1 as an optimization; and we don't need 'keepAlive' either
    if canFormAcycle(a.t):
      lineCg(p, cpsStmts, "if ($1) #nimGCunref($1);$n", a.rdLoc)
    else:
      lineCg(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", a.rdLoc)
    b.r = ropecg(p.module, "($1) #newObjRC1($2, sizeof($3))", args)
    lineCg(p, cpsStmts, "$1 = $2;$n", a.rdLoc, b.rdLoc)
  else:
    b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", args)
    genAssignment(p, a, b, {needToKeepAlive})  # set the object type:
  bt = skipTypes(refType.sons[0], abstractRange)
  genObjectInit(p, cpsStmts, bt, a, false)

proc genNewSeqAux(p: BProc, dest: TLoc, length: PRope) =
  let seqtype = skipTypes(dest.t, abstractVarRange)
  let args = [getTypeDesc(p.module, seqtype),
              genTypeInfo(p.module, seqType), length]
  var call: TLoc
  initLoc(call, locExpr, dest.t, OnHeap)
  if dest.s == OnHeap and optRefcGc in gGlobalOptions:
    lineCg(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", dest.rdLoc)
    call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", args)
    lineCg(p, cpsStmts, "$1 = $2;$n", dest.rdLoc, call.rdLoc)
  else:
    call.r = ropecg(p.module, "($1) #newSeq($2, $3)", args)
    genAssignment(p, dest, call, {needToKeepAlive})
  
proc genNewSeq(p: BProc, e: PNode) =
  var a, b: TLoc
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  genNewSeqAux(p, a, b.rdLoc)
  
proc genSeqConstr(p: BProc, t: PNode, d: var TLoc) =
  var arr: TLoc
  if d.k == locNone:
    getTemp(p, t.typ, d)
  # generate call to newSeq before adding the elements per hand:
  genNewSeqAux(p, d, intLiteral(sonsLen(t)))
  for i in countup(0, sonsLen(t) - 1):
    initLoc(arr, locExpr, elemType(skipTypes(t.typ, abstractInst)), OnHeap)
    arr.r = ropef("$1->data[$2]", [rdLoc(d), intLiteral(i)])
    arr.s = OnHeap            # we know that sequences are on the heap
    expr(p, t.sons[i], arr)

proc genArrToSeq(p: BProc, t: PNode, d: var TLoc) =
  var elem, a, arr: TLoc
  if t.kind == nkBracket:
    t.sons[1].typ = t.typ
    genSeqConstr(p, t.sons[1], d)
    return
  if d.k == locNone:
    getTemp(p, t.typ, d)
  # generate call to newSeq before adding the elements per hand:
  var L = int(lengthOrd(t.sons[1].typ))
  
  genNewSeqAux(p, d, intLiteral(L))
  initLocExpr(p, t.sons[1], a)
  for i in countup(0, L - 1):
    initLoc(elem, locExpr, elemType(skipTypes(t.typ, abstractInst)), OnHeap)
    elem.r = ropef("$1->data[$2]", [rdLoc(d), intLiteral(i)])
    elem.s = OnHeap # we know that sequences are on the heap
    initLoc(arr, locExpr, elemType(skipTypes(t.sons[1].typ, abstractInst)), a.s)
    arr.r = ropef("$1[$2]", [rdLoc(a), intLiteral(i)])
    genAssignment(p, elem, arr, {afDestIsNil, needToCopy})
  
proc genNewFinalize(p: BProc, e: PNode) =
  var
    a, b, f: TLoc
    refType, bt: PType
    ti: PRope
    oldModule: BModule
  refType = skipTypes(e.sons[1].typ, abstractVarRange)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], f)
  initLoc(b, locExpr, a.t, OnHeap)
  ti = genTypeInfo(p.module, refType)
  appf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
      getTypeDesc(p.module, refType),
      ti, getTypeDesc(p.module, skipTypes(reftype.sons[0], abstractRange))])
  genAssignment(p, a, b, {needToKeepAlive})  # set the object type:
  bt = skipTypes(refType.sons[0], abstractRange)
  genObjectInit(p, cpsStmts, bt, a, false)

proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, x, a)
  var dest = skipTypes(typ, typedescPtrs)
  var r = rdLoc(a)
  var nilCheck: PRope = nil
  var t = skipTypes(a.t, abstractInst)
  while t.kind in {tyVar, tyPtr, tyRef}:
    if t.kind != tyVar: nilCheck = r
    r = ropef("(*$1)", [r])
    t = skipTypes(t.sons[0], typedescInst)
  if gCmd != cmdCompileToCpp:
    while (t.kind == tyObject) and (t.sons[0] != nil):
      app(r, ".Sup")
      t = skipTypes(t.sons[0], typedescInst)
  if nilCheck != nil:
    r = ropecg(p.module, "(($1) && #isObj($2.m_type, $3))",
              [nilCheck, r, genTypeInfo(p.module, dest)])
  else:
    r = ropecg(p.module, "#isObj($1.m_type, $2)", 
              [r, genTypeInfo(p.module, dest)])
  putIntoDest(p, d, getSysType(tyBool), r)

proc genOf(p: BProc, n: PNode, d: var TLoc) =
  genOf(p, n.sons[1], n.sons[2].typ, d)

proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  # XXX we don't generate keep alive info for now here
  var a: TLoc
  InitLocExpr(p, e.sons[1], a)
  var t = skipTypes(e.sons[1].typ, abstractVarRange)
  case t.kind
  of tyInt..tyInt64, tyUInt..tyUInt64:
    putIntoDest(p, d, e.typ, 
                ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]))
  of tyFloat..tyFloat128:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]))
  of tyBool:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]))
  of tyChar:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]))
  of tyEnum, tyOrdinal:
    putIntoDest(p, d, e.typ,
                ropecg(p.module, "#reprEnum($1, $2)", [
                rdLoc(a), genTypeInfo(p.module, t)]))
  of tyString:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]))
  of tySet:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprSet($1, $2)", [
                addrLoc(a), genTypeInfo(p.module, t)]))
  of tyOpenArray, tyVarargs:
    var b: TLoc
    case a.t.kind
    of tyOpenArray, tyVarargs:
      putIntoDest(p, b, e.typ, ropef("$1, $1Len0", [rdLoc(a)]))
    of tyString, tySequence:
      putIntoDest(p, b, e.typ, 
                  ropef("$1->data, $1->$2", [rdLoc(a), lenField()]))
    of tyArray, tyArrayConstr:
      putIntoDest(p, b, e.typ,
                  ropef("$1, $2", [rdLoc(a), toRope(lengthOrd(a.t))]))
    else: InternalError(e.sons[0].info, "genRepr()")
    putIntoDest(p, d, e.typ, 
        ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
        genTypeInfo(p.module, elemType(t))]))
  of tyCString, tyArray, tyArrayConstr, tyRef, tyPtr, tyPointer, tyNil,
     tySequence:
    putIntoDest(p, d, e.typ,
                ropecg(p.module, "#reprAny($1, $2)", [
                rdLoc(a), genTypeInfo(p.module, t)]))
  else:
    putIntoDest(p, d, e.typ, ropecg(p.module, "#reprAny($1, $2)",
                                   [addrLoc(a), genTypeInfo(p.module, t)]))

proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  var t = skipTypes(e.sons[1].typ, abstractVarRange)
  putIntoDest(p, d, e.typ, genTypeInfo(p.module, t))

proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  var a: TLoc
  InitLocExpr(p, n.sons[1], a)
  a.r = ropecg(p.module, frmt, [rdLoc(a)])
  if d.k == locNone: getTemp(p, n.typ, d)
  genAssignment(p, d, a, {needToKeepAlive})

proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  var a = e.sons[1]
  if a.kind == nkHiddenAddr: a = a.sons[0]
  var typ = skipTypes(a.Typ, abstractVar)
  case typ.kind
  of tyOpenArray, tyVarargs:
    if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)")
    else: unaryExpr(p, e, d, "$1Len0")
  of tyCstring:
    if op == mHigh: unaryExpr(p, e, d, "(strlen($1)-1)")
    else: unaryExpr(p, e, d, "strlen($1)")
  of tyString, tySequence:
    if gCmd != cmdCompileToCpp:
      if op == mHigh: unaryExpr(p, e, d, "($1->Sup.len-1)")
      else: unaryExpr(p, e, d, "$1->Sup.len")
    else:
      if op == mHigh: unaryExpr(p, e, d, "($1->len-1)")
      else: unaryExpr(p, e, d, "$1->len")
  of tyArray, tyArrayConstr:
    # YYY: length(sideeffect) is optimized away incorrectly?
    if op == mHigh: putIntoDest(p, d, e.typ, toRope(lastOrd(Typ)))
    else: putIntoDest(p, d, e.typ, toRope(lengthOrd(typ)))
  else: InternalError(e.info, "genArrayLen()")

proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  var a, b: TLoc
  assert(d.k == locNone)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  var t = skipTypes(e.sons[1].typ, abstractVar)
  let setLenPattern = if gCmd != cmdCompileToCpp:
      "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n"
    else:
      "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n"

  lineCg(p, cpsStmts, setLenPattern, [
      rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
      getTypeDesc(p.module, t.sons[0])])
  keepAlive(p, a)

proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  binaryStmt(p, e, d, "$1 = #setLengthStr($1, $2);$n")
  keepAlive(P, d)

proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  # swap(a, b) -->
  # temp = a
  # a = b
  # b = temp
  var a, b, tmp: TLoc
  getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp)
  InitLocExpr(p, e.sons[1], a) # eval a
  InitLocExpr(p, e.sons[2], b) # eval b
  genAssignment(p, tmp, a, {})
  genAssignment(p, a, b, {})
  genAssignment(p, b, tmp, {})

proc rdSetElemLoc(a: TLoc, setType: PType): PRope =
  # read a location of an set element; it may need a substraction operation
  # before the set operation
  result = rdCharLoc(a)
  assert(setType.kind == tySet)
  if firstOrd(setType) != 0:
    result = ropef("($1- $2)", [result, toRope(firstOrd(setType))])

proc fewCmps(s: PNode): bool =
  # this function estimates whether it is better to emit code
  # for constructing the set or generating a bunch of comparisons directly
  if s.kind != nkCurly: InternalError(s.info, "fewCmps")
  if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags):
    result = false            # it is better to emit the set generation code
  elif elemType(s.typ).Kind in {tyInt, tyInt16..tyInt64}:
    result = true             # better not emit the set if int is basetype!
  else:
    result = sonsLen(s) <= 8  # 8 seems to be a good value

proc binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  putIntoDest(p, d, e.typ, ropef(frmt, [rdLoc(a), rdSetElemLoc(b, a.t)]))

proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  case int(getSize(skipTypes(e.sons[1].typ, abstractVar)))
  of 1: binaryExprIn(p, e, a, b, d, "(($1 &(1<<(($2)&7)))!=0)")
  of 2: binaryExprIn(p, e, a, b, d, "(($1 &(1<<(($2)&15)))!=0)")
  of 4: binaryExprIn(p, e, a, b, d, "(($1 &(1<<(($2)&31)))!=0)")
  of 8: binaryExprIn(p, e, a, b, d, "(($1 &(IL64(1)<<(($2)&IL64(63))))!=0)")
  else: binaryExprIn(p, e, a, b, d, "(($1[$2/8] &(1<<($2%8)))!=0)")

proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  var a, b: TLoc
  assert(d.k == locNone)
  InitLocExpr(p, e.sons[1], a)
  InitLocExpr(p, e.sons[2], b)
  lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(b, a.t)])

proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  var a, b, x, y: TLoc
  if (e.sons[1].Kind == nkCurly) and fewCmps(e.sons[1]):
    # a set constructor but not a constant set:
    # do not emit the set, but generate a bunch of comparisons
    initLocExpr(p, e.sons[2], a)
    initLoc(b, locExpr, e.typ, OnUnknown)
    b.r = toRope("(")
    var length = sonsLen(e.sons[1])
    for i in countup(0, length - 1):
      if e.sons[1].sons[i].Kind == nkRange:
        InitLocExpr(p, e.sons[1].sons[i].sons[0], x)
        InitLocExpr(p, e.sons[1].sons[i].sons[1], y)
        appf(b.r, "$1 >= $2 && $1 <= $3",
             [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
      else:
        InitLocExpr(p, e.sons[1].sons[i], x)
        appf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
      if i < length - 1: app(b.r, " || ")
    app(b.r, ")")
    putIntoDest(p, d, e.typ, b.r)
  else:
    assert(e.sons[1].typ != nil)
    assert(e.sons[2].typ != nil)
    InitLocExpr(p, e.sons[1], a)
    InitLocExpr(p, e.sons[2], b)
    genInExprAux(p, e, a, b, d)

proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  const
    lookupOpr: array[mLeSet..mSymDiffSet, string] = [
      "for ($1 = 0; $1 < $2; $1++) { $n" &
        "  $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
        "  if (!$3) break;}$n", "for ($1 = 0; $1 < $2; $1++) { $n" &
        "  $3 = (($4[$1] & ~ $5[$1]) == 0);$n" & "  if (!$3) break;}$n" &
        "if ($3) $3 = (memcmp($4, $5, $2) != 0);$n",
      "&", "|", "& ~", "^"]
  var a, b, i: TLoc
  var setType = skipTypes(e.sons[1].Typ, abstractVar)
  var size = int(getSize(setType))
  case size
  of 1, 2, 4, 8:
    case op
    of mIncl:
      var ts = "NI" & $(size * 8)
      binaryStmtInExcl(p, e, d,
          "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n")
    of mExcl:
      var ts = "NI" & $(size * 8)
      binaryStmtInExcl(p, e, d, "$1 &= ~((" & ts & ")(1) << (($2) % (sizeof(" &
          ts & ")*8)));$n")
    of mCard:
      if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
      else: unaryExprChar(p, e, d, "#countBits64($1)")
    of mLtSet: binaryExprChar(p, e, d, "(($1 & ~ $2 ==0)&&($1 != $2))")
    of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
    of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
    of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
    of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
    of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
    of mSymDiffSet: binaryExpr(p, e, d, "($1 ^ $2)")
    of mInSet:
      genInOp(p, e, d)
    else: internalError(e.info, "genSetOp()")
  else:
    case op
    of mIncl: binaryStmtInExcl(p, e, d, "$1[$2/8] |=(1<<($2%8));$n")
    of mExcl: binaryStmtInExcl(p, e, d, "$1[$2/8] &= ~(1<<($2%8));$n")
    of mCard: unaryExprChar(p, e, d, "#cardSet($1, " & $size & ')')
    of mLtSet, mLeSet:
      getTemp(p, getSysType(tyInt), i) # our counter
      initLocExpr(p, e.sons[1], a)
      initLocExpr(p, e.sons[2], b)
      if d.k == locNone: getTemp(p, a.t, d)
      lineF(p, cpsStmts, lookupOpr[op],
           [rdLoc(i), toRope(size), rdLoc(d), rdLoc(a), rdLoc(b)])
    of mEqSet:
      binaryExprChar(p, e, d, "(memcmp($1, $2, " & $(size) & ")==0)")
    of mMulSet, mPlusSet, mMinusSet, mSymDiffSet:
      # we inline the simple for loop for better code generation:
      getTemp(p, getSysType(tyInt), i) # our counter
      initLocExpr(p, e.sons[1], a)
      initLocExpr(p, e.sons[2], b)
      if d.k == locNone: getTemp(p, a.t, d)
      lineF(p, cpsStmts,
           "for ($1 = 0; $1 < $2; $1++) $n" & 
           "  $3[$1] = $4[$1] $6 $5[$1];$n", [
          rdLoc(i), toRope(size), rdLoc(d), rdLoc(a), rdLoc(b),
          toRope(lookupOpr[op])])
    of mInSet: genInOp(p, e, d)
    else: internalError(e.info, "genSetOp")

proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  unaryExprChar(p, e, d, "$1")

proc genCast(p: BProc, e: PNode, d: var TLoc) =
  const
    ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs,
                  tyArrayConstr}
  # we use whatever C gives us. Except if we have a value-type, we need to go
  # through its address:
  var a: TLoc
  InitLocExpr(p, e.sons[1], a)
  let etyp = skipTypes(e.typ, abstractRange)
  if etyp.kind in ValueTypes and lfIndirect notin a.flags:
    putIntoDest(p, d, e.typ, ropef("(*($1*) ($2))",
        [getTypeDesc(p.module, e.typ), addrLoc(a)]))
  elif etyp.kind == tyProc and etyp.callConv == ccClosure:
    putIntoDest(p, d, e.typ, ropef("(($1) ($2))",
        [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)]))
  else:
    putIntoDest(p, d, e.typ, ropef("(($1) ($2))",
        [getTypeDesc(p.module, e.typ), rdCharLoc(a)]))

proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) =
  var a: TLoc
  var dest = skipTypes(n.typ, abstractVar)
  # range checks for unsigned turned out to be buggy and annoying:
  if optRangeCheck notin p.options or dest.kind in {tyUInt..tyUInt64}:
    InitLocExpr(p, n.sons[0], a)
    putIntoDest(p, d, n.typ, ropef("(($1) ($2))",
        [getTypeDesc(p.module, dest), rdCharLoc(a)]))
  else:
    InitLocExpr(p, n.sons[0], a)
    if leValue(n.sons[2], n.sons[1]):
      InternalError(n.info, "range check will always fail; empty range")
    putIntoDest(p, d, dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [
        getTypeDesc(p.module, dest), rdCharLoc(a),
        genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest),
        toRope(magic)]))

proc genConv(p: BProc, e: PNode, d: var TLoc) =
  if compareTypes(e.typ, e.sons[1].typ, dcEqIgnoreDistinct):
    expr(p, e.sons[1], d)
  else:
    genCast(p, e, d)

proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, n.sons[0], a)
  putIntoDest(p, d, skipTypes(n.typ, abstractVar), ropef("$1->data",
      [rdLoc(a)]))

proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, n.sons[0], a)
  putIntoDest(p, d, skipTypes(n.typ, abstractVar),
              ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]))

proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  var x: TLoc
  var a = e.sons[1]
  var b = e.sons[2]
  if (a.kind == nkNilLit) or (b.kind == nkNilLit):
    binaryExpr(p, e, d, "($1 == $2)")
  elif (a.kind in {nkStrLit..nkTripleStrLit}) and (a.strVal == ""):
    initLocExpr(p, e.sons[2], x)
    putIntoDest(p, d, e.typ, 
      ropef("(($1) && ($1)->$2 == 0)", [rdLoc(x), lenField()]))
  elif (b.kind in {nkStrLit..nkTripleStrLit}) and (b.strVal == ""):
    initLocExpr(p, e.sons[1], x)
    putIntoDest(p, d, e.typ, 
      ropef("(($1) && ($1)->$2 == 0)", [rdLoc(x), lenField()]))
  else:
    binaryExpr(p, e, d, "#eqStrings($1, $2)")

proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  if {optNanCheck, optInfCheck} * p.options != {}:
    const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
    var a, b: TLoc
    assert(e.sons[1].typ != nil)
    assert(e.sons[2].typ != nil)
    InitLocExpr(p, e.sons[1], a)
    InitLocExpr(p, e.sons[2], b)
    putIntoDest(p, d, e.typ, ropef("($2 $1 $3)", [
                toRope(opr[m]), rdLoc(a), rdLoc(b)]))
    if optNanCheck in p.options:
      lineCg(p, cpsStmts, "#nanCheck($1);$n", [rdLoc(d)])
    if optInfCheck in p.options:
      lineCg(p, cpsStmts, "#infCheck($1);$n", [rdLoc(d)])
  else:
    binaryArith(p, e, d, m)

proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  var line, filen: PRope
  case op
  of mOr, mAnd: genAndOr(p, e, d, op)
  of mNot..mToBiggestInt: unaryArith(p, e, d, op)
  of mUnaryMinusI..mAbsI64: unaryArithOverflow(p, e, d, op)
  of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  of mShrI..mXor: binaryArith(p, e, d, op)
  of mEqProc: genEqProc(p, e, d)
  of mAddi..mModi64: binaryArithOverflow(p, e, d, op)
  of mRepr: genRepr(p, e, d)
  of mGetTypeInfo: genGetTypeInfo(p, e, d)
  of mSwap: genSwap(p, e, d)
  of mUnaryLt: 
    if not (optOverflowCheck in p.Options): unaryExpr(p, e, d, "$1 - 1")
    else: unaryExpr(p, e, d, "#subInt($1, 1)")
  of mPred:
    # XXX: range checking?
    if not (optOverflowCheck in p.Options): binaryExpr(p, e, d, "$1 - $2")
    else: binaryExpr(p, e, d, "#subInt($1, $2)")
  of mSucc:
    # XXX: range checking?
    if not (optOverflowCheck in p.Options): binaryExpr(p, e, d, "$1 + $2")
    else: binaryExpr(p, e, d, "#addInt($1, $2)")
  of mInc:
    if not (optOverflowCheck in p.Options):
      binaryStmt(p, e, d, "$1 += $2;$n")
    elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64:
      binaryStmt(p, e, d, "$1 = #addInt64($1, $2);$n")
    else:
      binaryStmt(p, e, d, "$1 = #addInt($1, $2);$n")
  of ast.mDec:
    if not (optOverflowCheck in p.Options):
      binaryStmt(p, e, d, "$1 -= $2;$n")
    elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64:
      binaryStmt(p, e, d, "$1 = #subInt64($1, $2);$n")
    else:
      binaryStmt(p, e, d, "$1 = #subInt($1, $2);$n")
  of mConStrStr: genStrConcat(p, e, d)
  of mAppendStrCh:
    binaryStmt(p, e, d, "$1 = #addChar($1, $2);$n")
    # strictly speaking we need to generate "keepAlive" here too, but this
    # very likely not needed and would slow down the code too much I fear
  of mAppendStrStr: genStrAppend(p, e, d)
  of mAppendSeqElem: genSeqElemAppend(p, e, d)
  of mEqStr: genStrEquals(p, e, d)
  of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  of mIsNil: genIsNil(p, e, d)
  of mIntToStr: genDollar(p, e, d, "#nimIntToStr($1)")
  of mInt64ToStr: genDollar(p, e, d, "#nimInt64ToStr($1)")
  of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  of mFloatToStr: genDollar(p, e, d, "#nimFloatToStr($1)")
  of mCStrToStr: genDollar(p, e, d, "#cstrToNimstr($1)")
  of mStrToStr: expr(p, e.sons[1], d)
  of mEnumToStr: genRepr(p, e, d)
  of mOf: genOf(p, e, d)
  of mNew: genNew(p, e)
  of mNewFinalize: genNewFinalize(p, e)
  of mNewSeq: genNewSeq(p, e)
  of mSizeOf:
    putIntoDest(p, d, e.typ, ropef("((NI)sizeof($1))",
                                   [getTypeDesc(p.module, e.sons[1].typ)]))
  of mChr: genCast(p, e, d)
  of mOrd: genOrd(p, e, d)
  of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
    genArrayLen(p, e, d, op)
  of mGCref: unaryStmt(p, e, d, "#nimGCref($1);$n")
  of mGCunref: unaryStmt(p, e, d, "#nimGCunref($1);$n")
  of mSetLengthStr: genSetLengthStr(p, e, d)
  of mSetLengthSeq: genSetLengthSeq(p, e, d)
  of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
     mInSet:
    genSetOp(p, e, d, op)
  of mNewString, mNewStringOfCap, mCopyStr, mCopyStrLast, mExit, mRand:
    var opr = e.sons[0].sym
    if lfNoDecl notin opr.loc.flags:
      discard cgsym(p.module, opr.loc.r.ropeToStr)
    genCall(p, e, d)
  of mReset: genReset(p, e)
  of mEcho: genEcho(p, e)
  of mArrToSeq: genArrToSeq(p, e, d)
  of mNLen..mNError:
    localError(e.info, errCannotGenerateCodeForX, e.sons[0].sym.name.s)
  of mSlurp, mStaticExec:
    localError(e.info, errXMustBeCompileTime, e.sons[0].sym.name.s)
  else: internalError(e.info, "genMagicExpr: " & $op)

proc genConstExpr(p: BProc, n: PNode): PRope
proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  if (nfAllConst in n.flags) and (d.k == locNone) and (sonsLen(n) > 0):
    var t = getUniqueType(n.typ)
    discard getTypeDesc(p.module, t) # so that any fields are initialized
    var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId)
    fillLoc(d, locData, t, con("TMP", toRope(id)), OnHeap)
    if id == gBackendId:
      # expression not found in the cache:
      inc(gBackendId)
      appf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
           [getTypeDesc(p.module, t), d.r, genConstExpr(p, n)])
    result = true
  else:
    result = false

proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  # example: { a..b, c, d, e, f..g }
  # we have to emit an expression of the form:
  # memset(tmp, 0, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  var
    a, b, idx: TLoc
  if nfAllConst in e.flags:
    putIntoDest(p, d, e.typ, genSetNode(p, e))
  else:
    if d.k == locNone: getTemp(p, e.typ, d)
    if getSize(e.typ) > 8:
      # big set:
      lineF(p, cpsStmts, "memset($1, 0, sizeof($1));$n", [rdLoc(d)])
      for i in countup(0, sonsLen(e) - 1):
        if e.sons[i].kind == nkRange:
          getTemp(p, getSysType(tyInt), idx) # our counter
          initLocExpr(p, e.sons[i].sons[0], a)
          initLocExpr(p, e.sons[i].sons[1], b)
          lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
              "$2[$1/8] |=(1<<($1%8));$n", [rdLoc(idx), rdLoc(d),
              rdSetElemLoc(a, e.typ), rdSetElemLoc(b, e.typ)])
        else:
          initLocExpr(p, e.sons[i], a)
          lineF(p, cpsStmts, "$1[$2/8] |=(1<<($2%8));$n",
               [rdLoc(d), rdSetElemLoc(a, e.typ)])
    else:
      # small set
      var ts = "NI" & $(getSize(e.typ) * 8)
      lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)])
      for i in countup(0, sonsLen(e) - 1):
        if e.sons[i].kind == nkRange:
          getTemp(p, getSysType(tyInt), idx) # our counter
          initLocExpr(p, e.sons[i].sons[0], a)
          initLocExpr(p, e.sons[i].sons[1], b)
          lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
              "$2 |=(1<<((" & ts & ")($1)%(sizeof(" & ts & ")*8)));$n", [
              rdLoc(idx), rdLoc(d), rdSetElemLoc(a, e.typ),
              rdSetElemLoc(b, e.typ)])
        else:
          initLocExpr(p, e.sons[i], a)
          lineF(p, cpsStmts,
               "$1 |=(1<<((" & ts & ")($2)%(sizeof(" & ts & ")*8)));$n",
               [rdLoc(d), rdSetElemLoc(a, e.typ)])

proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  var rec: TLoc
  if not handleConstExpr(p, n, d):
    var t = getUniqueType(n.typ)
    discard getTypeDesc(p.module, t) # so that any fields are initialized
    if d.k == locNone: getTemp(p, t, d)
    for i in countup(0, sonsLen(n) - 1):
      var it = n.sons[i]
      if it.kind == nkExprColonExpr: it = it.sons[1]
      initLoc(rec, locExpr, it.typ, d.s)
      rec.r = ropef("$1.Field$2", [rdLoc(d), toRope(i)])
      expr(p, it, rec)
      when false:
        initLoc(rec, locExpr, it.typ, d.s)
        if (t.n.sons[i].kind != nkSym): InternalError(n.info, "genTupleConstr")
        rec.r = ropef("$1.$2",
                      [rdLoc(d), mangleRecFieldName(t.n.sons[i].sym, t)])
        expr(p, it, rec)

proc IsConstClosure(n: PNode): bool {.inline.} =
  result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and
      n.sons[1].kind == nkNilLit
      
proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  assert n.kind == nkClosure
  
  if IsConstClosure(n):
    inc(p.labels)
    var tmp = con("LOC", toRope(p.labels))
    appf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
        [getTypeDesc(p.module, n.typ), tmp, genConstExpr(p, n)])
    putIntoDest(p, d, n.typ, tmp)
  else:
    var tmp, a, b: TLoc
    initLocExpr(p, n.sons[0], a)
    initLocExpr(p, n.sons[1], b)
    getTemp(p, n.typ, tmp)
    lineCg(p, cpsStmts, "$1.ClPrc = $2; $1.ClEnv = $3;$n",
          tmp.rdLoc, a.rdLoc, b.rdLoc)
    putLocIntoDest(p, d, tmp)

proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  var arr: TLoc
  if not handleConstExpr(p, n, d):
    if d.k == locNone: getTemp(p, n.typ, d)
    for i in countup(0, sonsLen(n) - 1):
      initLoc(arr, locExpr, elemType(skipTypes(n.typ, abstractInst)), d.s)
      arr.r = ropef("$1[$2]", [rdLoc(d), intLiteral(i)])
      expr(p, n.sons[i], arr)

proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  requestConstImpl(p, sym)
  assert((sym.loc.r != nil) and (sym.loc.t != nil))
  putLocIntoDest(p, d, sym.loc)

proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  var length = sonsLen(n)
  for i in countup(0, length - 2): genStmts(p, n.sons[i])
  if length > 0: expr(p, n.sons[length - 1], d)

proc upConv(p: BProc, n: PNode, d: var TLoc) =
  var a: TLoc
  initLocExpr(p, n.sons[0], a)
  var dest = skipTypes(n.typ, abstractPtrs)
  if optObjCheck in p.options and not isPureObject(dest):
    var r = rdLoc(a)
    var nilCheck: PRope = nil
    var t = skipTypes(a.t, abstractInst)
    while t.kind in {tyVar, tyPtr, tyRef}:
      if t.kind != tyVar: nilCheck = r
      r = ropef("(*$1)", [r])
      t = skipTypes(t.sons[0], abstractInst)
    if gCmd != cmdCompileToCpp:
      while t.kind == tyObject and t.sons[0] != nil:
        app(r, ".Sup")
        t = skipTypes(t.sons[0], abstractInst)
    if nilCheck != nil:
      lineCg(p, cpsStmts, "if ($1) #chckObj($2.m_type, $3);$n",
           [nilCheck, r, genTypeInfo(p.module, dest)])
    else:
      lineCg(p, cpsStmts, "#chckObj($1.m_type, $2);$n",
           [r, genTypeInfo(p.module, dest)])
  if n.sons[0].typ.kind != tyObject:
    putIntoDest(p, d, n.typ,
                ropef("(($1) ($2))", [getTypeDesc(p.module, n.typ), rdLoc(a)]))
  else:
    putIntoDest(p, d, n.typ, ropef("(*($1*) ($2))",
                                   [getTypeDesc(p.module, dest), addrLoc(a)]))

proc downConv(p: BProc, n: PNode, d: var TLoc) =
  if gCmd == cmdCompileToCpp:
    expr(p, n.sons[0], d)     # downcast does C++ for us
  else:
    var dest = skipTypes(n.typ, abstractPtrs)
    var src = skipTypes(n.sons[0].typ, abstractPtrs)
    var a: TLoc
    initLocExpr(p, n.sons[0], a)
    var r = rdLoc(a)
    if skipTypes(n.sons[0].typ, abstractInst).kind in {tyRef, tyPtr, tyVar}:
      app(r, "->Sup")
      for i in countup(2, abs(inheritanceDiff(dest, src))): app(r, ".Sup")
      r = con("&", r)
    else:
      for i in countup(1, abs(inheritanceDiff(dest, src))): app(r, ".Sup")
    putIntoDest(p, d, n.typ, r)

proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) =
  var t = getUniqueType(n.typ)
  discard getTypeDesc(p.module, t) # so that any fields are initialized
  var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId)
  var tmp = con("TMP", toRope(id))
  
  if id == gBackendId:
    # expression not found in the cache:
    inc(gBackendId)
    appf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
         [getTypeDesc(p.module, t), tmp, genConstExpr(p, n)])
  
  if d.k == locNone:
    fillLoc(d, locData, t, tmp, OnHeap)
  else:
    putIntoDest(p, d, t, tmp)

proc genBlock(p: BProc, t: PNode, d: var TLoc)
proc expr(p: BProc, e: PNode, d: var TLoc) =
  case e.kind
  of nkSym:
    var sym = e.sym
    case sym.Kind
    of skMethod:
      if sym.getBody.kind == nkEmpty:
        # we cannot produce code for the dispatcher yet:
        fillProcLoc(sym)
        genProcPrototype(p.module, sym)
      else:
        genProc(p.module, sym)
      putLocIntoDest(p, d, sym.loc)
    of skProc, skConverter:
      genProc(p.module, sym)
      if sym.loc.r == nil or sym.loc.t == nil:
        InternalError(e.info, "expr: proc not init " & sym.name.s)
      putLocIntoDest(p, d, sym.loc)
    of skConst:
      if sfFakeConst in sym.flags:
        if sfGlobal in sym.flags: genVarPrototype(p.module, sym)
        putLocIntoDest(p, d, sym.loc)
      elif isSimpleConst(sym.typ):
        putIntoDest(p, d, e.typ, genLiteral(p, sym.ast, sym.typ))
      else:
        genComplexConst(p, sym, d)
    of skEnumField:
      putIntoDest(p, d, e.typ, toRope(sym.position))
    of skVar, skForVar, skResult, skLet:
      if sfGlobal in sym.flags: genVarPrototype(p.module, sym)
      if sym.loc.r == nil or sym.loc.t == nil:
        InternalError(e.info, "expr: var not init " & sym.name.s)
      if sfThread in sym.flags:
        AccessThreadLocalVar(p, sym)
        if emulatedThreadVars(): 
          putIntoDest(p, d, sym.loc.t, con("NimTV->", sym.loc.r))
        else:
          putLocIntoDest(p, d, sym.loc)
      else:
        putLocIntoDest(p, d, sym.loc)
    of skTemp:
      if sym.loc.r == nil or sym.loc.t == nil:
        InternalError(e.info, "expr: temp not init " & sym.name.s)
      putLocIntoDest(p, d, sym.loc)
    of skParam:
      if sym.loc.r == nil or sym.loc.t == nil:
        InternalError(e.info, "expr: param not init " & sym.name.s)
      putLocIntoDest(p, d, sym.loc)
    else: InternalError(e.info, "expr(" & $sym.kind & "); unknown symbol")
  of nkStrLit..nkTripleStrLit, nkIntLit..nkUInt64Lit,
     nkFloatLit..nkFloat128Lit, nkNilLit, nkCharLit:
    putIntoDest(p, d, e.typ, genLiteral(p, e))
  of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkPostfix, nkCommand,
     nkCallStrLit:
    if e.sons[0].kind == nkSym and e.sons[0].sym.magic != mNone:
      genMagicExpr(p, e, d, e.sons[0].sym.magic)
    else:
      genCall(p, e, d)
  of nkCurly:
    if isDeepConstExpr(e) and e.len != 0:
      putIntoDest(p, d, e.typ, genSetNode(p, e))
    else:
      genSetConstr(p, e, d)
  of nkBracket:
    if isDeepConstExpr(e) and e.len != 0:
      exprComplexConst(p, e, d)
    elif skipTypes(e.typ, abstractVarRange).kind == tySequence:
      genSeqConstr(p, e, d)
    else:
      genArrayConstr(p, e, d)
  of nkPar:
    if isDeepConstExpr(e) and e.len != 0:
      exprComplexConst(p, e, d)
    else:
      genTupleConstr(p, e, d)
  of nkCast: genCast(p, e, d)
  of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, e, d)
  of nkHiddenAddr, nkAddr: genAddr(p, e, d)
  of nkBracketExpr:
    var ty = skipTypes(e.sons[0].typ, abstractVarRange)
    if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.sons[0], abstractVarRange)
    case ty.kind
    of tyArray, tyArrayConstr: genArrayElem(p, e, d)
    of tyOpenArray, tyVarargs: genOpenArrayElem(p, e, d)
    of tySequence, tyString: genSeqElem(p, e, d)
    of tyCString: genCStringElem(p, e, d)
    of tyTuple: genTupleElem(p, e, d)
    else: InternalError(e.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  of nkDerefExpr, nkHiddenDeref: genDeref(p, e, d)
  of nkDotExpr: genRecordField(p, e, d)
  of nkCheckedFieldExpr: genCheckedRecordField(p, e, d)
  of nkBlockExpr: genBlock(p, e, d)
  of nkStmtListExpr: genStmtListExpr(p, e, d)
  of nkIfExpr: genIfExpr(p, e, d)
  of nkObjDownConv: downConv(p, e, d)
  of nkObjUpConv: upConv(p, e, d)
  of nkChckRangeF: genRangeChck(p, e, d, "chckRangeF")
  of nkChckRange64: genRangeChck(p, e, d, "chckRange64")
  of nkChckRange: genRangeChck(p, e, d, "chckRange")
  of nkStringToCString: convStrToCStr(p, e, d)
  of nkCStringToString: convCStrToStr(p, e, d)
  of nkLambdaKinds:
    var sym = e.sons[namePos].sym
    genProc(p.module, sym)
    if sym.loc.r == nil or sym.loc.t == nil:
      InternalError(e.info, "expr: proc not init " & sym.name.s)
    putLocIntoDest(p, d, sym.loc)
  of nkClosure: genClosure(p, e, d)
  of nkMetaNode: expr(p, e.sons[0], d)
  else: InternalError(e.info, "expr(" & $e.kind & "); unknown node kind")

proc genNamedConstExpr(p: BProc, n: PNode): PRope =
  if n.kind == nkExprColonExpr: result = genConstExpr(p, n.sons[1])
  else: result = genConstExpr(p, n)

proc genConstSimpleList(p: BProc, n: PNode): PRope =
  var length = sonsLen(n)
  result = toRope("{")
  for i in countup(0, length - 2):
    appf(result, "$1,$n", [genNamedConstExpr(p, n.sons[i])])
  if length > 0: app(result, genNamedConstExpr(p, n.sons[length - 1]))
  appf(result, "}$n")

proc genConstSeq(p: BProc, n: PNode, t: PType): PRope =
  var data = ropef("{{$1, $1}", n.len.toRope)
  if n.len > 0: 
    # array part needs extra curlies:
    data.app(", {")
    for i in countup(0, n.len - 1):
      if i > 0: data.appf(",$n")
      data.app genConstExpr(p, n.sons[i])
    data.app("}")
  data.app("}")
  
  inc(gBackendId)
  result = con("CNSTSEQ", gBackendId.toRope)
  
  appcg(p.module, cfsData,
        "NIM_CONST struct {$n" & 
        "  #TGenericSeq Sup;$n" &
        "  $1 data[$2];$n" & 
        "} $3 = $4;$n", [
        getTypeDesc(p.module, t.sons[0]), n.len.toRope, result, data])

  result = ropef("(($1)&$2)", [getTypeDesc(p.module, t), result])

proc genConstExpr(p: BProc, n: PNode): PRope =
  case n.Kind
  of nkHiddenStdConv, nkHiddenSubConv:
    result = genConstExpr(p, n.sons[1])
  of nkCurly:
    var cs: TBitSet
    toBitSet(n, cs)
    result = genRawSetData(cs, int(getSize(n.typ)))
  of nkBracket, nkPar, nkClosure:
    var t = skipTypes(n.typ, abstractInst)
    if t.kind == tySequence:
      result = genConstSeq(p, n, t)
    else:
      result = genConstSimpleList(p, n)
  else:
    var d: TLoc
    initLocExpr(p, n, d)
    result = rdLoc(d)