-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathvmgen.nim
2450 lines (2270 loc) · 83.2 KB
/
vmgen.nim
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 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This module implements the code generator for the VM.
# Important things to remember:
# - The VM does not distinguish between definitions ('var x = y') and
# assignments ('x = y'). For simple data types that fit into a register
# this doesn't matter. However it matters for strings and other complex
# types that use the 'node' field; the reason is that slots are
# re-used in a register based VM. Example:
# ```nim
# let s = a & b # no matter what, create fresh node
# s = a & b # no matter what, keep the node
# ```
# Also *stores* into non-temporary memory need to perform deep copies:
# a.b = x.y
# We used to generate opcAsgn for the *load* of 'x.y' but this is clearly
# wrong! We need to produce opcAsgn (the copy) for the *store*. This also
# solves the opcLdConst vs opcAsgnConst issue. Of course whether we need
# this copy depends on the involved types.
import std/[tables, intsets, strutils]
when defined(nimPreviewSlimSystem):
import std/assertions
import
ast, types, msgs, renderer, vmdef, trees,
magicsys, options, lowerings, lineinfos, transf, astmsgs
from modulegraphs import getBody
when defined(nimCompilerStacktraceHints):
import std/stackframes
const
debugEchoCode* = defined(nimVMDebug)
when debugEchoCode:
import std/private/asciitables
when hasFFI:
import evalffi
type
TGenFlag = enum
gfNode # Affects how variables are loaded - always loads as rkNode
gfNodeAddr # Affects how variables are loaded - always loads as rkNodeAddr
gfIsParam # do not deepcopy parameters, they are immutable
gfIsSinkParam # deepcopy sink parameters
TGenFlags = set[TGenFlag]
proc debugInfo(c: PCtx; info: TLineInfo): string =
result = toFileLineCol(c.config, info)
proc codeListing(c: PCtx, result: var string, start=0; last = -1) =
## for debugging purposes
# first iteration: compute all necessary labels:
var jumpTargets = initIntSet()
let last = if last < 0: c.code.len-1 else: min(last, c.code.len-1)
for i in start..last:
let x = c.code[i]
if x.opcode in relativeJumps:
jumpTargets.incl(i+x.regBx-wordExcess)
template toStr(opc: TOpcode): string = ($opc).substr(3)
result.add "code listing:\n"
var i = start
while i <= last:
if i in jumpTargets: result.addf("L$1:\n", i)
let x = c.code[i]
result.add($i)
let opc = opcode(x)
if opc in {opcIndCall, opcIndCallAsgn}:
result.addf("\t$#\tr$#, r$#, nargs:$#", opc.toStr, x.regA,
x.regB, x.regC)
elif opc in {opcConv, opcCast}:
let y = c.code[i+1]
let z = c.code[i+2]
result.addf("\t$#\tr$#, r$#, $#, $#", opc.toStr, x.regA, x.regB,
c.types[y.regBx-wordExcess].typeToString,
c.types[z.regBx-wordExcess].typeToString)
inc i, 2
elif opc < firstABxInstr:
result.addf("\t$#\tr$#, r$#, r$#", opc.toStr, x.regA,
x.regB, x.regC)
elif opc in relativeJumps + {opcTry}:
result.addf("\t$#\tr$#, L$#", opc.toStr, x.regA,
i+x.regBx-wordExcess)
elif opc in {opcExcept}:
let idx = x.regBx-wordExcess
result.addf("\t$#\t$#, $#", opc.toStr, x.regA, $idx)
elif opc in {opcLdConst, opcAsgnConst}:
let idx = x.regBx-wordExcess
result.addf("\t$#\tr$#, $# ($#)", opc.toStr, x.regA,
c.constants[idx].renderTree, $idx)
else:
result.addf("\t$#\tr$#, $#", opc.toStr, x.regA, x.regBx-wordExcess)
result.add("\t# ")
result.add(debugInfo(c, c.debug[i]))
result.add("\n")
inc i
when debugEchoCode:
result = result.alignTable
proc echoCode*(c: PCtx; start=0; last = -1) {.deprecated.} =
var buf = ""
codeListing(c, buf, start, last)
echo buf
proc gABC(ctx: PCtx; n: PNode; opc: TOpcode;
a: TRegister = 0, b: TRegister = 0, c: TRegister = 0) =
## Takes the registers `b` and `c`, applies the operation `opc` to them, and
## stores the result into register `a`
## The node is needed for debug information
assert opc.ord < 255
let ins = (opc.TInstrType or (a.TInstrType shl regAShift) or
(b.TInstrType shl regBShift) or
(c.TInstrType shl regCShift)).TInstr
when false:
if ctx.code.len == 43:
writeStackTrace()
echo "generating ", opc
ctx.code.add(ins)
ctx.debug.add(n.info)
proc gABI(c: PCtx; n: PNode; opc: TOpcode; a, b: TRegister; imm: BiggestInt) =
# Takes the `b` register and the immediate `imm`, applies the operation `opc`,
# and stores the output value into `a`.
# `imm` is signed and must be within [-128, 127]
if imm >= -128 and imm <= 127:
let ins = (opc.TInstrType or (a.TInstrType shl regAShift) or
(b.TInstrType shl regBShift) or
(imm+byteExcess).TInstrType shl regCShift).TInstr
c.code.add(ins)
c.debug.add(n.info)
else:
localError(c.config, n.info,
"VM: immediate value does not fit into an int8")
proc gABx(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0; bx: int) =
# Applies `opc` to `bx` and stores it into register `a`
# `bx` must be signed and in the range [regBxMin, regBxMax]
when false:
if c.code.len == 43:
writeStackTrace()
echo "generating ", opc
if bx >= regBxMin-1 and bx <= regBxMax:
let ins = (opc.TInstrType or a.TInstrType shl regAShift or
(bx+wordExcess).TInstrType shl regBxShift).TInstr
c.code.add(ins)
c.debug.add(n.info)
else:
localError(c.config, n.info,
"VM: immediate value does not fit into regBx")
proc xjmp(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0): TPosition =
#assert opc in {opcJmp, opcFJmp, opcTJmp}
result = TPosition(c.code.len)
gABx(c, n, opc, a, 0)
proc genLabel(c: PCtx): TPosition =
result = TPosition(c.code.len)
#c.jumpTargets.incl(c.code.len)
proc jmpBack(c: PCtx, n: PNode, p = TPosition(0)) =
let dist = p.int - c.code.len
internalAssert(c.config, regBxMin < dist and dist < regBxMax)
gABx(c, n, opcJmpBack, 0, dist)
proc patch(c: PCtx, p: TPosition) =
# patch with current index
let p = p.int
let diff = c.code.len - p
#c.jumpTargets.incl(c.code.len)
internalAssert(c.config, regBxMin < diff and diff < regBxMax)
let oldInstr = c.code[p]
# opcode and regA stay the same:
c.code[p] = ((oldInstr.TInstrType and regBxMask).TInstrType or
TInstrType(diff+wordExcess) shl regBxShift).TInstr
proc getSlotKind(t: PType): TSlotKind =
case t.skipTypes(abstractRange-{tyTypeDesc}).kind
of tyBool, tyChar, tyEnum, tyOrdinal, tyInt..tyInt64, tyUInt..tyUInt64:
slotTempInt
of tyString, tyCstring:
slotTempStr
of tyFloat..tyFloat128:
slotTempFloat
else:
slotTempComplex
const
HighRegisterPressure = 40
proc bestEffort(c: PCtx): TLineInfo =
if c.prc != nil and c.prc.sym != nil:
c.prc.sym.info
else:
c.module.info
proc getFreeRegister(cc: PCtx; k: TSlotKind; start: int): TRegister =
let c = cc.prc
# we prefer the same slot kind here for efficiency. Unfortunately for
# discardable return types we may not know the desired type. This can happen
# for e.g. mNAdd[Multiple]:
for i in start..c.regInfo.len-1:
if c.regInfo[i].kind == k and not c.regInfo[i].inUse:
c.regInfo[i].inUse = true
return TRegister(i)
# if register pressure is high, we re-use more aggressively:
if c.regInfo.len >= high(TRegister):
for i in start..c.regInfo.len-1:
if not c.regInfo[i].inUse:
c.regInfo[i] = (inUse: true, kind: k)
return TRegister(i)
if c.regInfo.len >= high(TRegister):
globalError(cc.config, cc.bestEffort, "VM problem: too many registers required")
result = TRegister(max(c.regInfo.len, start))
c.regInfo.setLen int(result)+1
c.regInfo[result] = (inUse: true, kind: k)
proc getTemp(cc: PCtx; tt: PType): TRegister =
let typ = tt.skipTypesOrNil({tyStatic})
# we prefer the same slot kind here for efficiency. Unfortunately for
# discardable return types we may not know the desired type. This can happen
# for e.g. mNAdd[Multiple]:
let k = if typ.isNil: slotTempComplex else: typ.getSlotKind
result = getFreeRegister(cc, k, start = 0)
when false:
# enable this to find "register" leaks:
if result == 4:
echo "begin ---------------"
writeStackTrace()
echo "end ----------------"
proc freeTemp(c: PCtx; r: TRegister) =
let c = c.prc
if r < c.regInfo.len and c.regInfo[r].kind in {slotSomeTemp..slotTempComplex}:
# this seems to cause https://github.com/nim-lang/Nim/issues/10647
c.regInfo[r].inUse = false
proc getTempRange(cc: PCtx; n: int; kind: TSlotKind): TRegister =
# if register pressure is high, we re-use more aggressively:
let c = cc.prc
# we could also customize via the following (with proper caching in ConfigRef):
# let highRegisterPressure = cc.config.getConfigVar("vm.highRegisterPressure", "40").parseInt
if c.regInfo.len >= HighRegisterPressure or c.regInfo.len+n >= high(TRegister):
for i in 0..c.regInfo.len-n:
if not c.regInfo[i].inUse:
block search:
for j in i+1..i+n-1:
if c.regInfo[j].inUse: break search
result = TRegister(i)
for k in result..result+n-1: c.regInfo[k] = (inUse: true, kind: kind)
return
if c.regInfo.len+n >= high(TRegister):
globalError(cc.config, cc.bestEffort, "VM problem: too many registers required")
result = TRegister(c.regInfo.len)
setLen c.regInfo, c.regInfo.len+n
for k in result..result+n-1: c.regInfo[k] = (inUse: true, kind: kind)
proc freeTempRange(c: PCtx; start: TRegister, n: int) =
for i in start..start+n-1: c.freeTemp(TRegister(i))
template withTemp(tmp, typ, body: untyped) {.dirty.} =
var tmp = getTemp(c, typ)
body
c.freeTemp(tmp)
proc popBlock(c: PCtx; oldLen: int) =
for f in c.prc.blocks[oldLen].fixups:
c.patch(f)
c.prc.blocks.setLen(oldLen)
template withBlock(labl: PSym; body: untyped) {.dirty.} =
var oldLen {.gensym.} = c.prc.blocks.len
c.prc.blocks.add TBlock(label: labl, fixups: @[])
body
popBlock(c, oldLen)
proc gen(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags = {})
proc gen(c: PCtx; n: PNode; dest: TRegister; flags: TGenFlags = {}) =
var d: TDest = dest
gen(c, n, d, flags)
#internalAssert c.config, d == dest # issue #7407
proc gen(c: PCtx; n: PNode; flags: TGenFlags = {}) =
var tmp: TDest = -1
gen(c, n, tmp, flags)
if tmp >= 0:
freeTemp(c, tmp)
#if n.typ.isEmptyType: internalAssert tmp < 0
proc genx(c: PCtx; n: PNode; flags: TGenFlags = {}): TRegister =
var tmp: TDest = -1
gen(c, n, tmp, flags)
#internalAssert c.config, tmp >= 0 # 'nim check' does not like this internalAssert.
if tmp >= 0:
result = TRegister(tmp)
else:
result = 0
proc clearDest(c: PCtx; n: PNode; dest: var TDest) {.inline.} =
# stmt is different from 'void' in meta programming contexts.
# So we only set dest to -1 if 'void':
if dest >= 0 and (n.typ.isNil or n.typ.kind == tyVoid):
c.freeTemp(dest)
dest = -1
proc isNotOpr(n: PNode): bool =
n.kind in nkCallKinds and n[0].kind == nkSym and
n[0].sym.magic == mNot
proc genWhile(c: PCtx; n: PNode) =
# lab1:
# cond, tmp
# fjmp tmp, lab2
# body
# jmp lab1
# lab2:
let lab1 = c.genLabel
withBlock(nil):
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(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(lab2)
proc genBlock(c: PCtx; n: PNode; dest: var TDest) =
let oldRegisterCount = c.prc.regInfo.len
withBlock(n[0].sym):
c.gen(n[1], dest)
for i in oldRegisterCount..<c.prc.regInfo.len:
#if c.prc.regInfo[i].kind in {slotFixedVar, slotFixedLet}:
if i != dest:
when not defined(release):
if c.config.cmd != cmdCheck:
if c.prc.regInfo[i].inUse and c.prc.regInfo[i].kind in {slotTempUnknown,
slotTempInt,
slotTempFloat,
slotTempStr,
slotTempComplex}:
raiseAssert "leaking temporary " & $i & " " & $c.prc.regInfo[i].kind
c.prc.regInfo[i] = (inUse: false, kind: slotEmpty)
c.clearDest(n, dest)
proc genBreak(c: PCtx; n: PNode) =
let lab1 = c.xjmp(n, opcJmp)
if n[0].kind == nkSym:
#echo cast[int](n[0].sym)
for i in countdown(c.prc.blocks.len-1, 0):
if c.prc.blocks[i].label == n[0].sym:
c.prc.blocks[i].fixups.add lab1
return
globalError(c.config, n.info, "VM problem: cannot find 'break' target")
else:
c.prc.blocks[c.prc.blocks.high].fixups.add lab1
proc genIf(c: PCtx, n: PNode; dest: var TDest) =
# if (!expr1) goto lab1;
# thenPart
# goto LEnd
# lab1:
# if (!expr2) goto lab2;
# thenPart2
# goto LEnd
# lab2:
# elsePart
# Lend:
if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
var endings: seq[TPosition] = @[]
for i in 0..<n.len:
var it = n[i]
if it.len == 2:
withTemp(tmp, it[0].typ):
var elsePos: TPosition
if isNotOpr(it[0]):
c.gen(it[0][1], tmp)
elsePos = c.xjmp(it[0][1], opcTJmp, tmp) # if true
else:
c.gen(it[0], tmp)
elsePos = c.xjmp(it[0], opcFJmp, tmp) # if false
c.clearDest(n, dest)
if isEmptyType(it[1].typ): # maybe noreturn call, don't touch `dest`
c.gen(it[1])
else:
c.gen(it[1], dest) # then part
if i < n.len-1:
endings.add(c.xjmp(it[1], opcJmp, 0))
c.patch(elsePos)
else:
c.clearDest(n, dest)
if isEmptyType(it[0].typ): # maybe noreturn call, don't touch `dest`
c.gen(it[0])
else:
c.gen(it[0], dest)
for endPos in endings: c.patch(endPos)
c.clearDest(n, dest)
proc isTemp(c: PCtx; dest: TDest): bool =
result = dest >= 0 and c.prc.regInfo[dest].kind >= slotTempUnknown
proc genAndOr(c: PCtx; n: PNode; opc: TOpcode; dest: var TDest) =
# asgn dest, a
# tjmp|fjmp lab1
# asgn dest, b
# lab1:
let copyBack = dest < 0 or not isTemp(c, dest)
let tmp = if copyBack:
getTemp(c, n.typ)
else:
TRegister dest
c.gen(n[1], tmp)
let lab1 = c.xjmp(n, opc, tmp)
c.gen(n[2], tmp)
c.patch(lab1)
if dest < 0:
dest = tmp
elif copyBack:
c.gABC(n, opcAsgnInt, dest, tmp)
freeTemp(c, tmp)
proc rawGenLiteral(c: PCtx; n: PNode): int =
result = c.constants.len
#assert(n.kind != nkCall)
n.flags.incl nfAllConst
n.flags.excl nfIsRef
c.constants.add n
internalAssert c.config, result < regBxMax
proc sameConstant*(a, b: PNode): bool =
result = false
if a == b:
result = true
elif a != nil and b != nil and a.kind == b.kind:
case a.kind
of nkSym: result = a.sym == b.sym
of nkIdent: result = a.ident.id == b.ident.id
of nkCharLit..nkUInt64Lit: result = a.intVal == b.intVal
of nkFloatLit..nkFloat64Lit:
result = cast[uint64](a.floatVal) == cast[uint64](b.floatVal)
# refs bug #16469
# if we wanted to only distinguish 0.0 vs -0.0:
# if a.floatVal == 0.0: result = cast[uint64](a.floatVal) == cast[uint64](b.floatVal)
# else: result = a.floatVal == b.floatVal
of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal
of nkType, nkNilLit: result = a.typ == b.typ
of nkEmpty: result = true
else:
if a.len == b.len:
for i in 0..<a.len:
if not sameConstant(a[i], b[i]): return
result = true
proc genLiteral(c: PCtx; n: PNode): int =
# types do not matter here:
for i in 0..<c.constants.len:
if sameConstant(c.constants[i], n): return i
result = rawGenLiteral(c, n)
proc unused(c: PCtx; n: PNode; x: TDest) {.inline.} =
if x >= 0:
#debug(n)
globalError(c.config, n.info, "not unused")
proc genCase(c: PCtx; n: PNode; dest: var TDest) =
# if (!expr1) goto lab1;
# thenPart
# goto LEnd
# lab1:
# if (!expr2) goto lab2;
# thenPart2
# goto LEnd
# lab2:
# elsePart
# Lend:
if not isEmptyType(n.typ):
if dest < 0: dest = getTemp(c, n.typ)
else:
unused(c, n, dest)
var endings: seq[TPosition] = @[]
withTemp(tmp, n[0].typ):
c.gen(n[0], tmp)
# branch tmp, codeIdx
# fjmp elseLabel
for i in 1..<n.len:
let it = n[i]
if it.len == 1:
# else stmt:
let body = it[0]
if body.kind != nkNilLit or body.typ != nil:
# an nkNilLit with nil for typ implies there is no else branch, this
# avoids unused related errors as we've already consumed the dest
if isEmptyType(body.typ): # maybe noreturn call, don't touch `dest`
c.gen(body)
else:
c.gen(body, dest)
else:
let b = rawGenLiteral(c, it)
c.gABx(it, opcBranch, tmp, b)
let body = it.lastSon
let elsePos = c.xjmp(body, opcFJmp, tmp)
if isEmptyType(body.typ): # maybe noreturn call, don't touch `dest`
c.gen(body)
else:
c.gen(body, dest)
if i < n.len-1:
endings.add(c.xjmp(body, opcJmp, 0))
c.patch(elsePos)
c.clearDest(n, dest)
for endPos in endings: c.patch(endPos)
proc genType(c: PCtx; typ: PType): int =
for i, t in c.types:
if sameType(t, typ): return i
result = c.types.len
c.types.add(typ)
internalAssert(c.config, result <= regBxMax)
proc genTry(c: PCtx; n: PNode; dest: var TDest) =
if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
var endings: seq[TPosition] = @[]
let ehPos = c.xjmp(n, opcTry, 0)
if isEmptyType(n[0].typ): # maybe noreturn call, don't touch `dest`
c.gen(n[0])
else:
c.gen(n[0], dest)
c.clearDest(n, dest)
# Add a jump past the exception handling code
let jumpToFinally = c.xjmp(n, opcJmp, 0)
# This signals where the body ends and where the exception handling begins
c.patch(ehPos)
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 = c.xjmp(it, opcExcept, 0)
for j in 0..<it.len - 1:
assert(it[j].kind == nkType)
let typ = it[j].typ.skipTypes(abstractPtrs-{tyTypeDesc})
c.gABx(it, opcExcept, 0, c.genType(typ))
if it.len == 1:
# general except section:
c.gABx(it, opcExcept, 0, 0)
let body = it.lastSon
if isEmptyType(body.typ): # maybe noreturn call, don't touch `dest`
c.gen(body)
else:
c.gen(body, dest)
c.clearDest(n, dest)
if i < n.len:
endings.add(c.xjmp(it, opcJmp, 0))
c.patch(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(jumpToFinally)
c.gABx(fin, opcFinally, 0, 0)
for endPos in endings: c.patch(endPos)
if fin.kind == nkFinally:
c.gen(fin[0])
c.clearDest(n, dest)
c.gABx(fin, opcFinallyEnd, 0, 0)
proc genRaise(c: PCtx; n: PNode) =
let dest = genx(c, n[0])
c.gABC(n, opcRaise, dest)
c.freeTemp(dest)
proc genReturn(c: PCtx; n: PNode) =
if n[0].kind != nkEmpty:
gen(c, n[0])
c.gABC(n, opcRet)
proc genLit(c: PCtx; n: PNode; dest: var TDest) =
# opcLdConst is now always valid. We produce the necessary copy in the
# assignments now:
#var opc = opcLdConst
if dest < 0: dest = c.getTemp(n.typ)
#elif c.prc.regInfo[dest].kind == slotFixedVar: opc = opcAsgnConst
let lit = genLiteral(c, n)
c.gABx(n, opcLdConst, dest, lit)
proc genCall(c: PCtx; n: PNode; dest: var TDest) =
# it can happen that due to inlining we have a 'n' that should be
# treated as a constant (see issue #537).
#if n.typ != nil and n.typ.sym != nil and n.typ.sym.magic == mPNimrodNode:
# genLit(c, n, dest)
# return
# bug #10901: do not produce code for wrong call expressions:
if n.len == 0 or n[0].typ.isNil: return
if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
let x = c.getTempRange(n.len, slotTempUnknown)
# varargs need 'opcSetType' for the FFI support:
let fntyp = skipTypes(n[0].typ, abstractInst)
for i in 0..<n.len:
var r: TRegister = x+i
if i >= fntyp.signatureLen:
c.gen(n[i], r, {gfIsParam})
internalAssert c.config, tfVarargs in fntyp.flags
c.gABx(n, opcSetType, r, c.genType(n[i].typ))
else:
if fntyp[i] != nil and fntyp[i].kind == tySink and
fntyp[i].skipTypes({tySink}).kind in {tyObject, tyString, tySequence}:
c.gen(n[i], r, {gfIsSinkParam})
else:
c.gen(n[i], r, {gfIsParam})
if dest < 0:
c.gABC(n, opcIndCall, 0, x, n.len)
else:
c.gABC(n, opcIndCallAsgn, dest, x, n.len)
c.freeTempRange(x, n.len)
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 needsAsgnPatch(n: PNode): bool =
n.kind in {nkBracketExpr, nkDotExpr, nkCheckedFieldExpr,
nkDerefExpr, nkHiddenDeref} or (n.kind == nkSym and n.sym.isGlobal)
proc genField(c: PCtx; n: PNode): TRegister =
if n.kind != nkSym or n.sym.kind != skField:
globalError(c.config, n.info, "no field symbol")
let s = n.sym
if s.position > high(typeof(result)):
globalError(c.config, n.info,
"too large offset! cannot generate code for: " & s.name.s)
result = s.position
proc genIndex(c: PCtx; n: PNode; arr: PType): TRegister =
if arr.skipTypes(abstractInst).kind == tyArray and (let x = firstOrd(c.config, arr);
x != Zero):
let tmp = c.genx(n)
# freeing the temporary here means we can produce: regA = regA - Imm
c.freeTemp(tmp)
result = c.getTemp(n.typ)
c.gABI(n, opcSubImmInt, result, tmp, toInt(x))
else:
result = c.genx(n)
proc genCheckedObjAccessAux(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags)
proc genAsgnPatch(c: PCtx; le: PNode, value: TRegister) =
case le.kind
of nkBracketExpr:
let
dest = c.genx(le[0], {gfNode})
idx = c.genIndex(le[1], le[0].typ)
collTyp = le[0].typ.skipTypes(abstractVarRange-{tyTypeDesc})
case collTyp.kind
of tyString, tyCstring:
c.gABC(le, opcWrStrIdx, dest, idx, value)
of tyTuple:
c.gABC(le, opcWrObj, dest, int le[1].intVal, value)
else:
c.gABC(le, opcWrArr, dest, idx, value)
c.freeTemp(dest)
c.freeTemp(idx)
of nkCheckedFieldExpr:
var objR: TDest = -1
genCheckedObjAccessAux(c, le, objR, {gfNode})
let idx = genField(c, le[0][1])
c.gABC(le[0], opcWrObj, objR, idx, value)
c.freeTemp(objR)
of nkDotExpr:
let dest = c.genx(le[0], {gfNode})
let idx = genField(c, le[1])
c.gABC(le, opcWrObj, dest, idx, value)
c.freeTemp(dest)
of nkDerefExpr, nkHiddenDeref:
let dest = c.genx(le[0], {gfNode})
c.gABC(le, opcWrDeref, dest, 0, value)
c.freeTemp(dest)
of nkSym:
if le.sym.isGlobal:
let dest = c.genx(le, {gfNodeAddr})
c.gABC(le, opcWrDeref, dest, 0, value)
c.freeTemp(dest)
of nkHiddenStdConv, nkHiddenSubConv, nkConv:
if sameBackendType(le.typ, le[1].typ):
genAsgnPatch(c, le[1], value)
else:
discard
proc genNew(c: PCtx; n: PNode) =
let dest = if needsAsgnPatch(n[1]): c.getTemp(n[1].typ)
else: c.genx(n[1])
# we use the ref's base type here as the VM conflates 'ref object'
# and 'object' since internally we already have a pointer.
c.gABx(n, opcNew, dest,
c.genType(n[1].typ.skipTypes(abstractVar-{tyTypeDesc})[0]))
c.genAsgnPatch(n[1], dest)
c.freeTemp(dest)
proc genNewSeq(c: PCtx; n: PNode) =
let t = n[1].typ
let dest = if needsAsgnPatch(n[1]): c.getTemp(t)
else: c.genx(n[1])
let tmp = c.genx(n[2])
c.gABx(n, opcNewSeq, dest, c.genType(t.skipTypes(
abstractVar-{tyTypeDesc})))
c.gABx(n, opcNewSeq, tmp, 0)
c.freeTemp(tmp)
c.genAsgnPatch(n[1], dest)
c.freeTemp(dest)
proc genNewSeqOfCap(c: PCtx; n: PNode; dest: var TDest) =
let t = n.typ
if dest < 0:
dest = c.getTemp(n.typ)
let tmp = c.getTemp(n[1].typ)
c.gABx(n, opcLdNull, dest, c.genType(t))
c.gABx(n, opcLdImmInt, tmp, 0)
c.gABx(n, opcNewSeq, dest, c.genType(t.skipTypes(
abstractVar-{tyTypeDesc})))
c.gABx(n, opcNewSeq, tmp, 0)
c.freeTemp(tmp)
proc genUnaryABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n.typ)
c.gABC(n, opc, dest, tmp)
c.freeTemp(tmp)
proc genUnaryABI(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode; imm: BiggestInt=0) =
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n.typ)
c.gABI(n, opc, dest, tmp, imm)
c.freeTemp(tmp)
proc genBinaryABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
let
tmp = c.genx(n[1])
tmp2 = c.genx(n[2])
if dest < 0: dest = c.getTemp(n.typ)
c.gABC(n, opc, dest, tmp, tmp2)
c.freeTemp(tmp)
c.freeTemp(tmp2)
proc genBinaryABCD(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
let
tmp = c.genx(n[1])
tmp2 = c.genx(n[2])
tmp3 = c.genx(n[3])
if dest < 0: dest = c.getTemp(n.typ)
c.gABC(n, opc, dest, tmp, tmp2)
c.gABC(n, opc, tmp3)
c.freeTemp(tmp)
c.freeTemp(tmp2)
c.freeTemp(tmp3)
template sizeOfLikeMsg(name): string =
"'$1' requires '.importc' types to be '.completeStruct'" % [name]
proc genNarrow(c: PCtx; n: PNode; dest: TDest) =
let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
# uint is uint64 in the VM, we we only need to mask the result for
# other unsigned types:
let size = getSize(c.config, t)
if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
c.gABC(n, opcNarrowU, dest, TRegister(size*8))
elif t.kind in {tyInt8..tyInt32} or (t.kind == tyInt and size < 8):
c.gABC(n, opcNarrowS, dest, TRegister(size*8))
proc genNarrowU(c: PCtx; n: PNode; dest: TDest) =
let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
# uint is uint64 in the VM, we we only need to mask the result for
# other unsigned types:
let size = getSize(c.config, t)
if t.kind in {tyUInt8..tyUInt32, tyInt8..tyInt32} or
(t.kind in {tyUInt, tyInt} and size < 8):
c.gABC(n, opcNarrowU, dest, TRegister(size*8))
proc genBinaryABCnarrow(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
genBinaryABC(c, n, dest, opc)
genNarrow(c, n, dest)
proc genBinaryABCnarrowU(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
genBinaryABC(c, n, dest, opc)
genNarrowU(c, n, dest)
proc genSetType(c: PCtx; n: PNode; dest: TRegister) =
let t = skipTypes(n.typ, abstractInst-{tyTypeDesc})
if t.kind == tySet:
c.gABx(n, opcSetType, dest, c.genType(t))
proc genBinarySet(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
let
tmp = c.genx(n[1])
tmp2 = c.genx(n[2])
if dest < 0: dest = c.getTemp(n.typ)
c.genSetType(n[1], tmp)
c.genSetType(n[2], tmp2)
c.gABC(n, opc, dest, tmp, tmp2)
c.freeTemp(tmp)
c.freeTemp(tmp2)
proc genBinaryStmt(c: PCtx; n: PNode; opc: TOpcode) =
let
dest = c.genx(n[1])
tmp = c.genx(n[2])
c.gABC(n, opc, dest, tmp, 0)
c.freeTemp(tmp)
c.freeTemp(dest)
proc genBinaryStmtVar(c: PCtx; n: PNode; opc: TOpcode) =
var x = n[1]
if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
let
dest = c.genx(x)
tmp = c.genx(n[2])
c.gABC(n, opc, dest, tmp, 0)
#c.genAsgnPatch(n[1], dest)
c.freeTemp(tmp)
c.freeTemp(dest)
proc genUnaryStmt(c: PCtx; n: PNode; opc: TOpcode) =
let tmp = c.genx(n[1])
c.gABC(n, opc, tmp, 0, 0)
c.freeTemp(tmp)
proc genVarargsABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
if dest < 0: dest = getTemp(c, n.typ)
var x = c.getTempRange(n.len-1, slotTempStr)
for i in 1..<n.len:
var r: TRegister = x+i-1
c.gen(n[i], r)
c.gABC(n, opc, dest, x, n.len-1)
c.freeTempRange(x, n.len-1)
proc isInt8Lit(n: PNode): bool =
if n.kind in {nkCharLit..nkUInt64Lit}:
result = n.intVal >= low(int8) and n.intVal <= high(int8)
else:
result = false
proc isInt16Lit(n: PNode): bool =
if n.kind in {nkCharLit..nkUInt64Lit}:
result = n.intVal >= low(int16) and n.intVal <= high(int16)
else:
result = false
proc genAddSubInt(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
if n[2].isInt8Lit:
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n.typ)
c.gABI(n, succ(opc), dest, tmp, n[2].intVal)
c.freeTemp(tmp)
else:
genBinaryABC(c, n, dest, opc)
c.genNarrow(n, dest)
proc genConv(c: PCtx; n, arg: PNode; dest: var TDest, flags: TGenFlags = {}; opc=opcConv) =
let t2 = n.typ.skipTypes({tyDistinct})
let targ2 = arg.typ.skipTypes({tyDistinct})
proc implicitConv(): bool =
if sameBackendType(t2, targ2): return true
# xxx consider whether to use t2 and targ2 here
if n.typ.kind == arg.typ.kind and arg.typ.kind == tyProc:
# don't do anything for lambda lifting conversions:
result = true
else:
result = false
if implicitConv():
gen(c, arg, dest, flags)
return
let tmp = c.genx(arg)
if dest < 0: dest = c.getTemp(n.typ)
c.gABC(n, opc, dest, tmp)
c.gABx(n, opc, 0, genType(c, n.typ.skipTypes({tyStatic})))
c.gABx(n, opc, 0, genType(c, arg.typ.skipTypes({tyStatic})))
c.freeTemp(tmp)
proc genCard(c: PCtx; n: PNode; dest: var TDest) =
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n.typ)
c.genSetType(n[1], tmp)
c.gABC(n, opcCard, dest, tmp)
c.freeTemp(tmp)
proc genCastIntFloat(c: PCtx; n: PNode; dest: var TDest) =
template isSigned(typ: PType): bool {.dirty.} =
typ.kind == tyEnum and firstOrd(c.config, typ) < 0 or
typ.kind in {tyInt..tyInt64}
template isUnsigned(typ: PType): bool {.dirty.} =
typ.kind == tyEnum and firstOrd(c.config, typ) >= 0 or
typ.kind in {tyUInt..tyUInt64, tyChar, tyBool}
const allowedIntegers = {tyInt..tyInt64, tyUInt..tyUInt64, tyChar, tyEnum, tyBool}
let src = n[1].typ.skipTypes(abstractRange)#.kind
let dst = n[0].typ.skipTypes(abstractRange)#.kind
let srcSize = getSize(c.config, src)
let dstSize = getSize(c.config, dst)
const unsupportedCastDifferentSize =
"VM does not support 'cast' from $1 with size $2 to $3 with size $4 due to different sizes"
if src.kind in allowedIntegers and dst.kind in allowedIntegers:
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ)
c.gABC(n, opcAsgnInt, dest, tmp)
if dstSize != sizeof(BiggestInt): # don't do anything on biggest int types
if isSigned(dst): # we need to do sign extensions
if dstSize <= srcSize:
# Sign extension can be omitted when the size increases.
c.gABC(n, opcSignExtend, dest, TRegister(dstSize*8))
elif isUnsigned(dst):
if isSigned(src) or dstSize < srcSize:
# Cast from signed to unsigned always needs narrowing. Cast
# from unsigned to unsigned only needs narrowing when target
# is smaller than source.
c.gABC(n, opcNarrowU, dest, TRegister(dstSize*8))
c.freeTemp(tmp)
elif src.kind in allowedIntegers and
dst.kind in {tyFloat, tyFloat32, tyFloat64}:
if srcSize != dstSize:
globalError(c.config, n.info, unsupportedCastDifferentSize %
[$src.kind, $srcSize, $dst.kind, $dstSize])
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ)
if dst.kind == tyFloat32:
c.gABC(n, opcCastIntToFloat32, dest, tmp)
else:
c.gABC(n, opcCastIntToFloat64, dest, tmp)
c.freeTemp(tmp)
elif src.kind in {tyFloat, tyFloat32, tyFloat64} and
dst.kind in allowedIntegers:
if srcSize != dstSize:
globalError(c.config, n.info, unsupportedCastDifferentSize %
[$src.kind, $srcSize, $dst.kind, $dstSize])
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ)
if src.kind == tyFloat32:
c.gABC(n, opcCastFloatToInt32, dest, tmp)
if isUnsigned(dst):
# integers are sign extended by default.
# since there is no opcCastFloatToUInt32, narrowing should do the trick.
c.gABC(n, opcNarrowU, dest, TRegister(32))
else:
c.gABC(n, opcCastFloatToInt64, dest, tmp)
# narrowing for 64 bits not needed (no extended sign bits available).
c.freeTemp(tmp)
elif src.kind in PtrLikeKinds + {tyRef} and dst.kind == tyInt:
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ)
var imm: BiggestInt = if src.kind in PtrLikeKinds: 1 else: 2
c.gABI(n, opcCastPtrToInt, dest, tmp, imm)
c.freeTemp(tmp)
elif src.kind in PtrLikeKinds + {tyInt} and dst.kind in PtrLikeKinds:
let tmp = c.genx(n[1])
if dest < 0: dest = c.getTemp(n[0].typ)
c.gABx(n, opcSetType, dest, c.genType(dst))
c.gABC(n, opcCastIntToPtr, dest, tmp)
c.freeTemp(tmp)
elif src.kind == tyNil and dst.kind in NilableTypes:
# supports casting nil literals to NilableTypes in VM
# see #16024
if dest < 0: dest = c.getTemp(n[0].typ)
genLit(c, n[1], dest)
else:
# todo: support cast from tyInt to tyRef
globalError(c.config, n.info, "VM does not support 'cast' from " & $src.kind & " to " & $dst.kind)
proc genVoidABC(c: PCtx, n: PNode, dest: TDest, opcode: TOpcode) =
unused(c, n, dest)
var
tmp1 = c.genx(n[1])