forked from nim-lang/Nim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast2ir.nim
More file actions
2694 lines (2403 loc) · 90.5 KB
/
Copy pathast2ir.nim
File metadata and controls
2694 lines (2403 loc) · 90.5 KB
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
#
#
# The Nim Compiler
# (c) Copyright 2023 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
import std / [assertions, tables, sets]
import ".." / [ast, astalgo, types, options, lineinfos, msgs, magicsys,
modulegraphs, renderer, transf, bitsets, trees, nimsets,
expanddefaults, wordrecg]
from ".." / lowerings import lowerSwap, lowerTupleUnpacking
from ".." / pathutils import customPath
import .. / ic / bitabs
import nirtypes, nirinsts, nirlineinfos, nirslots, types2ir, nirfiles
when defined(nimCompilerStacktraceHints):
import std/stackframes
type
ModuleCon* = ref object
nirm*: ref NirModule
types: TypesCon
module*: PSym
graph*: ModuleGraph
nativeIntId, nativeUIntId: TypeId
strPayloadId: (TypeId, TypeId)
idgen: IdGenerator
processedProcs, pendingProcsAsSet: HashSet[ItemId]
pendingProcs: seq[PSym] # procs we still need to generate code for
pendingVarsAsSet: HashSet[ItemId]
pendingVars: seq[PSym]
noModularity*: bool
inProc: int
toSymId: Table[ItemId, SymId]
symIdCounter: int32
ProcCon* = object
config*: ConfigRef
lit: Literals
lastFileKey: FileIndex
lastFileVal: LitId
labelGen: int
exitLabel: LabelId
#code*: Tree
blocks: seq[(PSym, LabelId)]
sm: SlotManager
idgen: IdGenerator
m: ModuleCon
prc: PSym
options: TOptions
template code(c: ProcCon): Tree = c.m.nirm.code
proc initModuleCon*(graph: ModuleGraph; config: ConfigRef; idgen: IdGenerator; module: PSym;
nirm: ref NirModule): ModuleCon =
#let lit = Literals() # must be shared
result = ModuleCon(graph: graph, types: initTypesCon(config), nirm: nirm,
idgen: idgen, module: module)
case config.target.intSize
of 2:
result.nativeIntId = Int16Id
result.nativeUIntId = UInt16Id
of 4:
result.nativeIntId = Int32Id
result.nativeUIntId = UInt16Id
else:
result.nativeIntId = Int64Id
result.nativeUIntId = UInt16Id
result.strPayloadId = strPayloadPtrType(result.types, result.nirm.types)
nirm.namespace = nirm.lit.strings.getOrIncl(customPath(toFullPath(config, module.info)))
nirm.intbits = uint32(config.target.intSize * 8)
proc initProcCon*(m: ModuleCon; prc: PSym; config: ConfigRef): ProcCon =
result = ProcCon(m: m, sm: initSlotManager({}), prc: prc, config: config,
lit: m.nirm.lit, idgen: m.idgen,
options: if prc != nil: prc.options
else: config.options)
result.exitLabel = newLabel(result.labelGen)
proc toLineInfo(c: var ProcCon; i: TLineInfo): PackedLineInfo =
var val: LitId
if c.lastFileKey == i.fileIndex:
val = c.lastFileVal
else:
val = c.lit.strings.getOrIncl(toFullPath(c.config, i.fileIndex))
# remember the entry:
c.lastFileKey = i.fileIndex
c.lastFileVal = val
result = pack(c.m.nirm.man, val, int32 i.line, int32 i.col)
proc bestEffort(c: ProcCon): TLineInfo =
if c.prc != nil:
c.prc.info
else:
c.m.module.info
proc popBlock(c: var ProcCon; oldLen: int) =
c.blocks.setLen(oldLen)
template withBlock(labl: PSym; info: PackedLineInfo; asmLabl: LabelId; body: untyped) {.dirty.} =
var oldLen {.gensym.} = c.blocks.len
c.blocks.add (labl, asmLabl)
body
popBlock(c, oldLen)
type
GenFlag = enum
gfAddrOf # load the address of the expression
gfToOutParam # the expression is passed to an `out` parameter
GenFlags = set[GenFlag]
proc gen(c: var ProcCon; n: PNode; d: var Value; flags: GenFlags = {})
proc genScope(c: var ProcCon; n: PNode; d: var Value; flags: GenFlags = {}) =
openScope c.sm
gen c, n, d, flags
closeScope c.sm
proc freeTemp(c: var ProcCon; tmp: Value) =
let s = extractTemp(tmp)
if s != SymId(-1):
freeTemp(c.sm, s)
proc freeTemps(c: var ProcCon; tmps: openArray[Value]) =
for t in tmps: freeTemp(c, t)
proc typeToIr(m: ModuleCon; t: PType): TypeId =
typeToIr(m.types, m.nirm.types, t)
proc allocTemp(c: var ProcCon; t: TypeId): SymId =
if c.m.noModularity:
result = allocTemp(c.sm, t, c.m.symIdCounter)
else:
result = allocTemp(c.sm, t, c.idgen.symId)
const
ListSymId = -1
proc toSymId(c: var ProcCon; s: PSym): SymId =
if c.m.noModularity:
result = c.m.toSymId.getOrDefault(s.itemId, SymId(-1))
if result.int < 0:
inc c.m.symIdCounter
result = SymId(c.m.symIdCounter)
c.m.toSymId[s.itemId] = result
when ListSymId != -1:
if result.int == ListSymId or s.name.s == "echoBinSafe":
echo result.int, " is ", s.name.s, " ", c.m.graph.config $ s.info, " ", s.flags
writeStackTrace()
else:
result = SymId(s.itemId.item)
proc getTemp(c: var ProcCon; n: PNode): Value =
let info = toLineInfo(c, n.info)
let t = typeToIr(c.m, n.typ)
let tmp = allocTemp(c, t)
c.code.addSummon info, tmp, t
result = localToValue(info, tmp)
proc getTemp(c: var ProcCon; t: TypeId; info: PackedLineInfo): Value =
let tmp = allocTemp(c, t)
c.code.addSummon info, tmp, t
result = localToValue(info, tmp)
proc gen(c: var ProcCon; n: PNode; flags: GenFlags = {}) =
var tmp = default(Value)
gen(c, n, tmp, flags)
freeTemp c, tmp
proc genScope(c: var ProcCon; n: PNode; flags: GenFlags = {}) =
openScope c.sm
gen c, n, flags
closeScope c.sm
proc genx(c: var ProcCon; n: PNode; flags: GenFlags = {}): Value =
result = default(Value)
gen(c, n, result, flags)
assert Tree(result).len > 0, $n
proc clearDest(c: var ProcCon; n: PNode; d: var Value) {.inline.} =
when false:
if n.typ.isNil or n.typ.kind == tyVoid:
let s = extractTemp(d)
if s != SymId(-1):
freeLoc(c.sm, s)
proc isNotOpr(n: PNode): bool =
n.kind in nkCallKinds and n[0].kind == nkSym and n[0].sym.magic == mNot
proc jmpBack(c: var ProcCon; n: PNode; lab: LabelId) =
c.code.gotoLabel toLineInfo(c, n.info), GotoLoop, lab
type
JmpKind = enum opcFJmp, opcTJmp
proc xjmp(c: var ProcCon; n: PNode; jk: JmpKind; v: Value): LabelId =
result = newLabel(c.labelGen)
let info = toLineInfo(c, n.info)
buildTyped c.code, info, Select, Bool8Id:
c.code.copyTree Tree(v)
build c.code, info, SelectPair:
build c.code, info, SelectValue:
c.code.boolVal(c.lit.numbers, info, jk == opcTJmp)
c.code.gotoLabel info, Goto, result
proc patch(c: var ProcCon; n: PNode; L: LabelId) =
addLabel c.code, toLineInfo(c, n.info), Label, L
proc genWhile(c: var ProcCon; n: PNode) =
# lab1:
# cond, tmp
# fjmp tmp, lab2
# body
# jmp lab1
# lab2:
let info = toLineInfo(c, n.info)
let lab1 = c.code.addNewLabel(c.labelGen, info, LoopLabel)
withBlock(nil, info, lab1):
if isTrue(n[0]):
c.gen(n[1])
c.jmpBack(n, lab1)
elif isNotOpr(n[0]):
var tmp = c.genx(n[0][1])
let lab2 = c.xjmp(n, opcTJmp, tmp)
c.freeTemp(tmp)
c.gen(n[1])
c.jmpBack(n, lab1)
c.patch(n, lab2)
else:
var tmp = c.genx(n[0])
let lab2 = c.xjmp(n, opcFJmp, tmp)
c.freeTemp(tmp)
c.gen(n[1])
c.jmpBack(n, lab1)
c.patch(n, lab2)
proc genBlock(c: var ProcCon; n: PNode; d: var Value) =
openScope c.sm
let info = toLineInfo(c, n.info)
let lab1 = newLabel(c.labelGen)
withBlock(n[0].sym, info, lab1):
c.gen(n[1], d)
c.code.addLabel(info, Label, lab1)
closeScope c.sm
c.clearDest(n, d)
proc jumpTo(c: var ProcCon; n: PNode; L: LabelId) =
c.code.addLabel(toLineInfo(c, n.info), Goto, L)
proc genBreak(c: var ProcCon; n: PNode) =
if n[0].kind == nkSym:
for i in countdown(c.blocks.len-1, 0):
if c.blocks[i][0] == n[0].sym:
c.jumpTo n, c.blocks[i][1]
return
localError(c.config, n.info, "NIR problem: cannot find 'break' target")
else:
c.jumpTo n, c.blocks[c.blocks.high][1]
proc genIf(c: var ProcCon; n: PNode; d: var Value) =
# if (!expr1) goto lab1;
# thenPart
# goto LEnd
# lab1:
# if (!expr2) goto lab2;
# thenPart2
# goto LEnd
# lab2:
# elsePart
# Lend:
if isEmpty(d) and not isEmptyType(n.typ): d = getTemp(c, n)
var ending = newLabel(c.labelGen)
for i in 0..<n.len:
var it = n[i]
if it.len == 2:
let info = toLineInfo(c, it[0].info)
var elsePos: LabelId
if isNotOpr(it[0]):
let tmp = c.genx(it[0][1])
elsePos = c.xjmp(it[0][1], opcTJmp, tmp) # if true
c.freeTemp tmp
else:
let tmp = c.genx(it[0])
elsePos = c.xjmp(it[0], opcFJmp, tmp) # if false
c.freeTemp tmp
c.clearDest(n, d)
if isEmptyType(it[1].typ): # maybe noreturn call, don't touch `d`
c.genScope(it[1])
else:
c.genScope(it[1], d) # then part
if i < n.len-1:
c.jumpTo it[1], ending
c.patch(it, elsePos)
else:
c.clearDest(n, d)
if isEmptyType(it[0].typ): # maybe noreturn call, don't touch `d`
c.genScope(it[0])
else:
c.genScope(it[0], d)
c.patch(n, ending)
c.clearDest(n, d)
proc tempToDest(c: var ProcCon; n: PNode; d: var Value; tmp: Value) =
if isEmpty(d):
d = tmp
else:
let info = toLineInfo(c, n.info)
buildTyped c.code, info, Asgn, typeToIr(c.m, n.typ):
c.code.copyTree d
c.code.copyTree tmp
freeTemp(c, tmp)
proc genAndOr(c: var ProcCon; n: PNode; opc: JmpKind; d: var Value) =
# asgn d, a
# tjmp|fjmp lab1
# asgn d, b
# lab1:
var tmp = getTemp(c, n)
c.gen(n[1], tmp)
let lab1 = c.xjmp(n, opc, tmp)
c.gen(n[2], tmp)
c.patch(n, lab1)
tempToDest c, n, d, tmp
proc unused(c: var ProcCon; n: PNode; x: Value) {.inline.} =
if hasValue(x):
#debug(n)
localError(c.config, n.info, "not unused")
proc caseValue(c: var ProcCon; n: PNode) =
let info = toLineInfo(c, n.info)
build c.code, info, SelectValue:
let x = genx(c, n)
c.code.copyTree x
freeTemp(c, x)
proc caseRange(c: var ProcCon; n: PNode) =
let info = toLineInfo(c, n.info)
build c.code, info, SelectRange:
let x = genx(c, n[0])
let y = genx(c, n[1])
c.code.copyTree x
c.code.copyTree y
freeTemp(c, y)
freeTemp(c, x)
proc addUseCodegenProc(c: var ProcCon; dest: var Tree; name: string; info: PackedLineInfo) =
let cp = getCompilerProc(c.m.graph, name)
let theProc = c.genx newSymNode(cp)
copyTree c.code, theProc
template buildCond(useNegation: bool; cond: typed; body: untyped) =
let lab = newLabel(c.labelGen)
buildTyped c.code, info, Select, Bool8Id:
c.code.copyTree cond
build c.code, info, SelectPair:
build c.code, info, SelectValue:
c.code.boolVal(c.lit.numbers, info, useNegation)
c.code.gotoLabel info, Goto, lab
body
c.code.addLabel info, Label, lab
template buildIf(cond: typed; body: untyped) =
buildCond false, cond, body
template buildIfNot(cond: typed; body: untyped) =
buildCond true, cond, body
template buildIfThenElse(cond: typed; then, otherwise: untyped) =
let lelse = newLabel(c.labelGen)
let lend = newLabel(c.labelGen)
buildTyped c.code, info, Select, Bool8Id:
c.code.copyTree cond
build c.code, info, SelectPair:
build c.code, info, SelectValue:
c.code.boolVal(c.lit.numbers, info, false)
c.code.gotoLabel info, Goto, lelse
then()
c.code.gotoLabel info, Goto, lend
c.code.addLabel info, Label, lelse
otherwise()
c.code.addLabel info, Label, lend
include stringcases
proc genCase(c: var ProcCon; n: PNode; d: var Value) =
if not isEmptyType(n.typ):
if isEmpty(d): d = getTemp(c, n)
else:
unused(c, n, d)
if n[0].typ.skipTypes(abstractInst).kind == tyString:
genStringCase(c, n, d)
return
var sections = newSeqOfCap[LabelId](n.len-1)
let ending = newLabel(c.labelGen)
let info = toLineInfo(c, n.info)
let tmp = c.genx(n[0])
buildTyped c.code, info, Select, typeToIr(c.m, n[0].typ):
c.code.copyTree tmp
for i in 1..<n.len:
let section = newLabel(c.labelGen)
sections.add section
let it = n[i]
let itinfo = toLineInfo(c, it.info)
build c.code, itinfo, SelectPair:
build c.code, itinfo, SelectList:
for j in 0..<it.len-1:
if it[j].kind == nkRange:
caseRange c, it[j]
else:
caseValue c, it[j]
c.code.addLabel itinfo, Goto, section
c.freeTemp tmp
for i in 1..<n.len:
let it = n[i]
let itinfo = toLineInfo(c, it.info)
c.code.addLabel itinfo, Label, sections[i-1]
c.gen it.lastSon
if i != n.len-1:
c.code.addLabel itinfo, Goto, ending
c.code.addLabel info, Label, ending
proc rawCall(c: var ProcCon; info: PackedLineInfo; opc: Opcode; t: TypeId; args: var openArray[Value]) =
buildTyped c.code, info, opc, t:
if opc in {CheckedCall, CheckedIndirectCall}:
c.code.addLabel info, CheckedGoto, c.exitLabel
for a in mitems(args):
c.code.copyTree a
freeTemp c, a
proc canRaiseDisp(c: ProcCon; n: PNode): bool =
# we assume things like sysFatal cannot raise themselves
if n.kind == nkSym and {sfNeverRaises, sfImportc, sfCompilerProc} * n.sym.flags != {}:
result = false
elif optPanics in c.config.globalOptions or
(n.kind == nkSym and sfSystemModule in getModule(n.sym).flags and
sfSystemRaisesDefect notin n.sym.flags):
# we know we can be strict:
result = canRaise(n)
else:
# we have to be *very* conservative:
result = canRaiseConservative(n)
proc genCall(c: var ProcCon; n: PNode; d: var Value) =
let canRaise = canRaiseDisp(c, n[0])
let opc = if n[0].kind == nkSym and n[0].sym.kind in routineKinds:
(if canRaise: CheckedCall else: Call)
else:
(if canRaise: CheckedIndirectCall else: IndirectCall)
let info = toLineInfo(c, n.info)
# In the IR we cannot nest calls. Thus we use two passes:
var args: seq[Value] = @[]
var t = n[0].typ
if t != nil: t = t.skipTypes(abstractInst)
args.add genx(c, n[0])
for i in 1..<n.len:
if t != nil and i < t.len:
if isCompileTimeOnly(t[i]): discard
elif isOutParam(t[i]): args.add genx(c, n[i], {gfToOutParam})
else: args.add genx(c, n[i])
else:
args.add genx(c, n[i])
let tb = typeToIr(c.m, n.typ)
if not isEmptyType(n.typ):
if isEmpty(d): d = getTemp(c, n)
# XXX Handle problematic aliasing here: `a = f_canRaise(a)`.
buildTyped c.code, info, Asgn, tb:
c.code.copyTree d
rawCall c, info, opc, tb, args
else:
rawCall c, info, opc, tb, args
freeTemps c, args
proc genRaise(c: var ProcCon; n: PNode) =
let info = toLineInfo(c, n.info)
let tb = typeToIr(c.m, n[0].typ)
let d = genx(c, n[0])
buildTyped c.code, info, SetExc, tb:
c.code.copyTree d
c.freeTemp(d)
c.code.addLabel info, Goto, c.exitLabel
proc genReturn(c: var ProcCon; n: PNode) =
if n[0].kind != nkEmpty:
gen(c, n[0])
# XXX Block leave actions?
let info = toLineInfo(c, n.info)
c.code.addLabel info, Goto, c.exitLabel
proc genTry(c: var ProcCon; n: PNode; d: var Value) =
if isEmpty(d) and not isEmptyType(n.typ): d = getTemp(c, n)
var endings: seq[LabelId] = @[]
let ehPos = newLabel(c.labelGen)
let oldExitLab = c.exitLabel
c.exitLabel = ehPos
if isEmptyType(n[0].typ): # maybe noreturn call, don't touch `d`
c.gen(n[0])
else:
c.gen(n[0], d)
c.clearDest(n, d)
# Add a jump past the exception handling code
let jumpToFinally = newLabel(c.labelGen)
c.jumpTo n, jumpToFinally
# This signals where the body ends and where the exception handling begins
c.patch(n, ehPos)
c.exitLabel = oldExitLab
for i in 1..<n.len:
let it = n[i]
if it.kind != nkFinally:
# first opcExcept contains the end label of the 'except' block:
let endExcept = newLabel(c.labelGen)
for j in 0..<it.len - 1:
assert(it[j].kind == nkType)
let typ = it[j].typ.skipTypes(abstractPtrs-{tyTypeDesc})
let itinfo = toLineInfo(c, it[j].info)
build c.code, itinfo, TestExc:
c.code.addTyped itinfo, typeToIr(c.m, typ)
if it.len == 1:
let itinfo = toLineInfo(c, it.info)
build c.code, itinfo, TestExc:
c.code.addTyped itinfo, VoidId
let body = it.lastSon
if isEmptyType(body.typ): # maybe noreturn call, don't touch `d`
c.gen(body)
else:
c.gen(body, d)
c.clearDest(n, d)
if i < n.len:
endings.add newLabel(c.labelGen)
c.patch(it, endExcept)
let fin = lastSon(n)
# we always generate an 'opcFinally' as that pops the safepoint
# from the stack if no exception is raised in the body.
c.patch(fin, jumpToFinally)
#c.gABx(fin, opcFinally, 0, 0)
for endPos in endings: c.patch(n, endPos)
if fin.kind == nkFinally:
c.gen(fin[0])
c.clearDest(n, d)
#c.gABx(fin, opcFinallyEnd, 0, 0)
template isGlobal(s: PSym): bool = sfGlobal in s.flags and s.kind != skForVar
proc isGlobal(n: PNode): bool = n.kind == nkSym and isGlobal(n.sym)
proc genField(c: var ProcCon; n: PNode; d: var Value) =
var pos: int
if n.kind != nkSym or n.sym.kind != skField:
localError(c.config, n.info, "no field symbol")
pos = 0
else:
pos = n.sym.position
d.addImmediateVal toLineInfo(c, n.info), pos
proc genIndex(c: var ProcCon; n: PNode; arr: PType; d: var Value) =
let info = toLineInfo(c, n.info)
if arr.skipTypes(abstractInst).kind == tyArray and
(let offset = firstOrd(c.config, arr); offset != Zero):
let x = c.genx(n)
buildTyped d, info, Sub, c.m.nativeIntId:
copyTree d.Tree, x
d.addImmediateVal toLineInfo(c, n.info), toInt(offset)
else:
c.gen(n, d)
if optBoundsCheck in c.options:
let idx = move d
build d, info, CheckedIndex:
d.Tree.addLabel info, CheckedGoto, c.exitLabel
copyTree d.Tree, idx
let x = toInt64 lengthOrd(c.config, arr)
d.addIntVal c.lit.numbers, info, c.m.nativeIntId, x
proc rawGenNew(c: var ProcCon; d: Value; refType: PType; ninfo: TLineInfo; needsInit: bool) =
assert refType.kind == tyRef
let baseType = refType.elementType
let info = toLineInfo(c, ninfo)
let codegenProc = magicsys.getCompilerProc(c.m.graph,
if needsInit: "nimNewObj" else: "nimNewObjUninit")
let refTypeIr = typeToIr(c.m, refType)
buildTyped c.code, info, Asgn, refTypeIr:
copyTree c.code, d
buildTyped c.code, info, Cast, refTypeIr:
buildTyped c.code, info, Call, VoidPtrId:
let theProc = c.genx newSymNode(codegenProc, ninfo)
copyTree c.code, theProc
c.code.addImmediateVal info, int(getSize(c.config, baseType))
c.code.addImmediateVal info, int(getAlign(c.config, baseType))
proc genNew(c: var ProcCon; n: PNode; needsInit: bool) =
# If in doubt, always follow the blueprint of the C code generator for `mm:orc`.
let refType = n[1].typ.skipTypes(abstractInstOwned)
let d = genx(c, n[1])
rawGenNew c, d, refType, n.info, needsInit
freeTemp c, d
proc genNewSeqOfCap(c: var ProcCon; n: PNode; d: var Value) =
let info = toLineInfo(c, n.info)
let seqtype = skipTypes(n.typ, abstractVarRange)
let baseType = seqtype.elementType
var a = c.genx(n[1])
if isEmpty(d): d = getTemp(c, n)
# $1.len = 0
buildTyped c.code, info, Asgn, c.m.nativeIntId:
buildTyped c.code, info, FieldAt, typeToIr(c.m, seqtype):
copyTree c.code, d
c.code.addImmediateVal info, 0
c.code.addImmediateVal info, 0
# $1.p = ($4*) #newSeqPayloadUninit($2, sizeof($3), NIM_ALIGNOF($3))
let payloadPtr = seqPayloadPtrType(c.m.types, c.m.nirm.types, seqtype)[0]
buildTyped c.code, info, Asgn, payloadPtr:
# $1.p
buildTyped c.code, info, FieldAt, typeToIr(c.m, seqtype):
copyTree c.code, d
c.code.addImmediateVal info, 1
# ($4*) #newSeqPayloadUninit($2, sizeof($3), NIM_ALIGNOF($3))
buildTyped c.code, info, Cast, payloadPtr:
buildTyped c.code, info, Call, VoidPtrId:
let codegenProc = magicsys.getCompilerProc(c.m.graph, "newSeqPayloadUninit")
let theProc = c.genx newSymNode(codegenProc, n.info)
copyTree c.code, theProc
copyTree c.code, a
c.code.addImmediateVal info, int(getSize(c.config, baseType))
c.code.addImmediateVal info, int(getAlign(c.config, baseType))
freeTemp c, a
proc genNewSeqPayload(c: var ProcCon; info: PackedLineInfo; d, b: Value; seqtype: PType) =
let baseType = seqtype.elementType
# $1.p = ($4*) #newSeqPayload($2, sizeof($3), NIM_ALIGNOF($3))
let payloadPtr = seqPayloadPtrType(c.m.types, c.m.nirm.types, seqtype)[0]
# $1.len = $2
buildTyped c.code, info, Asgn, c.m.nativeIntId:
buildTyped c.code, info, FieldAt, typeToIr(c.m, seqtype):
copyTree c.code, d
c.code.addImmediateVal info, 0
copyTree c.code, b
buildTyped c.code, info, Asgn, payloadPtr:
# $1.p
buildTyped c.code, info, FieldAt, typeToIr(c.m, seqtype):
copyTree c.code, d
c.code.addImmediateVal info, 1
# ($4*) #newSeqPayload($2, sizeof($3), NIM_ALIGNOF($3))
buildTyped c.code, info, Cast, payloadPtr:
buildTyped c.code, info, Call, VoidPtrId:
let codegenProc = magicsys.getCompilerProc(c.m.graph, "newSeqPayload")
let theProc = c.genx newSymNode(codegenProc)
copyTree c.code, theProc
copyTree c.code, b
c.code.addImmediateVal info, int(getSize(c.config, baseType))
c.code.addImmediateVal info, int(getAlign(c.config, baseType))
proc genNewSeq(c: var ProcCon; n: PNode) =
let info = toLineInfo(c, n.info)
let seqtype = skipTypes(n[1].typ, abstractVarRange)
var d = c.genx(n[1])
var b = c.genx(n[2])
genNewSeqPayload(c, info, d, b, seqtype)
freeTemp c, b
freeTemp c, d
template intoDest*(d: var Value; info: PackedLineInfo; typ: TypeId; body: untyped) =
if typ == VoidId:
body(c.code)
elif isEmpty(d):
body(Tree(d))
else:
buildTyped c.code, info, Asgn, typ:
copyTree c.code, d
body(c.code)
template valueIntoDest(c: var ProcCon; info: PackedLineInfo; d: var Value; typ: PType; body: untyped) =
if isEmpty(d):
body(Tree d)
else:
buildTyped c.code, info, Asgn, typeToIr(c.m, typ):
copyTree c.code, d
body(c.code)
template constrIntoDest(c: var ProcCon; info: PackedLineInfo; d: var Value; typ: PType; body: untyped) =
var tmp = default(Value)
body(Tree tmp)
if isEmpty(d):
d = tmp
else:
buildTyped c.code, info, Asgn, typeToIr(c.m, typ):
copyTree c.code, d
copyTree c.code, tmp
proc genBinaryOp(c: var ProcCon; n: PNode; d: var Value; opc: Opcode) =
let info = toLineInfo(c, n.info)
let tmp = c.genx(n[1])
let tmp2 = c.genx(n[2])
let t = typeToIr(c.m, n.typ)
template body(target) =
buildTyped target, info, opc, t:
if opc in {CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, CheckedMod}:
target.addLabel info, CheckedGoto, c.exitLabel
copyTree target, tmp
copyTree target, tmp2
intoDest d, info, t, body
c.freeTemp(tmp)
c.freeTemp(tmp2)
proc genCmpOp(c: var ProcCon; n: PNode; d: var Value; opc: Opcode) =
let info = toLineInfo(c, n.info)
let tmp = c.genx(n[1])
let tmp2 = c.genx(n[2])
let t = typeToIr(c.m, n[1].typ)
template body(target) =
buildTyped target, info, opc, t:
copyTree target, tmp
copyTree target, tmp2
intoDest d, info, Bool8Id, body
c.freeTemp(tmp)
c.freeTemp(tmp2)
proc genUnaryOp(c: var ProcCon; n: PNode; d: var Value; opc: Opcode) =
let info = toLineInfo(c, n.info)
let tmp = c.genx(n[1])
let t = typeToIr(c.m, n.typ)
template body(target) =
buildTyped target, info, opc, t:
copyTree target, tmp
intoDest d, info, t, body
c.freeTemp(tmp)
proc genIncDec(c: var ProcCon; n: PNode; opc: Opcode) =
let info = toLineInfo(c, n.info)
let t = typeToIr(c.m, skipTypes(n[1].typ, abstractVar))
let d = c.genx(n[1])
let tmp = c.genx(n[2])
# we produce code like: i = i + 1
buildTyped c.code, info, Asgn, t:
copyTree c.code, d
buildTyped c.code, info, opc, t:
if opc in {CheckedAdd, CheckedSub}:
c.code.addLabel info, CheckedGoto, c.exitLabel
copyTree c.code, d
copyTree c.code, tmp
c.freeTemp(tmp)
#c.genNarrow(n[1], d)
c.freeTemp(d)
proc genArrayLen(c: var ProcCon; n: PNode; d: var Value) =
#echo c.m.graph.config $ n.info, " ", n
let info = toLineInfo(c, n.info)
var a = n[1]
#if a.kind == nkHiddenAddr: a = a[0]
var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
case typ.kind
of tyOpenArray, tyVarargs:
let xa = c.genx(a)
template body(target) =
buildTyped target, info, FieldAt, typeToIr(c.m, typ):
copyTree target, xa
target.addImmediateVal info, 1 # (p, len)-pair so len is at index 1
intoDest d, info, c.m.nativeIntId, body
of tyCstring:
let xa = c.genx(a)
if isEmpty(d): d = getTemp(c, n)
buildTyped c.code, info, Call, c.m.nativeIntId:
let codegenProc = magicsys.getCompilerProc(c.m.graph, "nimCStrLen")
assert codegenProc != nil
let theProc = c.genx newSymNode(codegenProc, n.info)
copyTree c.code, theProc
copyTree c.code, xa
of tyString, tySequence:
let xa = c.genx(a)
if typ.kind == tySequence:
# we go through a temporary here because people write bullshit code.
if isEmpty(d): d = getTemp(c, n)
template body(target) =
buildTyped target, info, FieldAt, typeToIr(c.m, typ):
copyTree target, xa
target.addImmediateVal info, 0 # (len, p)-pair so len is at index 0
intoDest d, info, c.m.nativeIntId, body
of tyArray:
template body(target) =
target.addIntVal(c.lit.numbers, info, c.m.nativeIntId, toInt lengthOrd(c.config, typ))
intoDest d, info, c.m.nativeIntId, body
else: internalError(c.config, n.info, "genArrayLen()")
proc genUnaryMinus(c: var ProcCon; n: PNode; d: var Value) =
let info = toLineInfo(c, n.info)
let tmp = c.genx(n[1])
let t = typeToIr(c.m, n.typ)
template body(target) =
buildTyped target, info, Sub, t:
# Little hack: This works because we know that `0.0` is all 0 bits:
target.addIntVal(c.lit.numbers, info, t, 0)
copyTree target, tmp
intoDest d, info, t, body
c.freeTemp(tmp)
proc genHigh(c: var ProcCon; n: PNode; d: var Value) =
let info = toLineInfo(c, n.info)
let t = typeToIr(c.m, n.typ)
var x = default(Value)
genArrayLen(c, n, x)
template body(target) =
buildTyped target, info, Sub, t:
copyTree target, x
target.addIntVal(c.lit.numbers, info, t, 1)
intoDest d, info, t, body
c.freeTemp x
proc genBinaryCp(c: var ProcCon; n: PNode; d: var Value; compilerProc: string) =
let info = toLineInfo(c, n.info)
let xa = c.genx(n[1])
let xb = c.genx(n[2])
if isEmpty(d) and not isEmptyType(n.typ): d = getTemp(c, n)
let t = typeToIr(c.m, n.typ)
template body(target) =
buildTyped target, info, Call, t:
let codegenProc = magicsys.getCompilerProc(c.m.graph, compilerProc)
#assert codegenProc != nil, $n & " " & (c.m.graph.config $ n.info)
let theProc = c.genx newSymNode(codegenProc, n.info)
copyTree target, theProc
copyTree target, xa
copyTree target, xb
intoDest d, info, t, body
c.freeTemp xb
c.freeTemp xa
proc genUnaryCp(c: var ProcCon; n: PNode; d: var Value; compilerProc: string; argAt = 1) =
let info = toLineInfo(c, n.info)
let xa = c.genx(n[argAt])
if isEmpty(d) and not isEmptyType(n.typ): d = getTemp(c, n)
let t = typeToIr(c.m, n.typ)
template body(target) =
buildTyped target, info, Call, t:
let codegenProc = magicsys.getCompilerProc(c.m.graph, compilerProc)
let theProc = c.genx newSymNode(codegenProc, n.info)
copyTree target, theProc
copyTree target, xa
intoDest d, info, t, body
c.freeTemp xa
proc genEnumToStr(c: var ProcCon; n: PNode; d: var Value) =
let t = n[1].typ.skipTypes(abstractInst+{tyRange})
let toStrProc = getToStringProc(c.m.graph, t)
# XXX need to modify this logic for IC.
var nb = copyTree(n)
nb[0] = newSymNode(toStrProc)
gen(c, nb, d)
proc genOf(c: var ProcCon; n: PNode; d: var Value) =
genUnaryOp c, n, d, TestOf
template sizeOfLikeMsg(name): string =
"'" & name & "' requires '.importc' types to be '.completeStruct'"
proc genIsNil(c: var ProcCon; n: PNode; d: var Value) =
let info = toLineInfo(c, n.info)
let tmp = c.genx(n[1])
let t = typeToIr(c.m, n[1].typ)
template body(target) =
buildTyped target, info, Eq, t:
copyTree target, tmp
addNilVal target, info, t
intoDest d, info, Bool8Id, body
c.freeTemp(tmp)
proc fewCmps(conf: ConfigRef; 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:
result = false
elif (getSize(conf, s.typ) <= conf.target.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 = s.len <= 8 # 8 seems to be a good value
proc genInBitset(c: var ProcCon; n: PNode; d: var Value) =
let info = toLineInfo(c, n.info)
let a = c.genx(n[1])
let b = c.genx(n[2])
let t = bitsetBasetype(c.m.types, c.m.nirm.types, n[1].typ)
let setType = typeToIr(c.m, n[1].typ)
let mask =
case t
of UInt8Id: 7
of UInt16Id: 15
of UInt32Id: 31
else: 63
let expansion = if t == UInt64Id: UInt64Id else: c.m.nativeUIntId
# "(($1 &(1U<<((NU)($2)&7U)))!=0)" - or -
# "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)"
template body(target) =
buildTyped target, info, BoolNot, Bool8Id:
buildTyped target, info, Eq, t:
buildTyped target, info, BitAnd, t:
if c.m.nirm.types[setType].kind != ArrayTy:
copyTree target, a
else:
buildTyped target, info, ArrayAt, setType:
copyTree target, a
buildTyped target, info, BitShr, t:
buildTyped target, info, Cast, expansion:
copyTree target, b
addIntVal target, c.lit.numbers, info, expansion, 3
buildTyped target, info, BitShl, t:
addIntVal target, c.lit.numbers, info, t, 1
buildTyped target, info, BitAnd, t:
buildTyped target, info, Cast, expansion:
copyTree target, b
addIntVal target, c.lit.numbers, info, expansion, mask
addIntVal target, c.lit.numbers, info, t, 0
intoDest d, info, t, body
c.freeTemp(b)
c.freeTemp(a)
proc genInSet(c: var ProcCon; n: PNode; d: var Value) =
let g {.cursor.} = c.m.graph
if n[1].kind == nkCurly and fewCmps(g.config, n[1]):
# a set constructor but not a constant set:
# do not emit the set, but generate a bunch of comparisons; and if we do
# so, we skip the unnecessary range check: This is a semantical extension
# that code now relies on. :-/ XXX
let elem = if n[2].kind in {nkChckRange, nkChckRange64}: n[2][0]
else: n[2]
let curly = n[1]
var ex: PNode = nil
for it in curly:
var test: PNode
if it.kind == nkRange:
test = newTree(nkCall, g.operators.opAnd.newSymNode,
newTree(nkCall, g.operators.opLe.newSymNode, it[0], elem), # a <= elem
newTree(nkCall, g.operators.opLe.newSymNode, elem, it[1])
)
else:
test = newTree(nkCall, g.operators.opEq.newSymNode, elem, it)
test.typ = getSysType(g, it.info, tyBool)
if ex == nil: ex = test
else: ex = newTree(nkCall, g.operators.opOr.newSymNode, ex, test)
if ex == nil:
let info = toLineInfo(c, n.info)
template body(target) =
boolVal target, c.lit.numbers, info, false
intoDest d, info, Bool8Id, body
else:
gen c, ex, d
else:
genInBitset c, n, d
proc genCard(c: var ProcCon; n: PNode; d: var Value) =
let info = toLineInfo(c, n.info)
let a = c.genx(n[1])
let t = typeToIr(c.m, n.typ)
let setType = typeToIr(c.m, n[1].typ)
if isEmpty(d): d = getTemp(c, n)
buildTyped c.code, info, Asgn, t:
copyTree c.code, d
buildTyped c.code, info, Call, t:
if c.m.nirm.types[setType].kind == ArrayTy:
let codegenProc = magicsys.getCompilerProc(c.m.graph, "cardSet")
let theProc = c.genx newSymNode(codegenProc, n.info)
copyTree c.code, theProc
buildTyped c.code, info, AddrOf, ptrTypeOf(c.m.nirm.types, setType):
copyTree c.code, a
c.code.addImmediateVal info, int(getSize(c.config, n[1].typ))
elif t == UInt64Id: