Check-in [b287bafe45]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Update to current trunk
Timelines: family | ancestors | descendants | both | kbk-domain-check | notworking
Files: files | file ages | folders
SHA3-256:b287bafe455a9fd5afb6fce73c8065543979f6071c92e4f3e2c80d4ad3075030
User & Date: kbk 2018-03-20 01:18:13
Context
2018-03-20
04:54
Partial implementation of code gen for type checking on Boolean values check-in: 5032b57581 user: kbk tags: kbk-domain-check, notworking
01:18
Update to current trunk check-in: b287bafe45 user: kbk tags: kbk-domain-check, notworking
2018-03-15
22:09
Correct broken Markdown formatting in NRE notes check-in: 86584bbbc5 user: kbk tags: trunk
2016-12-30
01:00
Merge in initial code for IMPURE data. This branch now needs work to generate code for 'NUMERIC BOOLEAN' - representing an acceptable argument to [jumpTrue], [jumpFalse] and [not]. check-in: 784b0f7e6f user: kbk tags: kbk-domain-check
Changes

Added Dockerfile.

























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
FROM debian:9

ENV USER docker-build

ARG VCS_URL=https://core.tcl.tk/tclquadcode
LABEL org.label-schema.vcs-url=$VCS_URL \
	org.label-schema.docker.schema-version="1.0"

RUN apt-get update && \
	apt-get install -y git curl && \
	apt-get install -y libssl-dev && \
	apt-get install -y llvm llvm-dev llvm-runtime clang make && \
	apt-get install -y tcl8.6 tcl8.6-dev && \
	mkdir -p /tmp/build /tmp/build/llvmtcl /tmp/build/tclquadcode /tmp/build/tcllib /tmp/build/fossil && \
	git clone https://github.com/dkfellows/llvmtcl /tmp/build/llvmtcl && \
	cd /tmp/build/llvmtcl && ./configure --prefix=/usr --with-tcl=/usr/lib/tcl8.6 && make && make install && \
	cd /tmp/build/fossil && curl 'http://fossil-scm.org/index.html/uv/fossil-src-2.3.tar.gz' | gzip -dc | tar -xf - && \
	cd /tmp/build/fossil/* && ./configure && make && cp fossil /usr/bin && \
	fossil clone https://core.tcl.tk/tcllib /tmp/build/tcllib/.repo && \
	cd /tmp/build/tcllib && fossil open /tmp/build/tcllib/.repo tcllib-1-18 && ./configure --prefix=/usr && make && make install && \
	rm -rf /tmp/build && \
	mkdir -p /opt/tclquadcode && \
	fossil clone $VCS_URL /opt/tclquadcode/.repo && \
	cd /opt/tclquadcode && fossil open .repo && \
	apt-get remove -y curl git libssl-dev llvm llvm-dev llvm-runtime clang make tcl8.6-dev && \
	apt-get autoremove -y && \
	apt-get install -y ca-certificates binutils && \
	apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

Changes to codegen/build.tcl.

221
222
223
224
225
226
227










































































































































































































































































































































































































































































































































































































228
229
230
231
232
233
234
...
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
...
464
465
466
467
468
469
470














471
472
473
474
475
476
477
...
487
488
489
490
491
492
493

























































































































































































































































494
495
496
497
498
499
500
...
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
...
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
...
771
772
773
774
775
776
777










778
779
780
781
782
783
784
...
795
796
797
798
799
800
801



802
803
804
805
806
807
808
...
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
...
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
....
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
....
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
....
1259
1260
1261
1262
1263
1264
1265






















1266
1267
1268
1269
1270
1271
1272
....
1436
1437
1438
1439
1440
1441
1442



































































1443
1444
1445
1446
1447
1448
1449
....
1498
1499
1500
1501
1502
1503
1504
























































































































































































































































































































































1505
1506
1507
1508
1509
1510
1511
....
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
....
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
....
1705
1706
1707
1708
1709
1710
1711
1712
















1713
1714
1715
1716
1717
1718
1719
....
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
....
1788
1789
1790
1791
1792
1793
1794

























































































































































1795
1796
1797
1798
1799
1800
1801
....
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
....
2124
2125
2126
2127
2128
2129
2130











































































































































2131
2132
2133
2134
2135
2136
2137
....
2415
2416
2417
2418
2419
2420
2421




































































2422
2423
2424
2425
2426
2427
2428
....
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
....
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509


















2510
2511
2512
2513
2514
2515
2516
....
2659
2660
2661
2662
2663
2664
2665



2666
2667
2668



























2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
....
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
....
3417
3418
3419
3420
3421
3422
3423
































































3424
3425
3426
3427
3428
3429
3430
....
3436
3437
3438
3439
3440
3441
3442






















































3443
3444
3445
3446
3447
3448
3449
....
3455
3456
3457
3458
3459
3460
3461















3462
3463
3464


3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491

3492
3493
3494
3495
3496
3497
3498
....
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542





3543
3544
3545
3546
3547
3548
3549
....
3932
3933
3934
3935
3936
3937
3938
3939





















































3940
3941
3942
3943
3944
3945
3946


3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964

3965
3966
3967
3968
3969
3970
3971
3972
3973
3974






















3975
3976
3977
3978
3979
3980
3981
....
3995
3996
3997
3998
3999
4000
4001


































4002
4003
4004
4005
4006

4007
4008
4009
4010
4011
4012
4013
4014
4015
4016



































































4017


















4018
4019
4020
4021
4022

4023
4024
4025
4026
4027
4028
4029
4030

4031
4032
4033
4034
4035
4036
4037
....
4044
4045
4046
4047
4048
4049
4050















































































4051
4052
4053
4054
4055
4056
4057
....
4062
4063
4064
4065
4066
4067
4068


















4069
4070
4071
4072
4073
4074
4075
....
4080
4081
4082
4083
4084
4085
4086


















4087
4088
4089
4090
4091
4092
4093
....
4098
4099
4100
4101
4102
4103
4104


















4105
4106
4107
4108
4109
4110
4111
....
4121
4122
4123
4124
4125
4126
4127

4128
4129
4130
4131
4132
4133
4134



4135
4136
4137
4138
4139
4140
4141
....
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
....
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
....
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
....
4744
4745
4746
4747
4748
4749
4750
4751

4752














































































































































































































4753
4754
4755
4756

4757
    # Results:
    #	A boolean (int1) LLVM value reference.

    method in32range {int {name ""}} {
	my and [my ge $int [Const -0x80000000 int64]] \
	    [my le $int [Const 0x7fffffff int64]] $name
    }










































































































































































































































































































































































































































































































































































































 
    # Builder:add(INT,INT) --
    #
    #	Generate code to add two INTs. Quadcode implementation ('add').
    #
    # Parameters:
    #	left -	The INT LLVM value reference for the left operand.
................................................................................
    #	None.

    method addReference(EMPTY) {value} {
	my Call tcl.addReference $value
	return
    }

    # Builder:addReference(ZEROONE BOOLEAN) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The ZEROONE BOOLEAN LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(ZEROONE\040BOOLEAN) {value} {
	my Call tcl.addReference [my extract $value BOOLWORD.word]
	return
    }

    # Builder:addReference(NEXIST STRING) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(NEXIST\040STRING) {value} {
	my Call tcl.addMaybeReference $value
	return
    }

    # Builder:addReference(FAIL STRING) --
    #
    #	Generate code to increment the reference count of a value.
    #
................................................................................
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(FAIL\040STRING) {value} {
	my Call tcl.addMaybeReference $value
	return
    }

    # Builder:addReference(NEXIST EMPTY) --
    #
    #	Generate code to increment the reference count of a value.
    #
................................................................................
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(NEXIST\040EMPTY) {value} {
	my Call tcl.addMaybeReference $value
	return
    }

    # Builder:addReference(FAIL EMPTY) --
    #
    #	Generate code to increment the reference count of a value.
    #
................................................................................
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(FAIL\040EMPTY) {value} {
	my Call tcl.addMaybeReference $value
	return
    }

























































    # Builder:addReference(DICTITER) --
    #
    #	Generate code to increment the reference count of a DICTITER value.
    #
    # Parameters:
    #	value -	The DICTITER LLVM value reference for the operand.
................................................................................
    # Results:
    #	None.

    method addReference(DICTITER) {value} {
	my call ${tcl.dict.addIterReference} [list $value] ""
	return
    }















    # Builder:appendString --
    #
    #	Append a string value to a working buffer. The working buffer is
    #	assumed to be an UNSHARED Tcl_Obj reference; caller must ensure this,
    #	and the quadcode stream does not provide this guarantee. See also the
    #	unshare(STRING) and unshareCopy(STRING) methods.
................................................................................
    # Results:
    #	None.

    method appendString(STRING) {value buffer} {
	my Call tcl.append.string $buffer $value
	return
    }


























































































































































































































































    # Builder:assume --
    #
    #	Generate code to tell LLVM that a particular boolean expression is
    #	true. Used to optimize reference count management, among other things.
    #
    # Parameters:
................................................................................
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The runtime state value, as an LLVM FOREACH FAIL value. This will have
    #	the name "pair" associated with it.

    method unshareList {list {name ""}} {
	my call ${tcl.list.unshare} [list $list] $name
    }

    # Builder:foreachIter --
    #
    #	Get the iteration number from a FOREACH state. Quadcode implementation
    #	('foreachIter').
................................................................................
    method foreachMayStep {pair {name ""}} {
	my call ${tcl.list.foreach.mayStep} [list $pair] $name
    }

    # Builder:IsVectorItemConstant --
    #
    #	Determine if an element of a vector is a constant STRING and so does
    #	not need to have its reference count managed, either during
    #	construction or destruction of the vector.
    #
    # Parameters:
    #   value -	The tclquadcode value being considered.
    #	type -	The tclquadcode type of the value.
    #
    # Results:
    #	Tcl boolean.
................................................................................

    method ExtractVector {vector {lenVar len} {aryVar ary}} {
	upvar 1 $lenVar len $aryVar ary
	set len [my extract $vector 0]
	set ary [my cast(ptr) [my extract $vector 1] STRING]
	return
    }











    # Builder:Call --
    #
    #	Generate code to call a function. Note that the function might be an
    #	inlining candidate, and might be a candidate for being tail-called.
    #	This is a wrapper round the Builder:call method to make it easier to
    #	use in the common case where no name is given to the result.
................................................................................
    # Results:
    #	An LLVM value reference if the function returns anything. The type
    #	depends on what the function returns.

    method Call {function args} {
	if {![string match LLVMValueRef* $function]} {
	    upvar 1 $function var



	    set function $var
	}
	my call $function $args ""
    }

    # Builder:cast(BOOLEAN) --
    #
................................................................................

    method cast(INT?) {value {name ""}} {
	if {[TypeOf $value] eq [Type int32]} {
	    set packer packInt32
	} else {
	    set packer packInt64
	}
	my just [my $packer $value] $name
    }

    # Builder:cast(NUMERIC?) --
    #
    #	Generate code to cast an INT, DOUBLE, INT? or DOUBLE? to a NUMERIC?.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A NUMERIC FAIL LLVM value reference.

    method cast(NUMERIC?) {value {name ""}} {
	set t [TypeOf $value]
	if {$t eq [Type DOUBLE]} {
	    return [my just [my packNumericDouble $value]]
	} elseif {$t eq [Type INT]} {
	    return [my just [my packNumericInt $value]]
	} elseif {$t eq [Type DOUBLE?]} {
	    set packer packNumericDouble
	} else {
	    set packer packNumericInt
	}
	my select [my maybe $value] [my nothing NUMERIC] \
		[my just [my $packer [my unmaybe $value]]] $name
    }

    # Builder:cast(bool) --
    #
    #	Generate code to cast an INT to an int1.
    #
    # Parameters:
................................................................................
    # Results:
    #	An int32 LLVM value reference.

    method cast(uint) {value {name ""}} {
	my castUInt2Int $value int $name
    }

    # Builder:checkArithDomain.DOUBLE(STRING) --
    #
    #	Generate code to check if the given STRING contains something that can
    #	be parsed to get a DOUBLE, and set up an exception to throw if it is
    #	not. Quadcode implementation ('checkArithDomain').
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to check.
    #	msg -	The exception message. Expected to be a Const STRING.
    #	exn -	The exception code. Expected to be a Const STRING.
    #	ec -	Memory location to write the Tcl error code if an exception is
    #		generated.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An int1 LLVM value reference.

    method checkArithDomain.DOUBLE(STRING) {value msg exn ec {name ""}} {
	my call ${tcl.checkDouble} [list $value $msg $exn $ec] $name
    }

    # Builder:checkArithDomain.INT(STRING) --
    #
    #	Generate code to check if the given STRING contains something that can
    #	be parsed to get an INT, and set up an exception to throw if it is
    #	not. Quadcode implementation ('checkArithDomain').
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to check.
    #	msg -	The exception message. Expected to be a Const STRING.
    #	exn -	The exception code. Expected to be a Const STRING.
    #	ec -	Memory location to write the Tcl error code if an exception is
    #		generated.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An int1 LLVM value reference.

    method checkArithDomain.INT(STRING) {value msg exn ec {name ""}} {
	my call ${tcl.checkInteger} [list $value $msg $exn $ec] $name
    }
    method {checkArithDomain.IMPURE INT(STRING)} {value msg exn ec {name ""}} {
	my call ${tcl.checkInteger} [list $value $msg $exn $ec] $name
    }

    # Builder:checkArithDomain.NUMERIC(STRING) --
    #
    #	Generate code to check if the given STRING contains something that can
    #	be parsed to get a NUMERIC, and set up an exception to throw if it is
    #	not. Quadcode implementation ('checkArithDomain').
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to check.
    #	msg -	The exception message. Expected to be a Const STRING.
    #	exn -	The exception code. Expected to be a Const STRING.
    #	ec -	Memory location to write the Tcl error code if an exception is
    #		generated.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An int1 LLVM value reference.

    method checkArithDomain.NUMERIC(STRING) {value msg exn ec {name ""}} {
	my call ${tcl.checkNumeric} [list $value $msg $exn $ec] $name
    }
    method {checkArithDomain.IMPURE NUMERIC(STRING)} {value msg exn ec 
						      {name ""}} {
	my call ${tcl.checkNumeric} [list $value $msg $exn $ec] $name
    }

    # Builder:clearVector --
    #
    #	Clean up a vector value created with buildVector.
    #
    # Parameters:
    #	srcs -	The quadcode values that the vector elements were built from.
    #		Used to detect direct literal STRINGs, which don't need
................................................................................
    #	None.

    method clearVector {srcs vector types} {
	set idx -1
	set ary [my extract $vector 1]
	set stack [my extract $vector 2]
	foreach src $srcs t $types {
	    set s [my gep $ary 0 [incr idx]]
	    if {![my IsVectorItemConstant $src $t]} {
		my dropReference [my load $s]
	    }
	}
	my Call [$m intrinsic stackrestore] $stack
	return
    }

    # Builder:concat() --
    #
................................................................................
    #
    # Results:
    #	The retrieved value as an LLVM value reference, or a FAIL.

    method dictGet(STRING,STRING) {dict key ec {name ""}} {
	my call ${tcl.dict.get1} [list $dict $key $ec] $name
    }























    # Builder:dictIncr(STRING,STRING,INT) --
    #
    #	Increment the value for a key in a dictionary. NOTE: this operation
    #	can fail (e.g., because it can be given an invalid dictionary) so it
    #	produces a STRING FAIL. Quadcode implementation ('dictIncr').
    #
................................................................................
    #
    # Results:
    #	The new dictionary value.

    method dictSet(STRING,STRING,STRING) {dict key value ec {name ""}} {
	my call ${tcl.dict.set1} [list $dict $key $value $ec] $name
    }




































































    # Builder:dictSize(STRING) --
    #
    #	Get the size of a dictionary, i.e., the number of key-value pairs.
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to a dict to get the size of.
................................................................................
    #
    # Results:
    #	The new dictionary value.

    method dictUnset(STRING,STRING) {dict key ec {name ""}} {
	my call ${tcl.dict.unset1} [list $dict $key $ec] $name
    }

























































































































































































































































































































































    # Builder:div(INT,INT) --
    #
    #	Generate code to divide two INTs. Quadcode implementation ('div').
    #
    # Parameters:
    #	left -	The INT LLVM value reference for the left operand.
................................................................................
    #	None.

    method dropReference(STRING) {value} {
	my Call tcl.dropReference $value
	return
    }

    # Builder:dropReference(STRING FAIL) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The STRING FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(STRING\040FAIL) {value} {
	my Call tcl.dropMaybeReference $value
	return
    }

    # Builder:dropReference(FAIL STRING) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Parameters:
    #	value -	The STRING FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040STRING) {value} {
	my Call tcl.dropMaybeReference $value
	return
    }

    # Builder:dropReference(NEXIST STRING) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Parameters:
    #	value -	The NEXIST STRING LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040STRING) {value} {
	my Call tcl.dropMaybeReference $value
















	return
    }

    # Builder:dropReference(NEXIST EMPTY) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Parameters:
    #	value -	The NEXIST EMPTY LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040EMPTY) {value} {
	my Call tcl.dropMaybeReference $value
	return
    }

    # Builder:dropReference(ZEROONE BOOLEAN) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The ZEROONE BOOLEAN LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(ZEROONE\040BOOLEAN) {value} {
	my Call tcl.dropReference [my extract $value BOOLWORD.word]
	return
    }

    # Builder:dropReference(DICTITER) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Results:
    #	None.

    method dropReference(FAIL\040DICTITER) {value} {
	my Call tcl.dict.dropIterFailReference $value
	return
    }


























































































































































    # Builder:eq --
    #
    #	Generate code to compare two integers of the same bit width *or* two
    #	pointers for equality.
    #
    # Parameters:
................................................................................
    # Results:
    #	A ZEROONE LLVM value reference.

    method exists {value {name ""}} {
	my not [my maybe $value] $name
    }

    # Builder:existsOrError --
    #
    #	Test if a possibly-nonexisting value (something with NEXIST as part of
    #	its type) is actually an existing value, and generate an error message
    #	if it does not. Quadcode implementation ('throwIfNotExists').
    #
    # Parameters:
    #	value -	The *NEXISTS LLVM value reference for the operand.
    #	message -
    #		The error message (LLVM STRING, literal) to use when the value
    #		does not exist.
    #	exception -
    #		The -errorcode (LLVM STRING, literal) to use when the value
    #		does not exist.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An int1 LLVM value reference.

    method existsOrError {value message exception ec {name ""}} {
	my call ${tcl.existsOrError} \
	    [list [my maybe $value] $message $exception $ec] \
	    $name
    }

    # Builder:expect --
    #
    #	Issue the expectation that a condition will be true or false. This
    #	affects the weights in the LLVM metadata, and guides the low-level
    #	code issuing.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A NUMERIC? LLVM value reference.

    method expon(NUMERIC,NUMERIC) {left right ec {name ""}} {
	my call ${tcl.pow.numeric} [list $left $right $ec] $name
    }












































































































































    # Builder:ge --
    #
    #	Generate code to compare two integers of the same bit width *or* two
    #	pointers to see if the first is greater or equal to the second.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A ZEROONE LLVM value reference.

    method gt(STRING,STRING) {left right {name ""}} {
	my gt [my Call tcl.cmp.strstr $left $right] [Const 0] $name
    }





































































    # Builder:initException --
    #
    #	Generate/set up an exception.
    #
    # Parameters:
    #	errorcode -
................................................................................
	} else {
	    set stringed [my stringify($type) $value]
	    set code [my Call tcl.initExceptionOptions $stringed $dict]
	    # FIXME?
	    # my dropReference $stringed
	}
	my store $code $errVar
	my select [my eq $code [Const 0]] \
	    [my just $value] [my nothing $type] $name
    }

    # Builder:initException(STRING,INT,INT) --
    #
    #	Generate/set up an exception, returning a FAIL derived from the
    #	'value' argument. Quadcode implementation ('initException').
    #
................................................................................
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference.

    method initException(STRING,INT,INT) {dict code level value type errVar {name ""}} {
	if {$type eq "STRING"} {
	    set newcode [my Call tcl.processReturn \
		$value [my getInt32 $code] [my getInt32 $level] $dict]
	} else {
	    set stringed [my stringify($type) $value]
	    set newcode [my Call tcl.processReturn \
		$stringed [my getInt32 $code] [my getInt32 $level] $dict]
	    # FIXME?
	    my dropReference $stringed
	}
	SetValueName $newcode "code"
	my store $newcode $errVar
	my select [my eq $newcode [Const 0]] \
	    [my just $value] [my nothing $type] $name


















    }

    # Builder:instanceOf.DOUBLE(STRING) --
    #
    #	Generate code to check if the given STRING contains something that can
    #	be parsed to get a DOUBLE. Quadcode implementation ('instanceOf').
    #
................................................................................
    #	Generate code to call a Tcl command.  Quadcode implementation
    #	('invoke').
    #
    # Parameters:
    #	arguments -
    #		The arguments as an LLVM vector value reference. Note that
    #		this includes the function name as the first argument.



    #	ec -	Location to write the Tcl return code into, as an LLVM int*
    #		reference. (TODO: Not yet used because we give the wrong type
    #		to command signatures.)



























    #	resultName (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference.

    method invoke {arguments ec {resultName ""}} {
	my ExtractVector $arguments
	my call ${tcl.invoke.command} [list $len $ary $ec] $resultName
    }

    # Builder:isBoolean(INT BOOLEAN) --
    #
    #	Test if a value is a boolean. Quadcode implementation ('isBoolean').
    #
    # Parameters:
................................................................................

    method lt(STRING,STRING) {left right {name ""}} {
	my lt [my Call tcl.cmp.strstr $left $right] [Const 0] $name
    }

    # Builder:just --
    #
    #	Package a value as a Just FAIL.
    #
    # Parameters:
    #	value -	The value to put inside the FAIL.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM FAIL value reference containing the other value.

    method just {value {name ""}} {
	my insert [my insert [my undef [TypeOf $value]?] \
		       [Const false bool] 0] $value 1 $name
    }

    # Builder:narrowToType.DOUBLE(STRING) --
    #
    #	Generate code to parse the given STRING and extract a DOUBLE. The
    #	STRING is already be known to contain a value of the right type (due
................................................................................
    #
    # Results:
    #	A DOUBLE LLVM value reference.

    method narrowToType.DOUBLE(STRING) {value {name ""}} {
	my call ${tcl.extractDouble} [list $value] $name
    }

































































    # Builder:narrowToType.INT(STRING) --
    #
    #	Generate code to parse the given STRING and extract an INT. The STRING
    #	is already be known to contain a value of the right type (due to
    #	higher-level quadcode constraints). Quadcode implementation
    #	('narrowToType').
................................................................................
    #
    # Results:
    #	An INT LLVM value reference.

    method narrowToType.INT(STRING) {value {name ""}} {
	my call ${tcl.extractInteger} [list $value] $name
    }























































    # Builder:narrowToType.NUMERIC(STRING) --
    #
    #	Generate code to parse the given STRING and extract a NUMERIC. The
    #	STRING is already be known to contain a value of the right type (due
    #	to higher-level quadcode constraints). Quadcode implementation
    #	('narrowToType').
................................................................................
    #
    # Results:
    #	A NUMERIC LLVM value reference.

    method narrowToType.NUMERIC(STRING) {value {name ""}} {
	my call ${tcl.extractNumeric} [list $value] $name
    }















    method narrowToType.IMPURE_NUMERIC(STRING) {value {name ""}} {
	my packImpure(NUMERIC) [my call ${tcl.extractNumeric} [list $value]] \
	    $name


    }

    # Builder:nothing --
    #
    #	Create a Nothing FAIL of the given type.
    #
    # Parameters:
    #	type -	The type of the FAIL.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM FAIL value reference containing nothing.

    method nothing {type {name ""}} {
	if {[string match "* FAIL" $type]} {
	    set type [string range $type 0 end-5]
	} elseif {[string match "FAIL *" $type]} {
	    set type [string range $type 5 end]
	}
	my insert [my undef $type?] [Const true bool] 0 $name
    }

    # Builder:unmaybe --
    #
    #	Get the value out of a FAIL. NOTE: The FAIL must be a Just or the
    #	result will be an 'undef'; test with the 'maybe' method first!

    #
    # Parameters:
    #	value -	The FAIL to get the value from.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
................................................................................
	set mapping [my @jumptable.constant $mapping]
	set notThere [Const $notThere int]
	my call ${tcl.maptoint} [list $value $mapping $notThere] $name
    }

    # Builder:maybe --
    #
    #	Test if the FAIL value is a Nothing.
    #
    # Parameters:
    #	type -	The FAIL to examine.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM int1 value reference that is true when the FAIL is a Nothing
    #	and false when the FAIL is a Just.

    method maybe {value {name ""}} {
	my extract $value 0 $name





    }

    # Builder:max --
    #
    #	Determines the maximum of two LLVM int[x] values.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A ZEROONE LLVM value reference.

    method not(ZEROONE) {value errVar {name ""}} {
	my not $value $name
    }






















































    # Builder:packImpure(NUMERIC) --
    #
    #	Convert a NUMERIC to an IMPURE NUMERIC
    #
    # Parameters:
    #	value - LLVM Value to pack into the 'impure' structure
    #	name - (Optional) name to assign to the result


    #
    # Results:
    #	Returns an LLVM IMPURE NUMERIC value

    method packImpure(NUMERIC) {value {name ""}} {
	set sval [my stringify(NUMERIC) $value]
	my addReference(STRING) $sval
	set ival [my undef [Type {IMPURE NUMERIC}]]
	return [my insert [my insert $ival $sval 0] $value 1 $name]
    }

    # Builder:packImpure(ZEROONE BOOLEAN) --
    #
    #	Convert a ZEROONE BOOLEAN to an IMPURE ZEROONE BOOLEAN
    #
    # Parameters:
    #	value - LLVM Value to pack into the 'impure' structure
    #	name - (Optional) name to assign to the result

    #
    # Results:
    #	Returns an LLVM IMPURE NUMERIC value

    method {packImpure(ZEROONE BOOLEAN)} {value {name ""}} {
	set sval [my stringify(NUMERIC) $value]
	my addReference(STRING) $sval
	set ival [my undef [Type {IMPURE NUMERIC}]]
	my {addReference(ZEROONE BOOLEAN)} $ival
	return [my insert [my insert $ival $sval 0] $value 1 $name]






















    }

    # Builder:regexp(INT,STRING,STRING) --
    #
    #	Match a string against a regular expression. NOTE: this operation can
    #	fail (e.g., because it can be given an invalid regexp) so it produces
    #	an INT FAIL. Quadcode implementation ('regexp').
................................................................................
    #	Whether any/how many matches occurred, as an LLVM ZEROONE FAIL
    #	reference.

    method regexp(INT,STRING,STRING) {opts regexpr value errVar {name ""}} {
	my call ${tcl.regexp} [list $opts $regexpr $value $errVar] $name
    }



































    # Builder:result() --
    #
    #	Get the Tcl result. Quadcode implementation ('result').
    #
    # Parameters:

    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method result() {{name ""}} {
	my call ${tcl.getresult} {} $name
    }




































































    # Builder:returnOptions(INT) --


















    #
    #	Get the Tcl exception dictionary. Quadcode implementation
    #	('returnOptions').
    #
    # Parameters:

    #	value -	The Tcl result code, as an LLVM INT value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method returnOptions(INT) {value {name ""}} {

	my call ${tcl.getreturnopts} [list $value] $name
    }

    # Builder:rshift(INT,INT) --
    #
    #	Generate code to shift an INT right (divide by powers of 2). Quadcode
    #	implementation ('rshift').
................................................................................
    #
    # Results:
    #	An INT LLVM value reference.

    method rshift(INT,INT) {left right {name ""}} {
	my call ${tcl.shr} [list $left $right] $name
    }
















































































    # Builder:stringify(DOUBLE) --
    #
    #	Generate a STRING representation of a DOUBLE. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
................................................................................
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(DOUBLE) {value {name ""}} {
	my call ${tcl.stringify.double} [list $value] $name
    }



















    # Builder:stringify(INT) --
    #
    #	Generate a STRING representation of an INT. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
................................................................................
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(INT) {value {name ""}} {
	my call ${tcl.stringify.int} [list $value] $name
    }



















    # Builder:stringify(NUMERIC) --
    #
    #	Generate a STRING representation of a NUMERIC. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
................................................................................
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(NUMERIC) {value {name ""}} {
	my call ${tcl.stringify.numeric} [list $value] $name
    }



















    # Builder:stringify(STRING) --
    #
    #	Do-nothing pass through.
    #
    # Parameters:
    #	value -	The INT LLVM value reference to convert.
................................................................................

    # Builder:stringifyImpure --
    #
    #	Extract the string value of an impure object
    #
    # Parameters:
    #	value - The LLVM value to convert

    #	name (optional) - A name to give the result value
    #
    # Results:
    #	The string value is extracted. No refcount management is performed.

    method stringifyImpure {value {name ""}} {
	set v [my extract $value 0 $name]



	return $v
    }

    # Builder:strcase(STRING,INT) --
    #
    #	Generate a STRING that is a copy of an input STRING with a case
    #	transformation applied to it; the case transformation is described by
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING FAIL LLVM value reference (never a nothing). This will have a
    #	non-zero reference count.

    method strindex(STRING,INT) {str idx ecvar {name ""}} {
	my just [my Call tcl.stridx $str $idx] $name
    }

    # Builder:strindex(STRING,STRING) --
    #
    #	Generate a STRING (of length 1) that describes the character in the
    #	input STRING located at the index given by the input STRING, or the
    #	empty STRING if that index does not indicate a character in the
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING FAIL LLVM value reference (never a nothing). This will have a
    #	non-zero reference count.

    method strrange(STRING,INT,INT) {str from to ecvar {name ""}} {
	my just [my Call tcl.strrange $str $from $to] $name
    }

    # Builder:strrange(STRING,STRING,STRING) --
    #
    #	Generate a STRING that describes the substring of the input STRING
    #	located from the index given by the input STRING 'from' to the index
    #	given by the input STRING 'to', or the empty STRING if those indices
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING FAIL LLVM value reference (never a nothing). This will have a
    #	non-zero reference count.

    method strreplace(STRING,INT,INT,STRING) {str from to substr ecvar {name ""}} {
	my just [my Call tcl.strreplace $str $from $to $substr] $name
    }

    # Builder:strreplace(STRING,STRING,STRING,STRING) --
    #
    #	Generate a STRING that is the input STRING 'str' with the substring
    #	from the index given by the input STRING 'from' to the index given by
    #	the input STRING 'to' replaced with the input STRING 'substr'. This is
................................................................................
    #
    # Results:
    #	A writable Tcl_Obj* in an LLVM value reference.

    method unshareCopy(STRING) {value {name ""}} {
	my call ${tcl.unshare.copy} [list $value] $name
    }
}

 














































































































































































































# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<











|







 







|







 







|







 







|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







|
|







 







>
>
>
>
>
>
>
>
>
>







 







>
>
>







 







|







 







|

|





|
|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
|
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|










|
|







 







|







 







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
|







 







|











|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>

<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|

|







 







|


|




|


|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
<
>
>




|


|




|


|
|
|
|

|




|
|
>







 







|


|








|
>
>
>
>
>







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|
<
>
>







|
<







|
|
>







|
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|




>






|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





>







|
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
|





|
>
>
>







 







|







 







|







 







|







 







|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>

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
...
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
....
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
....
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
....
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
....
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
....
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
....
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
....
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
....
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
....
1939
1940
1941
1942
1943
1944
1945









































































1946
1947
1948
1949
1950
1951
1952
....
1959
1960
1961
1962
1963
1964
1965


1966

1967
1968
1969
1970
1971
1972
1973
....
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
....
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
....
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
....
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
....
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
....
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
....
2997
2998
2999
3000
3001
3002
3003
3004
















3005
3006
3007
3008
3009
3010
3011
....
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
....
3337
3338
3339
3340
3341
3342
3343



























3344
3345
3346
3347
3348
3349
3350
....
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
....
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
....
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
....
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
....
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280


4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
....
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
....
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
....
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
....
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235

5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
....
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
....
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777

5778
5779
5780
5781
5782
5783
5784
5785
5786
5787

5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805


5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
....
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
....
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
....
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
....
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
....
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
....
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
....
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
....
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
....
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
....
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
    # Results:
    #	A boolean (int1) LLVM value reference.

    method in32range {int {name ""}} {
	my and [my ge $int [Const -0x80000000 int64]] \
	    [my le $int [Const 0x7fffffff int64]] $name
    }
 
    # Builder:fieldtostruct --
    #
    #	Given a pointer to a field in a structure and a specification of which
    #	type and field it is, return a pointer to the overall structure
    #	containing that field. Note that this does not require dereferencing
    #	the field pointer.
    #
    # Parameters:
    #	fieldPtr -
    #		The pointer LLVM value reference to the field.
    #	type -	The LLVM type of the structure.
    #	fieldname -
    #		The name of the field within the structure.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A pointer LLVM value reference to the structure.

    method fieldtostruct {fieldPtr type fieldname {name ""}} {
	set off [my neg [my offsetof $type $fieldname]]
	set ptr [my cast(ptr) $fieldPtr char]
	return [my cast(ptr) [my getelementptr $ptr $off] $type $name]
    }
 
    # Builder:arraystring.from.array --
    #
    #	Construct an ARRAYSTRING that contains an ARRAY.
    #
    # Parameters:
    #	array -	The ARRAY LLVM value reference to be put in the ARRAYSTRING.
    #
    # Results:
    #	An ARRAYSTRING LLVM value reference.

    method arraystring.from.array {array} {
	set as [my undef ARRAYSTRING]
	set as [my insert $as [Const 0 bool] ARRAYSTRING.kind]
	return [my insert $as $array ARRAYSTRING.array]
    }

    # Builder:arraystring.from.scalar --
    #
    #	Construct an ARRAYSTRING that contains a STRING.
    #
    # Parameters:
    #	scalar -
    #		The STRING LLVM value reference to be put in the ARRAYSTRING.
    #
    # Results:
    #	An ARRAYSTRING LLVM value reference.

    method arraystring.from.scalar {scalar} {
	set as [my undef ARRAYSTRING]
	set as [my insert $as [Const 1 bool] ARRAYSTRING.kind]
	return [my insert $as $scalar ARRAYSTRING.scalar]
    }

    # Builder:arraystring.is.array --
    #
    #	Report whether an ARRAYSTRING is wrapping an ARRAY.  If not, it
    #	contains a STRING scalar (and it never contains both).
    #
    # Parameters:
    #	as -	The ARRAYSTRING LLVM value reference to look at.
    #
    # Results:
    #	An int1 LLVM value reference.

    method arraystring.is.array {as} {
	return [my not [my extract $as ARRAYSTRING.kind]]
    }

    # Builder:arraystring.is.scalar --
    #
    #	Report whether an ARRAYSTRING is wrapping a STRING scalar. If not, it
    #	contains an ARRAY (and it never contains both).
    #
    # Parameters:
    #	as -	The ARRAYSTRING LLVM value reference to look at.
    #
    # Results:
    #	An int1 LLVM value reference.

    method arraystring.is.scalar {as} {
	return [my extract $as ARRAYSTRING.kind]
    }
 
    # Builder:frame.pack --
    #
    #	Combine a callframe with another value.
    #
    # Parameters:
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	value -	The INT LLVM value reference for the non-callframe value.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A CALLFRAME-value tuple LLVM value reference.

    method frame.pack {callframe value {name ""}} {
	set type [Type struct{CALLFRAME,[TypeOf $value]}]
	my insert [my insert [my undef $type] $callframe 0] $value 1 $name
    }

    # Builder:frame.frame --
    #
    #	Extract the callframe from a tupled value.
    #
    # Parameters:
    #	callframetuple -
    #		The CALLFRAME-tuple LLVM value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A CALLFRAME LLVM value reference.

    method frame.frame {callframetuple {name ""}} {
	my extract $callframetuple 0 $name
    }

    # Builder:frame.value --
    #
    #	Extract the non-callframe value from a tuple.
    #
    # Parameters:
    #	callframetuple -
    #		The CALLFRAME-tuple LLVM value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference.

    method frame.value {callframetuple {name ""}} {
	my extract $callframetuple 1 $name
    }
 
    # Builder:frame.args(INT) --
    #
    #	Extract the list of arguments from a callframe. Part of [info level].
    #
    # Parameters:
    #	depth -	An INT saying which frame to get the arguments from, with the
    #		value interpretation as used in [info frame].
    #	callframetuple -
    #		The CALLFRAME-tuple LLVM value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM FAIL STRING reference.

    method frame.args(INT) {depth callframe {name ""}} {
	my call ${tcl.callframe.getarglist} [list $callframe $depth] $name
    }

    # Builder:frame.depth --
    #
    #	Extract the call depth from a callframe. Part of [info level].
    #
    # Parameters:
    #	callframetuple -
    #		The CALLFRAME-tuple LLVM value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM INT reference.

    method frame.depth {callframe {name ""}} {
	my call ${tcl.callframe.depth} [list $callframe] $name
    }

    # Builder:frame.create --
    #
    #	Create and initialise a callframe.
    #
    # Parameters:
    #	varlist -
    #		The Tcl list of information about the callframe's variables
    #		extracted from the bytecode.
    #	argc -	The int LLVM value reference for the number of arguments.
    #	argv -	The STRING* LLVM value reference (or equivalent type) for the
    #		array of arguments, allocated on the function stack.
    #	proc -	The LLVM value reference to the procedure's metadata.
    #	localcache -
    #		The LLVM value reference to the procedure's local variable
    #		metadata.
    #
    # Results:
    #	A Tcl list of the LLVM CALLFRAME value reference and the mapping
    #	dictionary from string variable names to the corresponding LLVM Var*
    #	value references.

    method frame.create {varlist argc argv proc localcache} {
	# Construct the call frame itself
	set callframe [my alloc CallFrame "callframe"]
	set length [Const [llength $varlist]]
	set locals [my arrayAlloc Var $length]
	my Call tcl.callframe.init $callframe $length \
	    $argc [my cast(ptr) $argv STRING] $proc $localcache $locals
	# Initialise the information about the local variables
	set idx -1
	set varmap {}
	foreach varinfo $varlist {
	    lassign $varinfo flags var
	    set flagbits 0
	    set FLAGS {
		scalar 0x0 array 0x1 link 0x2
		arg 0x100 temp 0x200 args 0x400
		resolved 0x8000
	    }
	    foreach bit $flags {
		incr flagbits [dict get $FLAGS $bit]
	    }
	    set v [my Call tcl.callframe.makevar $callframe \
		       [Const [incr idx] int] [Const $flagbits int]]
	    dict set varmap $var $v
	}
	return [list $callframe $varmap]
    }

    # Builder:frame.release --
    #
    #	Delete the contents of a call frame.
    #
    # Parameters:
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	synthetics -
    #		A Tcl list of booleans saying which values in the callframe's
    #		argv array need to have their reference counts decremented
    #		because they are synthetic.
    #
    # Results:
    #	None.

    method frame.release {callframe synthetics} {
	set idx -1
	foreach drop $synthetics {
	    incr idx
	    if {$drop} {
		if {![info exist objv]} {
		    set objv [my dereference $callframe 0 CallFrame.objv]
		}
		set obj [my dereference $objv $idx]
		my dropReference(STRING) $obj
	    }
	}
	my Call tcl.callframe.clear $callframe
	return
    }

    # Builder:frame.store(NUMERIC) --
    #
    #	Transfer a value into a call frame variable.
    #
    # Parameters:
    #	value -	The LLVM value reference to go into the call frame's var.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to write to.
    #	varName -
    #		The Tcl string of the name of the variable.
    #
    # Results:
    #	None.

    method frame.store(NUMERIC) {value callframe var varName} {
	my frame.store(NEXIST\040NUMERIC) [my just $value] \
	    $callframe $var $varName
    }

    # Builder:frame.store(NEXIST NUMERIC) --
    #
    #	Transfer a value into a call frame variable.
    #
    # Parameters:
    #	value -	The LLVM value reference to go into the call frame's var.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to write to.
    #	varName -
    #		The Tcl string of the name of the variable.
    #
    # Results:
    #	None.

    method frame.store(NEXIST\040NUMERIC) {value callframe var varName} {
	my Call tcl.callframe.store.numeric $var [Const $varName STRING] $value
	return
    }

    # Builder:frame.store(STRING) --
    #
    #	Transfer a value into a call frame variable.
    #
    # Parameters:
    #	value -	The LLVM value reference to go into the call frame's var.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to write to.
    #	varName -
    #		The Tcl string of the name of the variable.
    #
    # Results:
    #	None.

    method frame.store(STRING) {value callframe var varName} {
	my frame.store(NEXIST\040STRING) [my just $value] \
	    $callframe $var $varName
    }

    # Builder:frame.store(NEXIST STRING) --
    #
    #	Transfer a value into a call frame variable. A non-existing value will
    #	convert into an unsetting of the variable.
    #
    # Parameters:
    #	value -	The LLVM value reference to go into the call frame's var.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to write to.
    #	varName -
    #		The Tcl string of the name of the variable.
    #
    # Results:
    #	None.

    method frame.store(NEXIST\040STRING) {value callframe var varName} {
	my Call tcl.callframe.store.string $var [Const $varName STRING] $value
	return
    }

    # Builder:frame.store(NEXIST) --
    #
    #	Unset a variable in a call frame.
    #
    # Parameters:
    #	value -	The non-existing value to put in the variable.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to unset.
    #	varName -
    #		The Tcl string of the name of the variable.
    #
    # Results:
    #	None.

    method frame.store(NEXIST) {value callframe var varName} {
	my frame.unset $callframe $var $varName
    }

    # Builder:frame.store(ARRAY) --
    #
    #	Generate code to store an ARRAY in a variable in the current
    #	callframe.  This makes the ARRAY become one that does not get
    #	deallocated immediately once its last reference count is dropped.
    #	Quadcode implementation ('moveToCallFrame').
    #
    # Parameters:
    #	value -	The ARRAY LLVM value to store.
    #	callframe -
    #		The callframe that contains the variable.
    #	var -	The variable in the callframe to store the ARRAY in.
    #	varName -
    #		The STRING name of the variable.
    #
    # Results:
    #	None.

    method frame.store(ARRAY) {value callframe var varName} {
	my frame.store(NEXIST\040ARRAY) [my just $value] \
	    $callframe $var $varName
    }

    # Builder:frame.store(NEXIST ARRAY) --
    #
    #	Generate code to store an ARRAY in a variable in the current callframe
    #	or to unset it.  This makes the ARRAY become one that does not get
    #	deallocated immediately once its last reference count is dropped.
    #	Quadcode implementation ('moveToCallFrame').
    #
    # Parameters:
    #	value -	The NEXIST ARRAY LLVM value to store.
    #	callframe -
    #		The callframe that contains the variable.
    #	var -	The variable in the callframe to store the ARRAY in.
    #	varName -
    #		The STRING name of the variable.
    #
    # Results:
    #	None.

    method frame.store(NEXIST\040ARRAY) {value callframe var varName} {
	my Call tcl.callframe.store.array $var [Const $varName STRING] $value
	return
    }

    # Builder:frame.store(ARRAY STRING) --
    #
    #	Generate code to store an ARRAY or STRING in a variable in the current
    #	callframe.  This makes the ARRAY (if present) become one that does not
    #	get deallocated immediately once its last reference count is dropped.
    #	Quadcode implementation ('moveToCallFrame').
    #
    # Parameters:
    #	value -	The ARRAY STRING LLVM value to store.
    #	callframe -
    #		The callframe that contains the variable.
    #	var -	The variable in the callframe to store the ARRAY/STRING in.
    #	varName -
    #		The STRING name of the variable.
    #
    # Results:
    #	None.

    method frame.store(ARRAY\040STRING) {value callframe var varName} {
	my frame.store(NEXIST\040ARRAY\040STRING) [my just $value] \
	    $callframe $var $varName
    }

    # Builder:frame.store(NEXIST ARRAY STRING) --
    #
    #	Generate code to store an ARRAY or STRING in a variable in the current
    #	callframe, or to unset it.  This makes the ARRAY (if present) become
    #	one that does not get deallocated immediately once its last reference
    #	count is dropped.  Quadcode implementation ('moveToCallFrame').
    #
    # Parameters:
    #	value -	The NEXIST ARRAY STRING LLVM value to store.
    #	callframe -
    #		The callframe that contains the variable.
    #	var -	The variable in the callframe to store the ARRAY/STRING in.
    #	varName -
    #		The STRING name of the variable.
    #
    # Results:
    #	None.

    method frame.store(NEXIST\040ARRAY\040STRING) {value callframe var varName} {
	my Call tcl.callframe.store.arraystring $var [Const $varName STRING] $value
	return
    }

    # Builder:frame.unset --
    #
    #	Unset a variable in a call frame.
    #
    # Parameters:
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to unset.
    #	varName -
    #		The Tcl string of the name of the variable.
    #
    # Results:
    #	None.

    method frame.unset {callframe var varName} {
	my frame.store(NEXIST\040STRING) [my nothing STRING] \
	    $callframe $var $varName
    }

    # Builder:frame.load --
    #
    #	Read a value from a variable in a call frame. Only variables in the
    #	call frame may be read with this method call.
    #
    # Parameters:
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	var -	The Var* LLVM reference for the variable to read.
    #	varName -
    #		The Tcl string of the name of the variable.
    #	name (optional) -
    #		The LLVM name of the result value.
    #
    # Results:
    #	An LLVM ARRAYSTRING! value reference.

    method frame.load {callframe var varName {name ""}} {
	my call ${tcl.callframe.load} [list $var [Const $varName STRING]] \
	    $name
    }

    # Builder:frame.bind.nsvar(STRING,STRING,STRING) --
    #
    #	Link a variable in the local call frame to a variable looked up in a
    #	given named namespace.
    #
    # Parameters:
    #	localName -
    #		An LLVM STRING reference to the local variable name.
    #	nsName -
    #		An LLVM STRING reference to the namespace name.
    #	otherName -
    #		An LLVM STRING reference to the name of the variable in the
    #		namespace to link to.
    #	localVar -
    #		An LLVM Var* reference to the local variable.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	ec -	An int* LLVM reference for where to write error codes into.
    #	name (optional) -
    #		The LLVM name of the result value.
    #
    # Results:
    #	An LLVM bool? value reference.

    method frame.bind.nsvar(STRING,STRING,STRING) {
	    localName nsName otherName localVar callframe ec {name ""}} {
	set otherVar [my call ${tcl.callframe.lookup.varns} [list \
		$callframe $nsName $otherName] "otherVar"]
	set val [my Call tcl.callframe.bindvar $callframe \
		     $otherVar $localVar $localName $ec]
	return [my frame.pack $callframe $val $name]
    }

    # Builder:frame.bind.var(STRING,STRING) --
    #
    #	Link a variable in the local call frame to a variable looked up with
    #	general respect to the call frame's context.
    #
    # Parameters:
    #	localName -
    #		An LLVM STRING reference to the local variable name.
    #	otherName -
    #		An LLVM STRING reference to the name of the variable to link
    #		to.
    #	localVar -
    #		An LLVM Var* reference to the local variable.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	ec -	An int* LLVM reference for where to write error codes into.
    #	name (optional) -
    #		The LLVM name of the result value.
    #
    # Results:
    #	An LLVM bool? value reference.

    method frame.bind.var(STRING,STRING) {
	    localName otherName localVar callframe ec {name ""}} {
	set otherVar [my call ${tcl.callframe.lookup.var} [list \
		$callframe $otherName] "otherVar"]
	set val [my call ${tcl.callframe.bindvar} [list \
		$callframe $otherVar $localVar $localName $ec] $name]
	return [my frame.pack $callframe $val $name]
    }

    # Builder:frame.bind.nsvar(STRING,STRING,STRING) --
    #
    #	Link a variable in the local call frame to a variable looked up in an
    #	indicated call frame.
    #
    # Parameters:
    #	localName -
    #		An LLVM STRING reference to the local variable name.
    #	level -	An LLVM STRING reference to the level descriptor.
    #	otherName -
    #		An LLVM STRING reference to the name of the variable in the
    #		namespace to link to.
    #	localVar -
    #		An LLVM Var* reference to the local variable.
    #	callframe -
    #		The CALLFRAME LLVM value reference.
    #	ec -	An int* LLVM reference for where to write error codes into.
    #	name (optional) -
    #		The LLVM name of the result value.
    #
    # Results:
    #	An LLVM bool? value reference.

    method frame.bind.upvar(STRING,STRING,STRING) {
	    localName level otherName localVar callframe ec {name ""}} {
	set otherVar [my call ${tcl.callframe.lookup.upvar} [list \
		$callframe $level $otherName] "otherVar"]
	set val [my call ${tcl.callframe.bindvar} [list \
		$callframe $otherVar $localVar $localName $ec] $name]
	return [my frame.pack $callframe $val $name]
    }
 
    # Builder:add(INT,INT) --
    #
    #	Generate code to add two INTs. Quadcode implementation ('add').
    #
    # Parameters:
    #	left -	The INT LLVM value reference for the left operand.
................................................................................
    #	None.

    method addReference(EMPTY) {value} {
	my Call tcl.addReference $value
	return
    }
















    # Builder:addReference(NEXIST STRING) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(NEXIST\040STRING) {value} {
	my Call tcl.addNExistReference $value
	return
    }

    # Builder:addReference(FAIL STRING) --
    #
    #	Generate code to increment the reference count of a value.
    #
................................................................................
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(FAIL\040STRING) {value} {
	my Call tcl.addFailReference $value
	return
    }

    # Builder:addReference(NEXIST EMPTY) --
    #
    #	Generate code to increment the reference count of a value.
    #
................................................................................
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(NEXIST\040EMPTY) {value} {
	my Call tcl.addNExistReference $value
	return
    }

    # Builder:addReference(FAIL EMPTY) --
    #
    #	Generate code to increment the reference count of a value.
    #
................................................................................
    # Parameters:
    #	value -	The STRING/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(FAIL\040EMPTY) {value} {
	my Call tcl.addFailReference $value
	return
    }

    # Builder:addReference(ARRAY) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The ARRAY LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(ARRAY) {value} {
	my Call tcl.array.addRef $value
    }

    # Builder:addReference(NEXIST ARRAY) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The ARRAY/etc. LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(NEXIST\040ARRAY) {value} {
	my Call tcl.array.addRef.nexist $value
    }

    # Builder:addReference(ARRAY STRING) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The ARRAYSTRING LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(ARRAY\040STRING) {value} {
	my Call tcl.arraystring.addRef $value
    }

    # Builder:addReference(NEXIST ARRAY STRING) --
    #
    #	Generate code to increment the reference count of a value.
    #
    # Parameters:
    #	value -	The ARRAYSTRING! LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(NEXIST\040ARRAY\040STRING) {value} {
	my Call tcl.arraystring.addRef.nexist $value
    }

    # Builder:addReference(DICTITER) --
    #
    #	Generate code to increment the reference count of a DICTITER value.
    #
    # Parameters:
    #	value -	The DICTITER LLVM value reference for the operand.
................................................................................
    # Results:
    #	None.

    method addReference(DICTITER) {value} {
	my call ${tcl.dict.addIterReference} [list $value] ""
	return
    }

    # Builder:addReference(FAIL DICTITER) --
    #
    #	Generate code to increment the reference count of a FAIL DICTITER value.
    #
    # Parameters:
    #	value -	The DICTITER LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method addReference(FAIL\040DICTITER) {value} {
	my Call tcl.dict.addIterFailReference $value
    }

    # Builder:appendString --
    #
    #	Append a string value to a working buffer. The working buffer is
    #	assumed to be an UNSHARED Tcl_Obj reference; caller must ensure this,
    #	and the quadcode stream does not provide this guarantee. See also the
    #	unshare(STRING) and unshareCopy(STRING) methods.
................................................................................
    # Results:
    #	None.

    method appendString(STRING) {value buffer} {
	my Call tcl.append.string $buffer $value
	return
    }

    # Builder:arrayExists(ARRAY STRING) --
    #
    #	Test if the value actually contains an ARRAY.  Quadcode implementation
    #	('arrayExists').
    #
    # Parameters:
    #	value -	The ARRAYSTRING LLVM value reference for the operand.
    #
    # Results:
    #	An int1 LLVM value reference.

    method arrayExists(ARRAY\040STRING) {value {name ""}} {
	my arraystring.is.array $value
    }

    # Builder:arrayExists(NEXIST ARRAY STRING) --
    #
    #	Test if the value actually contains an ARRAY.  Quadcode implementation
    #	('arrayExists').
    #
    # Parameters:
    #	value -	The ARRAYSTRING! LLVM value reference for the operand.
    #
    # Results:
    #	An int1 LLVM value reference.

    method arrayExists(NEXIST\040ARRAY\040STRING) {value {name ""}} {
	my call ${tcl.arraystring.isarray} [list $value]
    }

    # Builder:initArray --
    #
    #	Generate code to create a new ARRAY.  The ARRAY will not be initially
    #	associated with a callframe variable.  Quadcode implementation
    #	('initArray').
    #
    # Parameters:
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The ARRAY LLVM value reference.

    method initArray {{name ""}} {
	my call ${tcl.array.init} [list [my nothing ARRAY]] $name
    }

    # Builder:initArrayIfNotExists(NEXIST ARRAY STRING) --
    #
    #	Generate code to create a new ARRAY if the value was a NEXIST, and
    #	otherwise return the scalar STRING or existing ARRAY.  Any ARRAY
    #	created by this will not be initially associated with a callframe
    #	variable.  Quadcode implementation ('initArrayIfNotExists').
    #
    # Parameters:
    #	value -	The value to examine for NEXIST.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The ARRAY STRING LLVM value reference.

    method initArrayIfNotExists(NEXIST\040ARRAY\040STRING) {value {name ""}} {
	my call ${tcl.arraystring.init} [list $value] $name
    }

    # Builder:initArrayIfNotExists(NEXIST ARRAY) --
    #
    #	Generate code to create a new ARRAY if the value was a NEXIST, and
    #	otherwise return the existing ARRAY.  Any ARRAY created by this will
    #	not be initially associated with a callframe variable.  Quadcode
    #	implementation ('initArrayIfNotExists').
    #
    # Parameters:
    #	value -	The value to examine for NEXIST.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The ARRAY LLVM value reference.

    method initArrayIfNotExists(NEXIST\040ARRAY) {value {name ""}} {
	my call ${tcl.array.init} [list $value] $name
    }

    # Builder:arrayElementExists(ARRAY,STRING) --
    #
    #	Generate code to test if an element with a given STRING key exists in
    #	an ARRAY.  Quadcode implementation ('arrayElementExists').
    #
    # Parameters:
    #	ary -	The ARRAY to look inside.
    #	idx -	The STRING key to look for.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The int1 LLVM value reference.

    method arrayElementExists(ARRAY,STRING) {ary idx {name ""}} {
	my call ${tcl.array.elemexists} [list $ary $idx] $name
    }

    # Builder:arrayElementExists(ARRAY STRING,STRING) --
    #
    #	Generate code to test if an element with a given STRING key exists in
    #	an ARRAY STRING.  Note that STRINGs never contain any keys.  Quadcode
    #	implementation ('arrayElementExists').
    #
    # Parameters:
    #	ary -	The ARRAY to look inside.
    #	idx -	The STRING key to look for.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The int1 LLVM value reference.

    method arrayElementExists(ARRAY\040STRING,STRING) {ary idx {name ""}} {
	my call ${tcl.arraystring.elemexists} [list $ary $idx] $name
    }

    # Builder:arrayGet(ARRAY,STRING) --
    #
    #	Generate code to get the value of an element with a given STRING key
    #	in an ARRAY.  Produces an NEXIST if the element is absent.  Quadcode
    #	implementation ('arrayGet').
    #
    # Parameters:
    #	ary -	The ARRAY to look inside.
    #	idx -	The STRING key to look for.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The STRING! LLVM value reference.

    method arrayGet(ARRAY,STRING) {ary idx {name ""}} {
	my call ${tcl.array.get} [list $ary $idx] $name
    }

    # Builder:arraySet(ARRAY,STRING,STRING) --
    #
    #	Generate code to set the value of an element with a given STRING key
    #	in an ARRAY to the given value.  Produces the updated ARRAY.  Quadcode
    #	implementation ('arraySet').
    #
    # Parameters:
    #	ary -	The ARRAY to update.
    #	idx -	The STRING key to find or create the element with.
    #	value -	The STRING value to set the element's value to.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The ARRAY LLVM value reference.

    method arraySet(ARRAY,STRING,STRING) {ary idx value {name ""}} {
	my call ${tcl.array.set} [list $ary $idx $value] $name
    }

    # Builder:arrayUnset(ARRAY,STRING) --
    #
    #	Generate code to remove an element with a given STRING key from an
    #	ARRAY.  Produces the updated ARRAY.  Quadcode implementation
    #	('arrayUnset').
    #
    # Parameters:
    #	ary -	The ARRAY to update.
    #	idx -	The STRING key to find or create the element with.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The ARRAY LLVM value reference.

    method arrayUnset(ARRAY,STRING) {ary idx {name ""}} {
	my call ${tcl.array.unset} [list $ary $idx [Const $name STRING]] $name
    }

    # Builder:extractArray(NEXIST ARRAY STRING) --
    #
    #	Generate code to extract an NEXIST ARRAY from an NEXIST ARRAY STRING.
    #	The value must not contain a scalar STRING.  Quadcode implementation
    #	('extractArray').
    #
    # Parameters:
    #	value -	The value reference to get the ARRAY from.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The NEXIST ARRAY LLVM value reference.

    method extractArray(NEXIST\040ARRAY\040STRING) {value {name ""}} {
	my call ${tcl.arraystring.extractarray.nexist} [list $value] $name
    }

    # Builder:extractArray(ARRAY STRING) --
    #
    #	Generate code to extract an ARRAY from an ARRAY STRING. The value must
    #	not contain a scalar STRING. Quadcode implementation ('extractArray').
    #
    # Parameters:
    #	value -	The value reference to get the ARRAY from.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The ARRAY LLVM value reference.

    method extractArray(ARRAY\040STRING) {value {name ""}} {
	my call ${tcl.arraystring.extractarray} [list $value] $name
    }

    # Builder:extractScalar(NEXIST ARRAY STRING) --
    #
    #	Generate code to extract an NEXIST STRING from an NEXIST ARRAY STRING.
    #	Quadcode implementation ('extractScalar').
    #
    # Parameters:
    #	value -	The value reference to get the STRING from.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The NEXIST STRING LLVM value reference.

    method extractScalar(NEXIST\040ARRAY\040STRING) {value {name ""}} {
	my call ${tcl.arraystring.extractscalar.nexist} [list $value] $name
    }

    # Builder:extractScalar(ARRAY STRING) --
    #
    #	Generate code to extract a STRING from an ARRAY STRING.  Quadcode
    #	implementation ('extractScalar').
    #
    # Parameters:
    #	value -	The value reference to get the STRING from.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The STRING LLVM value reference.

    method extractScalar(ARRAY\040STRING) {value {name ""}} {
	my call ${tcl.arraystring.extractscalar} [list $value] $name
    }

    # Builder:assume --
    #
    #	Generate code to tell LLVM that a particular boolean expression is
    #	true. Used to optimize reference count management, among other things.
    #
    # Parameters:
................................................................................
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The runtime state value, as an LLVM FOREACH FAIL value. This will have
    #	the name "pair" associated with it.

    method unshareList(STRING) {list {name ""}} {
	my call ${tcl.list.unshare} [list $list] $name
    }

    # Builder:foreachIter --
    #
    #	Get the iteration number from a FOREACH state. Quadcode implementation
    #	('foreachIter').
................................................................................
    method foreachMayStep {pair {name ""}} {
	my call ${tcl.list.foreach.mayStep} [list $pair] $name
    }

    # Builder:IsVectorItemConstant --
    #
    #	Determine if an element of a vector is a constant STRING and so does
    #	not need to have its reference count managed during construction of
    #	the vector.
    #
    # Parameters:
    #   value -	The tclquadcode value being considered.
    #	type -	The tclquadcode type of the value.
    #
    # Results:
    #	Tcl boolean.
................................................................................

    method ExtractVector {vector {lenVar len} {aryVar ary}} {
	upvar 1 $lenVar len $aryVar ary
	set len [my extract $vector 0]
	set ary [my cast(ptr) [my extract $vector 1] STRING]
	return
    }

    method buildBitArray {booleans} {
	set type [Type array{bool,[llength $booleans]}]
	set bits [my alloc $type]
	set idx -1
	foreach bool $booleans {
	    my store [Const $bool bool] [my gep $bits 0 [incr idx]]
	}
	return [my cast(ptr) $bits bool]
    }

    # Builder:Call --
    #
    #	Generate code to call a function. Note that the function might be an
    #	inlining candidate, and might be a candidate for being tail-called.
    #	This is a wrapper round the Builder:call method to make it easier to
    #	use in the common case where no name is given to the result.
................................................................................
    # Results:
    #	An LLVM value reference if the function returns anything. The type
    #	depends on what the function returns.

    method Call {function args} {
	if {![string match LLVMValueRef* $function]} {
	    upvar 1 $function var
	    if {![info exist var]} {
		return -code error "no such visible function: $function"
	    }
	    set function $var
	}
	my call $function $args ""
    }

    # Builder:cast(BOOLEAN) --
    #
................................................................................

    method cast(INT?) {value {name ""}} {
	if {[TypeOf $value] eq [Type int32]} {
	    set packer packInt32
	} else {
	    set packer packInt64
	}
	my ok [my $packer $value] $name
    }

    # Builder:cast(NUMERIC?) --
    #
    #	Generate code to cast an INT, DOUBLE, INT? or DOUBLE? to a NUMERIC?.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A NUMERIC FAIL LLVM value reference.

    method cast(NUMERIC?) {value {name ""}} {
	set t [TypeOf $value]
	if {$t eq [Type DOUBLE]} {
	    return [my ok [my packNumericDouble $value]]
	} elseif {$t eq [Type INT]} {
	    return [my ok [my packNumericInt $value]]
	} elseif {$t eq [Type DOUBLE?]} {
	    set packer packNumericDouble
	} else {
	    set packer packNumericInt
	}
	my select [my maybe $value] [my fail NUMERIC] \
		[my ok [my $packer [my unmaybe $value]]] $name
    }

    # Builder:cast(bool) --
    #
    #	Generate code to cast an INT to an int1.
    #
    # Parameters:
................................................................................
    # Results:
    #	An int32 LLVM value reference.

    method cast(uint) {value {name ""}} {
	my castUInt2Int $value int $name
    }










































































    # Builder:clearVector --
    #
    #	Clean up a vector value created with buildVector.
    #
    # Parameters:
    #	srcs -	The quadcode values that the vector elements were built from.
    #		Used to detect direct literal STRINGs, which don't need
................................................................................
    #	None.

    method clearVector {srcs vector types} {
	set idx -1
	set ary [my extract $vector 1]
	set stack [my extract $vector 2]
	foreach src $srcs t $types {


	    my dropReference [my load [my gep $ary 0 [incr idx]]]

	}
	my Call [$m intrinsic stackrestore] $stack
	return
    }

    # Builder:concat() --
    #
................................................................................
    #
    # Results:
    #	The retrieved value as an LLVM value reference, or a FAIL.

    method dictGet(STRING,STRING) {dict key ec {name ""}} {
	my call ${tcl.dict.get1} [list $dict $key $ec] $name
    }

    # Builder:dictGetOrNexist(STRING,STRING) --
    #
    #	Retrieve a value from a dictionary, or NEXIST if the key doesn't map
    #	to a value in the dict. This version uses a single simple key. NOTE:
    #	this operation can fail (e.g., because it can be given an invalid
    #	dictionary) so it produces a FAIL NEXIST STRING. Quadcode
    #	implementation ('dictGetOrNexist').
    #
    # Parameters:
    #	dict -	The dictionary as an LLVM value reference.
    #	key -	The key as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The retrieved value as an LLVM value reference, or a NEXIST or FAIL.

    method dictGetOrNexist(STRING,STRING) {dict key ec {name ""}} {
	my call ${tcl.dict.get1.empty} [list $dict $key $ec] $name
    }

    # Builder:dictIncr(STRING,STRING,INT) --
    #
    #	Increment the value for a key in a dictionary. NOTE: this operation
    #	can fail (e.g., because it can be given an invalid dictionary) so it
    #	produces a STRING FAIL. Quadcode implementation ('dictIncr').
    #
................................................................................
    #
    # Results:
    #	The new dictionary value.

    method dictSet(STRING,STRING,STRING) {dict key value ec {name ""}} {
	my call ${tcl.dict.set1} [list $dict $key $value $ec] $name
    }

    # Builder:dictSetOrUnset(STRING,STRING,NEXIST) --
    #
    #	Remove a value in a dictionary. This version uses a single simple key.
    #	NOTE: this operation can fail (e.g., because it can be given an
    #	invalid dictionary) so it produces a STRING FAIL. Quadcode
    #	implementation ('dictSetOrUnset').
    #
    # Parameters:
    #	dict -	The dictionary as an LLVM value reference.
    #	key -	The key as an LLVM value reference.
    #	value -	The NEXIST value (actually ignored).
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new dictionary value, or FAIL.

    method dictSetOrUnset(STRING,STRING,NEXIST) {dict key value ec {name ""}} {
	my call ${tcl.dict.set1.empty} [list $dict $key [my nothing STRING] $ec] $name
    }

    # Builder:dictSetOrUnset(STRING,STRING,NEXIST STRING) --
    #
    #	Set, create or remove a value in a dictionary. This version uses a
    #	single simple key, and the value can be NEXIST to remove the key.
    #	NOTE: this operation can fail (e.g., because it can be given an
    #	invalid dictionary) so it produces a STRING FAIL. Quadcode
    #	implementation ('dictSetOrUnset').
    #
    # Parameters:
    #	dict -	The dictionary as an LLVM value reference.
    #	key -	The key as an LLVM value reference.
    #	value -	The value as an LLVM value reference, or NEXIST.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new dictionary value, or FAIL.

    method dictSetOrUnset(STRING,STRING,NEXIST\040STRING) {dict key value ec {name ""}} {
	my call ${tcl.dict.set1.empty} [list $dict $key $value $ec] $name
    }

    # Builder:dictSetOrUnset(STRING,STRING,NEXIST STRING) --
    #
    #	Set or create a value in a dictionary. This version uses a single
    #	simple key.  NOTE: this operation can fail (e.g., because it can be
    #	given an invalid dictionary) so it produces a STRING FAIL. Quadcode
    #	implementation ('dictSetOrUnset').
    #
    # Parameters:
    #	dict -	The dictionary as an LLVM value reference.
    #	key -	The key as an LLVM value reference.
    #	value -	The value as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new dictionary value, or FAIL.

    method dictSetOrUnset(STRING,STRING,STRING) {dict key value ec {name ""}} {
	my call ${tcl.dict.set1.empty} [list $dict $key [my just $value] $ec] $name
    }

    # Builder:dictSize(STRING) --
    #
    #	Get the size of a dictionary, i.e., the number of key-value pairs.
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to a dict to get the size of.
................................................................................
    #
    # Results:
    #	The new dictionary value.

    method dictUnset(STRING,STRING) {dict key ec {name ""}} {
	my call ${tcl.dict.unset1} [list $dict $key $ec] $name
    }

    # Builder:directAppend(STRING,STRING) --
    #
    #	Append a value to a variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a STRING FAIL. Quadcode implementation
    #	('directAppend').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	value -	The value to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directAppend(STRING,STRING) {varname value ec {name ""}} {
	my call ${tcl.direct.append} [list $varname {} $value $ec] $name
    }

    # Builder:directArrayAppend(STRING,STRING,STRING) --
    #
    #	Append a value to an array variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a STRING FAIL. Quadcode implementation
    #	('directArrayAppend').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	value -	The value to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directArrayAppend(STRING,STRING,STRING) {varname elem value ec {name ""}} {
	my call ${tcl.direct.append} [list $varname $elem $value $ec] $name
    }

    # Builder:directExists(STRING) --
    #
    #	Test if a variable exists; the variable should be referred to by a
    #	fully-qualified name. Quadcode implementation ('directExists').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A ZEROONE that indicates whether the variable is set.

    method directExists(STRING) {varname {name ""}} {
	my call ${tcl.direct.exists} [list $varname {}] $name
    }

    # Builder:directArrayExists(STRING,STRING) --
    #
    #	Test if an array variable exists; the variable should be referred to
    #	by a fully-qualified name. Quadcode implementation
    #	('directArrayExists').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A ZEROONE that indicates whether the variable is set.

    method directArrayExists(STRING,STRING) {varname elem {name ""}} {
	my call ${tcl.direct.exists} [list $varname $elem] $name
    }

    # Builder:directGet(STRING) --
    #
    #	Read the value of a variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a STRING FAIL. Quadcode implementation ('directGet').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The contents of the variable.

    method directGet(STRING) {varname ec {name ""}} {
	my call ${tcl.direct.get} [list $varname {} $ec] $name
    }

    # Builder:directArrayGet(STRING,STRING) --
    #
    #	Read the value of an array variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a STRING FAIL. Quadcode implementation
    #	('directArrayGet').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The contents of the variable.

    method directArrayGet(STRING,STRING) {varname elem ec {name ""}} {
	my call ${tcl.direct.get} [list $varname $elem $ec] $name
    }

    # Builder:directLappend(STRING,STRING) --
    #
    #	Append a value to a list in a variable, which should be referred to by
    #	a fully-qualified name. NOTE: this operation can fail because of
    #	traces so it produces a STRING FAIL. Quadcode implementation
    #	('directLappend').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	value -	The value to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directLappend(STRING,STRING) {varname value ec {name ""}} {
	my call ${tcl.direct.lappend} [list $varname {} $value $ec] $name
    }

    # Builder:directArrayLappend(STRING,STRING,STRING) --
    #
    #	Append a value to a list in an array variable, which should be
    #	referred to by a fully-qualified name. NOTE: this operation can fail
    #	because of traces so it produces a STRING FAIL. Quadcode
    #	implementation ('directArrayLappend').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	value -	The value to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directArrayLappend(STRING,STRING,STRING) {varname elem value ec {name ""}} {
	my call ${tcl.direct.lappend} [list $varname $elem $value $ec] $name
    }

    # Builder:directLappendList(STRING,STRING) --
    #
    #	Append the elements of a list to a list in a variable, which should be
    #	referred to by a fully-qualified name. NOTE: this operation can fail
    #	because of traces so it produces a STRING FAIL. Quadcode
    #	implementation ('directLappendList').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	value -	The list of values to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directLappendList(STRING,STRING) {varname value ec {name ""}} {
	my call ${tcl.direct.lappendList} [list $varname {} $value $ec] $name
    }

    # Builder:directLappendList(STRING,STRING,STRING) --
    #
    #	Append the elements of a list to a list in a variable, which should be
    #	referred to by a fully-qualified name. NOTE: this operation can fail
    #	because of traces so it produces a STRING FAIL. Quadcode
    #	implementation ('directLappendList').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	value -	The list of values to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directArrayLappendList(STRING,STRING,STRING) {varname elem value ec {name ""}} {
	my call ${tcl.direct.lappendList} [list $varname $elem $value $ec] $name
    }

    # Builder:directSet(STRING,STRING) --
    #
    #	Set the value of a variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a STRING FAIL. Quadcode implementation ('directSet').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	value -	The value to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directSet(STRING,STRING) {varname value ec {name ""}} {
	my call ${tcl.direct.set} [list $varname {} $value $ec] $name
    }

    # Builder:directArraySet(STRING,STRING,STRING) --
    #
    #	Set the value of an array variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a STRING FAIL. Quadcode implementation
    #	('directArraySet').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	value -	The value to append as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directArraySet(STRING,STRING,STRING) {varname elem value ec {name ""}} {
	my call ${tcl.direct.set} [list $varname $elem $value $ec] $name
    }

    # Builder:directUnset(STRING,INT) --
    #
    #	Unset a variable, which should be referred to by a fully-qualified
    #	name. NOTE: this operation can fail because of traces so it produces a
    #	ZEROONE FAIL (with meaningless value when not failing). Quadcode
    #	implementation ('directUnset').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	flag -	Whether failures are allowed, as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Whether the unset was successful.

    method directUnset(STRING,INT) {varname flag ec {name ""}} {
	my call ${tcl.direct.unset} [list $varname {} $flag $ec] $name
    }

    # Builder:directArrayUnset(STRING,STRING,INT) --
    #
    #	Unset an array variable, which should be referred to by a
    #	fully-qualified name. NOTE: this operation can fail because of traces
    #	so it produces a ZEROONE FAIL (with meaningless value when not
    #	failing). Quadcode implementation ('directArrayUnset').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	elem -	The element name as an LLVM value reference.
    #	flag -	Whether failures are allowed, as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Whether the unset was successful.

    method directArrayUnset(STRING,STRING,INT) {varname elem flag ec {name ""}} {
	my call ${tcl.direct.unset} [list $varname $elem $flag $ec] $name
    }

    # Builder:directIsArray(STRING) --
    #
    #	Tests if the variable whose name we are given is an array. NOTE: this
    #	operation can fail because of traces so it produces a BOOL FAIL.
    #	Quadcode implementation ('directIsArray').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The new contents of the variable.

    method directIsArray(STRING) {varname ec {name ""}} {
	my call ${tcl.direct.isArray} [list $varname $ec] $name
    }

    # Builder:directMakeArray(STRING) --
    #
    #	Makes the variable whose name we are given be an array. NOTE: this
    #	operation can fail because of traces so it produces a BOOL FAIL.
    #	Quadcode implementation ('directMakeArray').
    #
    # Parameters:
    #	varname -
    #		The variable name as an LLVM value reference.
    #	ec -	Where to write the error code if an error happens.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	FAIL if the operation fails; ignored result otherwise.

    method directMakeArray(STRING) {varname ec {name ""}} {
	my call ${tcl.direct.makeArray} [list $varname $ec] $name
    }

    # Builder:div(INT,INT) --
    #
    #	Generate code to divide two INTs. Quadcode implementation ('div').
    #
    # Parameters:
    #	left -	The INT LLVM value reference for the left operand.
................................................................................
    #	None.

    method dropReference(STRING) {value} {
	my Call tcl.dropReference $value
	return
    }

    # Builder:dropReference(FAIL EMPTY) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The STRING FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040EMPTY) {value} {
	my Call tcl.dropFailReference $value
	return
    }

    # Builder:dropReference(FAIL STRING) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Parameters:
    #	value -	The STRING FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040STRING) {value} {
	my Call tcl.dropFailReference $value
	return
    }

    # Builder:dropReference(NEXIST STRING) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Parameters:
    #	value -	The NEXIST STRING LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040STRING) {value} {
	my Call tcl.dropNExistReference $value
	return
    }

    # Builder:dropReference(NEXIST FAIL STRING) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The NEXIST FAIL STRING LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040FAIL\040STRING) {value} {
	my Call tcl.dropFailNExistReference $value
	return
    }

    # Builder:dropReference(NEXIST EMPTY) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Parameters:
    #	value -	The NEXIST EMPTY LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040EMPTY) {value} {
	my Call tcl.dropNExistReference $value
















	return
    }

    # Builder:dropReference(DICTITER) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
................................................................................
    # Results:
    #	None.

    method dropReference(FAIL\040DICTITER) {value} {
	my Call tcl.dict.dropIterFailReference $value
	return
    }

    # Builder:dropReference(FAIL IMPURE INT) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The <INT> FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040IMPURE\040INT) {value} {
	my Call tcl.dropReference.failImpureInt $value
	return
    }

    # Builder:dropReference(FAIL IMPURE ZEROONE BOOLEAN) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The <ZEROONE BOOLEAN> FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040IMPURE\040ZEROONE\040BOOLEAN) {value} {
	my Call tcl.dropReference.failImpureZeroOneBoolean $value
	return
    }

    # Builder:dropReference(FAIL IMPURE DOUBLE) --
    #
    #	Generate code to decrement the reference count of a value and delete
    #	the value if it has ceased to be used.
    #
    # Parameters:
    #	value -	The <DOUBLE> FAIL LLVM value reference for the operand.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040IMPURE\040DOUBLE) {value} {
	my Call tcl.dropReference.failImpureDouble $value
	return
    }

    # Builder:dropReference(NEXIST ARRAY STRING) --
    #
    #	Generate code to decrement the reference count of a value and free it
    #	if appropriate. ARRAYs are only fully freed if they are not shared
    #	with a variable in a callframe; if they are, the actual delete of the
    #	underlying hash table structure happens when the callframe variables
    #	are resynchronised.
    #
    # Parameters:
    #	value -	The ARRAYSTRING! LLVM value reference for the operand.
    #	name -	The STRING LLVM value reference for the name of the array,
    #		required for the deletion machinery. Expected but not required
    #		to be literal.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040ARRAY\040STRING) {value name} {
	my Call tcl.arraystring.dropRef.nexist $value $name
    }

    # Builder:dropReference(NEXIST ARRAY) --
    #
    #	Generate code to decrement the reference count of a value and free it
    #	if appropriate. ARRAYs are only fully freed if they are not shared
    #	with a variable in a callframe; if they are, the actual delete of the
    #	underlying hash table structure happens when the callframe variables
    #	are resynchronised.
    #
    # Parameters:
    #	value -	The ARRAY! LLVM value reference for the operand.
    #	name -	The STRING LLVM value reference for the name of the array,
    #		required for the deletion machinery. Expected but not required
    #		to be literal.
    #
    # Results:
    #	None.

    method dropReference(NEXIST\040ARRAY) {value name} {
	my Call tcl.array.dropRef.nexist $value $name
    }

    # Builder:dropReference(ARRAY STRING) --
    #
    #	Generate code to decrement the reference count of a value and free it
    #	if appropriate. ARRAYs are only fully freed if they are not shared
    #	with a variable in a callframe; if they are, the actual delete of the
    #	underlying hash table structure happens when the callframe variables
    #	are resynchronised.
    #
    # Parameters:
    #	value -	The ARRAYSTRING LLVM value reference for the operand.
    #	name -	The STRING LLVM value reference for the name of the array,
    #		required for the deletion machinery. Expected but not required
    #		to be literal.
    #
    # Results:
    #	None.

    method dropReference(ARRAY\040STRING) {value name} {
	my Call tcl.arraystring.dropRef $value $name
    }

    # Builder:dropReference(FAIL ARRAY) --
    #
    #	Generate code to decrement the reference count of a value and free it
    #	if appropriate. ARRAYs are only fully freed if they are not shared
    #	with a variable in a callframe; if they are, the actual delete of the
    #	underlying hash table structure happens when the callframe variables
    #	are resynchronised.
    #
    # Parameters:
    #	value -	The ARRAY? LLVM value reference for the operand.
    #	name -	The STRING LLVM value reference for the name of the array,
    #		required for the deletion machinery. Expected but not required
    #		to be literal.
    #
    # Results:
    #	None.

    method dropReference(FAIL\040ARRAY) {value name} {
	my Call tcl.array.dropRef.fail $value $name
    }

    # Builder:dropReference(ARRAY) --
    #
    #	Generate code to decrement the reference count of a value and free it
    #	if appropriate. ARRAYs are only fully freed if they are not shared
    #	with a variable in a callframe; if they are, the actual delete of the
    #	underlying hash table structure happens when the callframe variables
    #	are resynchronised.
    #
    # Parameters:
    #	value -	The ARRAY LLVM value reference for the operand.
    #	name -	The STRING LLVM value reference for the name of the array,
    #		required for the deletion machinery. Expected but not required
    #		to be literal.
    #
    # Results:
    #	None.

    method dropReference(ARRAY) {value name} {
	my Call tcl.array.dropRef $value $name
    }

    # Builder:eq --
    #
    #	Generate code to compare two integers of the same bit width *or* two
    #	pointers for equality.
    #
    # Parameters:
................................................................................
    # Results:
    #	A ZEROONE LLVM value reference.

    method exists {value {name ""}} {
	my not [my maybe $value] $name
    }




























    # Builder:expect --
    #
    #	Issue the expectation that a condition will be true or false. This
    #	affects the weights in the LLVM metadata, and guides the low-level
    #	code issuing.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A NUMERIC? LLVM value reference.

    method expon(NUMERIC,NUMERIC) {left right ec {name ""}} {
	my call ${tcl.pow.numeric} [list $left $right $ec] $name
    }
    
    # Builder:extractFail(FAIL DICTITER) -
    #
    #	Creates a plain FAIL from a FAIL DICTITER
    #
    # Parameters:
    #	src - The LLVM FAIL DICTITER value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040DICTITER) {src {name ""}} {
	my dropReference(FAIL\040DICTITER) $src
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL DOUBLE) -
    #
    #	Creates a plain FAIL from a FAIL DOUBLE
    #
    # Parameters:
    #	src - The LLVM FAIL DOUBLE value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040DOUBLE) {src {name ""}} {
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL EMPTY) -
    #
    #	Creates a plain FAIL from a FAIL EMPTY
    #
    # Parameters:
    #	src - The LLVM FAIL EMPTY value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040EMPTY) {src {name ""}} {
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL FOREACH) -
    #
    #	Creates a plain FAIL from a FAIL FOREACH
    #
    # Parameters:
    #	src - The LLVM FAIL FOREACH value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040FOREACH) {src {name ""}} {
	# Isn't FOREACH a reference type?
	# my dropReference(FAIL\040FOREACH) $src 
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL INT) -
    #
    #	Creates a plain FAIL from a FAIL INT
    #
    # Parameters:
    #	src - The LLVM FAIL INT value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040INT) {src {name ""}} {
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL NUMERIC) -
    #
    #	Creates a plain FAIL from a FAIL NUMERIC
    #
    # Parameters:
    #	src - The LLVM FAIL NUMERIC value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040NUMERIC) {src {name ""}} {
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL STRING) -
    #
    #	Creates a plain FAIL from a FAIL STRING
    #
    # Parameters:
    #	src - The LLVM FAIL STRING value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040STRING) {src {name ""}} {
	my extract $src 0 $name
    }

    # Builder:extractFail(FAIL ZEROONE) -
    #
    #	Creates a plain FAIL from a FAIL ZEROONE
    #
    # Parameters:
    #	src - The LLVM FAIL ZEROONE value
    #	name (optional) - A name to give to the result value

    method extractFail(FAIL\040ZEROONE) {src {name ""}} {
	my extract $src 0 $name
    }
    
    # Builder:extractFail(NEXIST FAIL STRING) -
    #
    #	Creates a plain FAIL from a NEXIST FAIL STRING
    #
    # Parameters:
    #	src - The LLVM NEXIST FAIL STRING value
    #	name (optional) - A name to give to the result value

    method extractFail(NEXIST\040FAIL\040STRING) {src {name ""}} {
	my dropReference(NEXIST\040FAIL\040STRING) $src
	my extract $src 0 $name
    }

    # Builder:fail --
    #
    #	Create a Nothing FAIL of the given type.
    #
    # Parameters:
    #	type -	The type of the FAIL.
    #	code (optional) -
    #		The error code in the failure (LLVM int32 reference), or the
    #		empty string to use the default.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM FAIL value reference containing nothing.

    method fail {type {code ""} {name ""}} {
	if {[string match "* FAIL" $type]} {
	    set type [string range $type 0 end-5]
	} elseif {[string match "FAIL *" $type]} {
	    set type [string range $type 5 end]
	}
	if {$code eq ""} {
	    set code [Const 1]
	}
	my insert [my undef $type?] $code 0 $name
    }

    # Builder:ge --
    #
    #	Generate code to compare two integers of the same bit width *or* two
    #	pointers to see if the first is greater or equal to the second.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A ZEROONE LLVM value reference.

    method gt(STRING,STRING) {left right {name ""}} {
	my gt [my Call tcl.cmp.strstr $left $right] [Const 0] $name
    }

    # Builder:impure --
    #
    #	Construct an impure value from its components. Note that this does not
    #	perform reference management.
    #
    # Parameters:
    #	basetype -
    #		The type to add impurity to.
    #	string -
    #		The string version of the resulting value, as a STRING LLVM
    #		reference.
    #	value -
    #		The non-string version of the resulting value, as an LLVM
    #		reference of the correct type.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A IMPURE $basetype LLVM value reference.

    method impure {basetype string value {name ""}} {
	set ival [my undef [Type "IMPURE $basetype"]]
	return [my insert [my insert $ival $string 0] $value 1 $name]
    }

    # Builder:impure.string --
    #
    #	Get the string part of an impure value. Note that this does not
    #	perform reference management.
    #
    # Parameters:
    #	value -	The IMPURE * LLVM value.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING LLVM value reference.

    method impure.string {value {name ""}} {
	set result [my extract $value 0 [GetValueName $value].string]
	if {$name ne ""} {
	    SetValueName $result $name
	}
	return $result
    }

    # Builder:impure.value --
    #
    #	Get the non-string part of an impure value. Note that this does not
    #	perform reference management.
    #
    # Parameters:
    #	value -	The IMPURE * LLVM value.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference. The type of the result will be the type of
    #	the value packed within the IMPURE holder.

    method impure.value {value {name ""}} {
	set result [my extract $value 1 [GetValueName $value].value]
	if {$name ne ""} {
	    SetValueName $result $name
	}
	return $result
    }

    # Builder:initException --
    #
    #	Generate/set up an exception.
    #
    # Parameters:
    #	errorcode -
................................................................................
	} else {
	    set stringed [my stringify($type) $value]
	    set code [my Call tcl.initExceptionOptions $stringed $dict]
	    # FIXME?
	    # my dropReference $stringed
	}
	my store $code $errVar
	my select [my Call tcl.handleExceptionResult $code $value] \
	    [my ok $value] [my fail $type $code] $name
    }

    # Builder:initException(STRING,INT,INT) --
    #
    #	Generate/set up an exception, returning a FAIL derived from the
    #	'value' argument. Quadcode implementation ('initException').
    #
................................................................................
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference.

    method initException(STRING,INT,INT) {dict code level value type errVar {name ""}} {
	if {$type in {STRING EMPTY}} {
	    set newcode [my Call tcl.processReturn \
		$value [my getInt32 $code] [my getInt32 $level] $dict]
	} else {
	    set stringed [my stringify($type) $value]
	    set newcode [my Call tcl.processReturn \
		$stringed [my getInt32 $code] [my getInt32 $level] $dict]
	    # FIXME?
	    my dropReference $stringed
	}
	SetValueName $newcode "code"
	my store $newcode $errVar
	my select [my Call tcl.handleExceptionResult $newcode $value] \
	    [my ok $value] [my fail $type $newcode] $name
    }

    # Builder:setReturnCode(INT) --
    #
    #	Set the current Tcl return code in the implicit state to be the given
    #	value. Quadcode implementation ('setReturnCode').
    #
    # Parameters:
    #	code -	The Tcl return code, as an INT.
    #	errVar -
    #		Where the actual result code is to be written to.
    #
    # Results:
    #	None.

    method setReturnCode(INT) {code errVar} {
	my store [my getInt32 $code] $errVar
	return
    }

    # Builder:instanceOf.DOUBLE(STRING) --
    #
    #	Generate code to check if the given STRING contains something that can
    #	be parsed to get a DOUBLE. Quadcode implementation ('instanceOf').
    #
................................................................................
    #	Generate code to call a Tcl command.  Quadcode implementation
    #	('invoke').
    #
    # Parameters:
    #	arguments -
    #		The arguments as an LLVM vector value reference. Note that
    #		this includes the function name as the first argument.
    #	havecf -
    #		Tcl boolean indicating if we have a valid callframe.
    #	cf -	The reference to the current callframe if 'havecf' is true.
    #	ec -	Location to write the Tcl return code into, as an LLVM int*


    #		reference.
    #	resultName (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference.

    method invoke {arguments havecf cf ec {resultName ""}} {
	my ExtractVector $arguments
	if {!$havecf} {
	    set cf {}
	}
	my call ${tcl.invoke.command} [list $len $ary $cf $ec] $resultName
    }

    # Builder:invokeExpanded --
    #
    #	Generate code to call a Tcl command while doing argument expansion.
    #	Quadcode implementation ('invokeExpanded').
    #
    # Parameters:
    #	arguments -
    #		The arguments as an LLVM vector value reference. Note that
    #		this includes the function name as the first argument.
    #	flags -	LLVM bit array indicating which arguments to expand.
    #	ec -	Location to write the Tcl return code into, as an LLVM int*
    #		reference.
    #	resultName (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM value reference.

    method invokeExpanded {arguments flags ec {resultName ""}} {
	my ExtractVector $arguments
	my call ${tcl.invoke.expanded} [list $len $ary $flags $ec] $resultName
    }

    # Builder:isBoolean(INT BOOLEAN) --
    #
    #	Test if a value is a boolean. Quadcode implementation ('isBoolean').
    #
    # Parameters:
................................................................................

    method lt(STRING,STRING) {left right {name ""}} {
	my lt [my Call tcl.cmp.strstr $left $right] [Const 0] $name
    }

    # Builder:just --
    #
    #	Package a value as a Just NEXIST.
    #
    # Parameters:
    #	value -	The value to put inside the NEXIST.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM NEXIST value reference containing the other value.

    method just {value {name ""}} {
	my insert [my insert [my undef [TypeOf $value]!] \
		       [Const false bool] 0] $value 1 $name
    }

    # Builder:narrowToType.DOUBLE(STRING) --
    #
    #	Generate code to parse the given STRING and extract a DOUBLE. The
    #	STRING is already be known to contain a value of the right type (due
................................................................................
    #
    # Results:
    #	A DOUBLE LLVM value reference.

    method narrowToType.DOUBLE(STRING) {value {name ""}} {
	my call ${tcl.extractDouble} [list $value] $name
    }

    # Builder:narrowToType.IMPURE_DOUBLE(STRING) --
    #
    #	Generate code to extract IMPURE DOUBLE from STRING.  This parses the
    #	number in the string and pairs it up with the string, as well as
    #	adding a reference to the string itself.
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to parse.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE DOUBLE LLVM value reference.

    method narrowToType.IMPURE_DOUBLE(STRING) {value {name ""}} {
	set nval [my Call tcl.extractDouble $value]
	my addReference(STRING) $value
	return [my impure DOUBLE $value $nval $name]
    }

    # Builder:narrowToType.IMPURE_BOOLEAN(IMPURE ZEROONE BOOLEAN) --
    #
    #	Generate code to extract IMPURE BOOLEAN from IMPURE ZEROONE BOOLEAN.
    #	The extraction does nothing except bump the reference count, the two
    #	types have the same internal representation
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to parse.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE BOOLEAN LLVM value reference.

    method narrowToType.IMPURE_BOOLEAN(IMPURE\040ZEROONE\040BOOLEAN) {value {name ""}} {
	my addReference(STRING) [my impure.string $value]
	if {$name ne "" && [string match {[0-9]*} [GetValueName $value]]} {
	    SetValueName $value $name
	}
	return $value
    }

    # Builder:narrowToType.IMPURE_ZEROONE(IMPURE ZEROONE BOOLEAN) --
    #
    #	Generate code to extract IMPURE ZEROONE from IMPURE ZEROONE BOOLEAN.
    #	The extracton does nothing except bump the reference count, the two
    #	types have the same internal representation
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to parse.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE ZEROONE LLVM value reference.

    method narrowToType.IMPURE_ZEROONE(IMPURE\040ZEROONE\040BOOLEAN) {value {name ""}} {
	my addReference(STRING) [my impure.string $value]
	if {$name ne "" && [string match {[0-9]*} [GetValueName $value]]} {
	    SetValueName $value $name
	}
	return $value
    }

    # Builder:narrowToType.INT(STRING) --
    #
    #	Generate code to parse the given STRING and extract an INT. The STRING
    #	is already be known to contain a value of the right type (due to
    #	higher-level quadcode constraints). Quadcode implementation
    #	('narrowToType').
................................................................................
    #
    # Results:
    #	An INT LLVM value reference.

    method narrowToType.INT(STRING) {value {name ""}} {
	my call ${tcl.extractInteger} [list $value] $name
    }

    # Builder:narrowToType.IMPURE_INT(STRING) --
    #
    #	Generate code to extract IMPURE INT from STRING.  This parses the
    #	number in the string and pairs it up with the string, as well as
    #	adding a reference to the string itself.
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to parse.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE INT LLVM value reference.

    method narrowToType.IMPURE_INT(STRING) {value {name ""}} {
	set nval [my Call tcl.extractInteger $value]
	my addReference(STRING) $value
	return [my impure INT $value $nval $name]
    }

    # Builder:narrowToType.INT(NUMERIC) --
    #
    #	Generate code to narrow a NUMERIC to an INT.
    #
    # Parameters:
    #	value - The NUMERIC LLVM reference to parse
    #	name (optional) -
    #		A name to give to the result value

    method narrowToType.INT(NUMERIC) {value {name ""}} {
	my numeric.int $value $name
    }

    # Builder:narrowToType.IMPURE_INT(IMPURE NUMERIC) --
    #
    #	Generate code to extract IMPURE INT from IMPURE NUMERIC.  This narrows
    #	the number in the string and pairs it up with the string part, as well
    #	as adding a reference to the string itself.
    #
    # Parameters:
    #	value -	The IMPURE NUMERIC LLVM value reference to narrow.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE DOUBLE LLVM value reference.

    method {narrowToType.IMPURE_INT(IMPURE NUMERIC)} {value {name ""}} {
	set sval [my impure.string $value]
	my addReference(STRING) $sval
	set nval [my numeric.int [my impure.value $value]]
	return [my impure INT $sval $nval $name]
    }

    # Builder:narrowToType.NUMERIC(STRING) --
    #
    #	Generate code to parse the given STRING and extract a NUMERIC. The
    #	STRING is already be known to contain a value of the right type (due
    #	to higher-level quadcode constraints). Quadcode implementation
    #	('narrowToType').
................................................................................
    #
    # Results:
    #	A NUMERIC LLVM value reference.

    method narrowToType.NUMERIC(STRING) {value {name ""}} {
	my call ${tcl.extractNumeric} [list $value] $name
    }

    # Builder:narrowToType.IMPURE_NUMERIC(STRING) --
    #
    #	Generate code to extract IMPURE NUMERIC from STRING.  This parses the
    #	number in the string and pairs it up with the string, as well as
    #	adding a reference to the string itself.
    #
    # Parameters:
    #	value -	The STRING LLVM value reference to parse.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE NUMERIC LLVM value reference.

    method narrowToType.IMPURE_NUMERIC(STRING) {value {name ""}} {
	set nval [my call ${tcl.extractNumeric} [list $value]]

	my addReference(STRING) $value
	return [my impure NUMERIC $value $nval $name]
    }

    # Builder:nothing --
    #
    #	Create a Nothing NEXIST of the given type.
    #
    # Parameters:
    #	type -	The type of the NEXIST.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM NEXIST value reference containing nothing.

    method nothing {type {name ""}} {
	if {[string match "* NEXIST" $type]} {
	    set type [string range $type 0 end-7]
	} elseif {[string match "NEXIST *" $type]} {
	    set type [string range $type 7 end]
	}
	my insert [my undef $type!] [Const true bool] 0 $name
    }

    # Builder:unmaybe --
    #
    #	Get the value out of a FAIL or NEXIST. NOTE: The FAIL/NEXIST must be a
    #	Just or the result will be an 'undef'; test with the 'maybe' method
    #	first!
    #
    # Parameters:
    #	value -	The FAIL to get the value from.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
................................................................................
	set mapping [my @jumptable.constant $mapping]
	set notThere [Const $notThere int]
	my call ${tcl.maptoint} [list $value $mapping $notThere] $name
    }

    # Builder:maybe --
    #
    #	Test if the FAIL or NEXIST value is a Nothing.
    #
    # Parameters:
    #	type -	The FAIL or NEXIST to examine.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM int1 value reference that is true when the FAIL is a Nothing
    #	and false when the FAIL is a Just.

    method maybe {value {name ""}} {
	set flag [my extract $value 0 $name]
	if {[TypeOf $flag] eq [Type bool]} {
	    my neq [Const false bool] $flag
	} else {
	    my neq [Const 0] $flag
	}
    }

    # Builder:max --
    #
    #	Determines the maximum of two LLVM int[x] values.
    #
    # Parameters:
................................................................................
    #
    # Results:
    #	A ZEROONE LLVM value reference.

    method not(ZEROONE) {value errVar {name ""}} {
	my not $value $name
    }

    # Builder:ok --
    #
    #	Package a value as a Just FAIL.
    #
    # Parameters:
    #	value -	The value to put inside the FAIL.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM FAIL value reference containing the other value.

    method ok {value {name ""}} {
	my insert [my insert [my undef [TypeOf $value]?] \
		       [Const 0] 0] $value 1 $name
    }

    # Builder:packImpure(DOUBLE) --
    #
    #	Convert a DOUBLE to an IMPURE DOUBLE
    #
    # Parameters:
    #	value -	LLVM Value to pack into the 'impure' structure
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Returns an LLVM IMPURE DOUBLE value

    method packImpure(DOUBLE) {value {name ""}} {
	set sval [my stringify(DOUBLE) $value]
	my addReference(STRING) $sval
	return [my impure DOUBLE $sval $value $name]
    }

    # Builder:packImpure(INT) --
    #
    #	Convert a INT to an IMPURE INT
    #
    # Parameters:
    #	value -	LLVM Value to pack into the 'impure' structure
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Returns an LLVM IMPURE INT value

    method packImpure(INT) {value {name ""}} {
	set sval [my stringify(INT) $value]
	my addReference(STRING) $sval
	return [my impure INT $sval $value $name]
    }

    # Builder:packImpure(NUMERIC) --
    #
    #	Convert a NUMERIC to an IMPURE NUMERIC
    #
    # Parameters:
    #	value -	LLVM Value to pack into the 'impure' structure

    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Returns an LLVM IMPURE NUMERIC value

    method packImpure(NUMERIC) {value {name ""}} {
	set sval [my stringify(NUMERIC) $value]
	my addReference(STRING) $sval
	return [my impure NUMERIC $sval $value $name]

    }

    # Builder:packImpure(ZEROONE BOOLEAN) --
    #
    #	Convert a ZEROONE BOOLEAN to an IMPURE ZEROONE BOOLEAN
    #
    # Parameters:
    #	value -	LLVM Value to pack into the 'impure' structure
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Returns an LLVM IMPURE NUMERIC value

    method {packImpure(ZEROONE BOOLEAN)} {value {name ""}} {
	set sval [my stringify(NUMERIC) $value]
	my addReference(STRING) $sval
	return [my impure ZEROONE $sval $value $name]


    }

    # Builder:procLeave(INT,STRING) --
    #
    #	Convert a return code in the way the end of a procedure does.
    #
    # Parameters:
    #	value -	LLVM INT value holding the planned return code.
    #	procName -
    #		LLVM STRING value with unqualified name of the procedure that
    #		we are returning from.
    #	errVar -
    #		Location to write the Tcl return code into, as an LLVM int*
    #		reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	Returns an LLVM IMPURE NUMERIC value

    method procLeave(INT,STRING) {value procName errVar {name ""}} {
	my call ${tcl.procedure.return} [list $value $procName $errVar] $name
    }

    # Builder:regexp(INT,STRING,STRING) --
    #
    #	Match a string against a regular expression. NOTE: this operation can
    #	fail (e.g., because it can be given an invalid regexp) so it produces
    #	an INT FAIL. Quadcode implementation ('regexp').
................................................................................
    #	Whether any/how many matches occurred, as an LLVM ZEROONE FAIL
    #	reference.

    method regexp(INT,STRING,STRING) {opts regexpr value errVar {name ""}} {
	my call ${tcl.regexp} [list $opts $regexpr $value $errVar] $name
    }

    # Builder:resolveCmd(STRING) --
    #
    #	Resolve the given command. Quadcode implementation ('resolveCmd').
    #
    # Parameters:
    #	cmdName - Name of the command being resolved
    #	name (optional) - A name to give to the result value
    #
    # Results:
    #	Returns an LLVM STRING value giving the resolved command name
    #   or an empty string if the command cannot be resolved.

    method resolveCmd(STRING) {cmdName {name ""}} {
	my call ${tcl.resolveCmd} [list $cmdName] $name
    }

    # Builder:originCmd(STRING) --
    #
    #	Resolve the original name of the given command.
    #   Quadcode implementation ('originCmd').
    #
    # Parameters:
    #	cmdName - Name of the command being resolved
    #	ec - Where to store the error code
    #	name (optional) - A name to give to the result value
    #
    # Results:
    #	Returns an LLVM STRING value giving the resolved command name
    #   or an empty string if the command cannot be resolved.

    method originCmd(STRING) {cmdName ec {name ""}} {
	my call ${tcl.originCmd} [list $cmdName $ec] $name
    }

    # Builder:result(FAIL) --
    #
    #	Get the Tcl result. Quadcode implementation ('result').
    #
    # Parameters:
    #   src - The Tcl FAIL object that should be manipulated
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method result(FAIL) {src {name ""}} {
	my call ${tcl.getresult} {} $name
    }

    # Builder:result(FAIL STRING) --
    #
    #	Get the Tcl result. Quadcode implementation ('result').
    #
    # Parameters:
    #   src - The Tcl FAIL STRING object that should be manipulated
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method result(FAIL\040STRING) {src {name ""}} {
	my dropReference(FAIL\040STRING) $src
	my call ${tcl.getresult} {} $name
    }

    # Builder:result(STRING) --
    #
    #	Get the Tcl result. Quadcode implementation ('result').
    #
    # Parameters:
    #   src - The Tcl STRING object that should be manipulated
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method result(STRING) {src {name ""}} {
	my dropReference(STRING) $src
	my call ${tcl.getresult} {} $name
    }

    # Builder:returnCode(FAIL) --
    #
    #   Pass the Tcl return code through to an LLVM value
    #
    # Parameters:
    #	src - The FAIL STRING value that encodes the last interpreter action
    #   ecode - The INT32 value that holds the return code
    #   name (optional) - A name to give to the result value
    #
    # Results:
    #	Returns an LLVM INT reference

    method returnCode(FAIL) {src ecode name} {
	my packInt32 $ecode
    }

    # Builder:returnCode(FAIL STRING) --
    #
    #   Pass the Tcl return code through to an LLVM value
    #
    # Parameters:
    #	src - The FAIL STRING value that encodes the last interpreter action
    #   ecode - The INT32 value that holds the return code
    #   name (optional) - A name to give to the result value
    #
    # Results:
    #	Returns an LLVM INT reference

    method returnCode(FAIL\040STRING) {src ecode name} {
	my dropReference(FAIL\040STRING) $src
	my packInt32 $ecode $name
    }

    # Builder:returnOptions(FAIL,INT) --
    #
    #	Get the Tcl exception dictionary. Quadcode implementation
    #	('returnOptions').
    #
    # Parameters:
    #   src - The Tcl status, as a LLVM FAIL reference
    #	value -	The Tcl result code, as an LLVM INT value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method returnOptions(FAIL,INT) {src value {name ""}} {
	my call ${tcl.getreturnopts} [list $value] $name
    }

    # Builder:returnOptions(FAIL STRING,INT) --
    #
    #	Get the Tcl exception dictionary. Quadcode implementation
    #	('returnOptions').
    #
    # Parameters:
    #   src - The Tcl status, as a LLVM FAIL STRING reference
    #	value -	The Tcl result code, as an LLVM INT value reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An LLVM STRING reference.

    method returnOptions(FAIL\040STRING,INT) {src value {name ""}} {
	my dropReference(FAIL\040STRING) $src
	my call ${tcl.getreturnopts} [list $value] $name
    }

    # Builder:rshift(INT,INT) --
    #
    #	Generate code to shift an INT right (divide by powers of 2). Quadcode
    #	implementation ('rshift').
................................................................................
    #
    # Results:
    #	An INT LLVM value reference.

    method rshift(INT,INT) {left right {name ""}} {
	my call ${tcl.shr} [list $left $right] $name
    }

    # Builder:logCommandInfo --
    #
    #	Generate code to log information about a command in the exception
    #	trace.
    #
    # Parameters:
    #	errorCode -
    #		The int32 LLVM value reference for the Tcl error code.
    #	command -
    #		The Tcl string containing the text of the command script
    #		(i.e., sourced before substitutions are performed).
    #
    # Results:
    #	None.

    method logCommandInfo {errorCode command} {
	set limit 150
	set overflow [expr {[string length $command] > $limit}]
	set length [Const [expr {$overflow ? $limit : [string length $command]}]]
	set cmd [my constString $command]
	set ellipsis [my constString [if {$overflow} {string cat "..."}]]
	my Call tcl.logCommandInfo $errorCode $length $cmd $ellipsis
	return
    }

    # Builder:setErrorLine --
    #
    #	Generate code to log information about a command in the exception
    #	trace if that command happens to have generated an error.
    #
    # Parameters:
    #	test -	The bool LLVM value reference that says whether the command
    #		this is talking about generated a non-TCL_OK result.
    #	errorCode -
    #		The int32 LLVM value reference for the Tcl error code.
    #	line -	The int32 LLVM value reference for the source line number for
    #		the (start of) the command.
    #	command -
    #		The Tcl string containing the text of the command script
    #		(i.e., sourced before substitutions are performed).
    #
    # Results:
    #	None.

    method setErrorLine {test errorCode line command} {
	set limit 150
	set overflow [expr {[string length $command] > $limit}]
	set length [Const [expr {$overflow ? $limit : [string length $command]}]]
	set cmd [my constString $command]
	set ellipsis [my constString [if {$overflow} {string cat "..."}]]
	my Call tcl.setErrorLine $test $errorCode $line $length $cmd $ellipsis
	return
    }

    # Builder:storeInStruct --
    #
    #	Generate code to write a value into a structure that is pointed to by
    #	the first argument.
    #
    # Parameters:
    #	structPointer -
    #		The LLVM pointer value reference to the structure to be
    #		written to.
    #	fieldOffset -
    #		The description of which field of the structure to update. See
    #		the 'gep' (or 'insert') method for a description of what forms
    #		this may take.
    #	value -	The value to write into the field. Must type-match.
    #
    # Results:
    #	None.

    method storeInStruct {structPointer fieldOffset value} {
	set field [my gep $structPointer 0 $fieldOffset]
	set fieldName [regsub {.*\.} $fieldOffset ""]
	SetValueName $field [GetValueName $structPointer].$fieldName
	my store $value $field
    }

    # Builder:stringify(DOUBLE) --
    #
    #	Generate a STRING representation of a DOUBLE. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
................................................................................
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(DOUBLE) {value {name ""}} {
	my call ${tcl.stringify.double} [list $value] $name
    }

    # Builder:stringify(IMPURE DOUBLE) --
    #
    #	Generate a STRING representation of an IMPURE DOUBLE. WARNING: caller
    #	is entirely responsible for reference count management; this method
    #	does not handle that. This method is used by the type promotion code.
    #
    # Parameters:
    #	value -	The IMPURE DOUBLE LLVM value reference to convert.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(IMPURE\040DOUBLE) {value {name ""}} {
	my stringifyImpure $value $name
    }

    # Builder:stringify(INT) --
    #
    #	Generate a STRING representation of an INT. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
................................................................................
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(INT) {value {name ""}} {
	my call ${tcl.stringify.int} [list $value] $name
    }

    # Builder:stringify(IMPURE INT) --
    #
    #	Generate a STRING representation of an IMPURE INT. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
    # Parameters:
    #	value -	The IMPURE INT LLVM value reference to convert.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(IMPURE\040INT) {value {name ""}} {
	my stringifyImpure $value $name
    }

    # Builder:stringify(NUMERIC) --
    #
    #	Generate a STRING representation of a NUMERIC. WARNING: caller is
    #	entirely responsible for reference count management; this method does
    #	not handle that. This method is used by the type promotion code.
    #
................................................................................
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(NUMERIC) {value {name ""}} {
	my call ${tcl.stringify.numeric} [list $value] $name
    }

    # Builder:stringify(IMPURE NUMERIC) --
    #
    #	Generate a STRING representation of an IMPURE NUMERIC. WARNING: caller
    #	is entirely responsible for reference count management; this method
    #	does not handle that. This method is used by the type promotion code.
    #
    # Parameters:
    #	value -	The IMPURE NUMERIC LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING LLVM value reference.

    method stringify(IMPURE\040NUMERIC) {value {name ""}} {
	my stringifyImpure $value $name
    }

    # Builder:stringify(STRING) --
    #
    #	Do-nothing pass through.
    #
    # Parameters:
    #	value -	The INT LLVM value reference to convert.
................................................................................

    # Builder:stringifyImpure --
    #
    #	Extract the string value of an impure object
    #
    # Parameters:
    #	value - The LLVM value to convert
    #	name (optional) -
    #		A name to give the result value
    #
    # Results:
    #	The string value is extracted. No refcount management is performed.

    method stringifyImpure {value {name ""}} {
	set v [my impure.string $value]
	if {$name ne ""} {
	    SetValueName $v $name
	}
	return $v
    }

    # Builder:strcase(STRING,INT) --
    #
    #	Generate a STRING that is a copy of an input STRING with a case
    #	transformation applied to it; the case transformation is described by
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING FAIL LLVM value reference (never a nothing). This will have a
    #	non-zero reference count.

    method strindex(STRING,INT) {str idx ecvar {name ""}} {
	my ok [my Call tcl.stridx $str $idx] $name
    }

    # Builder:strindex(STRING,STRING) --
    #
    #	Generate a STRING (of length 1) that describes the character in the
    #	input STRING located at the index given by the input STRING, or the
    #	empty STRING if that index does not indicate a character in the
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING FAIL LLVM value reference (never a nothing). This will have a
    #	non-zero reference count.

    method strrange(STRING,INT,INT) {str from to ecvar {name ""}} {
	my ok [my Call tcl.strrange $str $from $to] $name
    }

    # Builder:strrange(STRING,STRING,STRING) --
    #
    #	Generate a STRING that describes the substring of the input STRING
    #	located from the index given by the input STRING 'from' to the index
    #	given by the input STRING 'to', or the empty STRING if those indices
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	A STRING FAIL LLVM value reference (never a nothing). This will have a
    #	non-zero reference count.

    method strreplace(STRING,INT,INT,STRING) {str from to substr ecvar {name ""}} {
	my ok [my Call tcl.strreplace $str $from $to $substr] $name
    }

    # Builder:strreplace(STRING,STRING,STRING,STRING) --
    #
    #	Generate a STRING that is the input STRING 'str' with the substring
    #	from the index given by the input STRING 'from' to the index given by
    #	the input STRING 'to' replaced with the input STRING 'substr'. This is
................................................................................
    #
    # Results:
    #	A writable Tcl_Obj* in an LLVM value reference.

    method unshareCopy(STRING) {value {name ""}} {
	my call ${tcl.unshare.copy} [list $value] $name
    }

    # Builder:upcastImpure.INT(ZEROONE) --
    #
    #	Generate code to create the conversion of an IMPURE ZEROONE to an
    #	IMPURE INT.
    #
    # Parameters:
    #	value -	The IMPURE ZEROONE LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE INT LLVM value reference. *NOTE* that this does not do
    #	reference management of the string part!

    method upcastImpure.INT(ZEROONE) {value {name ""}} {
	set str [my impure.string $value]
	set num [my cast(BOOLEAN) [my impure.value $value]]
	return [my impure INT $str $num $name]
    }

    # Builder:upcastImpure.NUMERIC(DOUBLE) --
    #
    #	Generate code to create the conversion of an IMPURE DOUBLE to an
    #	IMPURE NUMERIC.
    #
    # Parameters:
    #	value -	The IMPURE DOUBLE LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE NUMERIC LLVM value reference. *NOTE* that this does not do
    #	reference management of the string part!

    method upcastImpure.NUMERIC(DOUBLE) {value {name ""}} {
	set str [my impure.string $value]
	set num [my packNumericDouble [my impure.value $value]]
	return [my impure NUMERIC $str $num $name]
    }

    # Builder:upcastImpure.NUMERIC(INT) --
    #
    #	Generate code to create the conversion of an IMPURE INT to an
    #	IMPURE NUMERIC.
    #
    # Parameters:
    #	value -	The IMPURE INT LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE NUMERIC LLVM value reference. *NOTE* that this does not do
    #	reference management of the string part!

    method upcastImpure.NUMERIC(INT) {value {name ""}} {
	set str [my impure.string $value]
	set num [my packNumericInt [my impure.value $value]]
	return [my impure NUMERIC $str $num $name]
    }

    # Builder:upcastImpure.INT(ZEROONE) --
    #
    #	Generate code to create the conversion of an IMPURE ZEROONE to an
    #	IMPURE NUMERIC.
    #
    # Parameters:
    #	value -	The IMPURE ZEROONE LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An IMPURE NUMERIC LLVM value reference. *NOTE* that this does not do
    #	reference management of the string part!

    method upcastImpure.NUMERIC(ZEROONE) {value {name ""}} {
	set str [my impure.string $value]
	set num [my packNumericInt [my cast(BOOLEAN) [my impure.value $value]]]
	return [my impure NUMERIC $str $num $name]
    }

    # Builder:uplus(INT) --
    #
    #	Generate code to create the negation of an INT. Quadcode
    #	implementation ('uplus').
    #
    # Parameters:
    #	value -	The INT LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	An INT LLVM value reference.

    method uplus(INT) {value {name ""}} {
	return $value
    }

    # Builder:uplus(DOUBLE) --
    #
    #	Generate code to create the negation of a DOUBLE. Quadcode
    #	implementation ('uplus').
    #
    # Parameters:
    #	value -	The DOUBLE LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A DOUBLE LLVM value reference.

    method uplus(DOUBLE) {value {name ""}} {
	if {[GetTypeKind [TypeOf $value]] ne "LLVMDoubleTypeKind"} {
	    return -code error "value must be double"
	}
	return $value
    }

    # Builder:uplus(NUMERIC) --
    #
    #	Generate code to create the negation of a NUMERIC. Quadcode
    #	implementation ('uplus').
    #
    # Parameters:
    #	value -	The NUMERIC LLVM value reference for the operand.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	A NUMERIC LLVM value reference.

    method uplus(NUMERIC) {value {name ""}} {
	return $value
    }

    # Builder:verifyList(STRING) --
    #
    #	Test whether a value is a list; if it is, return it, and if it isn't,
    #	produce a FAIL. Quadcode implementation ('verifyList').
    #
    # Parameters:
    #	value -	Value to verify, in an LLVM STRING reference.
    #	ec -	Location to write the Tcl return code into, as an LLVM int*
    #		reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The list, as an LLVM STRING FAIL reference.

    method verifyList(STRING) {value ec {name ""}} {
	my call ${tcl.list.verify} [list $value $ec] $name
    }

    # Builder:verifyList(DOUBLE) --
    #
    #	DOUBLEs are always lists. Quadcode implementation ('verifyList').
    #
    # Parameters:
    #	value -	Value to verify, in an LLVM DOUBLE reference.
    #	ec -	Location to write the Tcl return code into, as an LLVM int*
    #		reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The list, as an LLVM DOUBLE FAIL reference.

    method verifyList(DOUBLE) {value ec {name ""}} {
	return [my ok $value]
    }

    # Builder:verifyList(INT) --
    #
    #	INTs are always lists. Quadcode implementation ('verifyList').
    #
    # Parameters:
    #	value -	Value to verify, in an LLVM INT reference.
    #	ec -	Location to write the Tcl return code into, as an LLVM int*
    #		reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The list, as an LLVM INT FAIL reference.

    method verifyList(INT) {value ec {name ""}} {
	return [my ok $value]
    }

    # Builder:verifyList(NUMERIC) --
    #
    #	NUMERICs are always lists. Quadcode implementation ('verifyList').
    #
    # Parameters:
    #	value -	Value to verify, in an LLVM STRING reference.
    #	ec -	Location to write the Tcl return code into, as an LLVM int*
    #		reference.
    #	name (optional) -
    #		A name to give to the result value.
    #
    # Results:
    #	The list, as an LLVM NUMERIC reference.

    method verifyList(NUMERIC) {value ec {name ""}} {
	return [my ok $value]
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/compile.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
..
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
...
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
...
223
224
225
226
227
228
229



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
...
259
260
261
262
263
264
265

266






267
268
269
270
271
272
273
274
275
276
277
...
294
295
296
297
298
299
300







301
302
303
304
305
306
307
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
...
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
....
1145
1146
1147
1148
1149
1150
1151

1152
1153
1154

1155
1156
1157
1158
1159
1160
1161
....
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
....
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
....
1287
1288
1289
1290
1291
1292
1293
1294




















1295
1296
1297
1298
1299
1300
1301
....
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
....
1421
1422
1423
1424
1425
1426
1427






1428
1429
1430
1431
1432



1433
1434
















1435
1436
1437
1438
1439
1440
1441
....
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
....
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
....
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
....
1683
1684
1685
1686
1687
1688
1689
1690
1691

1692





1693
1694
1695
1696
1697
1698
1699
....
1702
1703
1704
1705
1706
1707
1708





1709
1710
1711
1712
1713
1714
1715
....
1727
1728
1729
1730
1731
1732
1733

1734
# compile.tcl --
#
#	Engine that handles compiling and issuing code for a single Tcl
#	procedure. Note that this needs to be done within the context of an
#	LLVM module (which is approximately the same concept as a compilation
#	unit in a language like C).
#
# Copyright (c) 2014-2016 by Donal K. Fellows
# Copyright (c) 2014-2015 by Kevin B. Kenny
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
................................................................................
#
# Public properties:
#	none

oo::class create TclCompiler {
    superclass llvmEntity
    variable bytecode cmd func quads paramTypes returnType vtypes variables
    variable m b pc errorCode
    variable bytecodeVars namespace

    constructor {} {
	next
	namespace import \
	    ::quadcode::nameOfType \
	    ::quadcode::typeOfLiteral \
................................................................................
	    ::quadcode::dataType::mightbea
	namespace eval tcl {
	    namespace eval mathfunc {
		proc literal {descriptor} {
		    string equal [lindex $descriptor 0] "literal"
		}
		proc refType {type} {

		    uplevel 1 [list my ReferenceType? $type]


		}
		proc failType {type} {
		    uplevel 1 [list my FailureType? $type]
		}
		proc operandType {operand} {
		    uplevel 1 [list my OperandType $operand]
		}
		proc consumed {var search} {
		    uplevel 1 [list my IsConsumed $var $search]
		}



	    }
	}
    }

    # TclCompiler:ByteCode --
    #
    #	Sets the bytecode description dictionary that this compiler code
................................................................................
	#

	set rtype [nameOfType $returnType]
	set returntype [Type $rtype]

	##############################################################
	#
	# Construct the function signature type, and hence the function object
	#

	set ft [llvmtcl FunctionType $returntype $argl 0]
	dict set bytecode signature [list $rtype $argn]

	set realname [list tcl $cmd $argn]

	# Check if the function already exists; that indicates serious
	# problems in the caller.
	if {[$m function.defined $realname]} {
	    return -code error "duplicate $cmd"
	}

	set func [$m function.create $realname $ft]

	return $func
    }
 
    # TclCompiler:Compile --
    #
    #	Generate the body for the function that we are transforming the Tcl
    #	code into.
................................................................................

	##############################################################
	#
	# Create builder, basic blocks and error code context
	#

	set b [$m builder]



	$func setAsCurrentDebuggingScope

	lassign [my GenerateBasicBlocks $quads] blockDict ipathDict pred
	array set block $blockDict
	array set ipath $ipathDict

	# NB: block(-1) is the function entry block. It's supposed to be
	# almost entirely optimized out.
	$block(-1) build-in $b
	$b @location 1 0
	set errorCode [$b alloc int "tcl.errorCode"]
	set curr_block $block(-1)
	set 0 [$b int 0]

	##############################################################
	#
	# Create stubs for variables in LLVM; because of loops, uses may occur
................................................................................
		if {[lindex $quads $origin 0] eq "param"} {
		    set idx [lsearch $bytecodeVars \
			[list "scalar arg" $formalname]]
		    if {$idx < 0} {
			return -code error \
			    "unmapped formal variable name: $formalname ($name)"
		    }

		    $func param $idx $formalname






		} else {
		    # Not a parameter; set up the debugging metadata as a
		    # local variable.
		    $func localvar [lindex $name 1] $type
		}
	    }

	    # This is awful, but these *must* be unique things to replace, so
	    # we make them be individual loads of a memory location that has
	    # never been written to. This prevents them from being coalesced
	    # too early by the constant management engine; merely using an
................................................................................
	##############################################################
	#
	# Convert Tcl parse output, one instruction at a time.
	#

	set pc -1
	set ERROR_TEMPLATE "\n    (compiling \"%s\" @ pc %d: %s)"







	foreach l $quads {
	    incr pc
	    if {[info exists block($pc)]} {
		$block($pc) build-in $b
		set curr_block $block($pc)
		set consumed {}
	    }
................................................................................

	    ##########################################################
	    #
	    # Issue the code for a single quadcode instruction.
	    #

	    try {

	    switch -exact -- [lindex $l 0 0] {




		"confluence" - "entry" - "unset" {
		    # Do nothing; required for SSA computations only
		}












		"@debug-value" {
		    # Debugging directive mapping value in quadcode to Tcl
		    # source variable
		    lassign $l opcode srcvar value
		    if {$value eq "Nothing"} {
			my AnnotateAssignment [lindex $srcvar 1] \
			    [$b undef void*]
		    } else {
			my AnnotateAssignment [lindex $srcvar 1] \
			    [my LoadOrLiteral $value]
		    }




		}
		"param" {
		    lassign $l opcode tgt src
		    set idx [lindex $src 1]
		    set name [lindex $tgt 1]









		    set variables($tgt) [$func param $idx $name]




		    set type [my OperandType $tgt]

		    if {refType($type)} {
			$b printref $variables($tgt) "param:"
			$b addReference($type) $variables($tgt)
			$b assume [$b shared $variables($tgt)]
		    }
		}

























































































		"bitor" - "bitxor" - "bitand" - "lshift" - "rshift" -
		"add" - "sub" - "mult" - "uminus" - "land" - "lor" -
		"isBoolean" - "eq" - "neq" - "lt" - "gt" - "le" - "ge" -
		"streq" - "bitnot" - "result" - "strcase" -
		"strclass" - "strcmp" - "strfind" - "strlen" - "strmap" -
		"strmatch" - "strrfind" - "strtrim" - "returnOptions" {




		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b $opcode {*}$srcs $name]
		}











		"list" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    set types [split [my ValueTypes {*}$srcs] ,]
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b list $srcs $types $name]
		}
		"strindex" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    set srcs [my ConvertIndices 0 strlen 1]
		    my StoreResult $tgt [$b $opcode {*}$srcs $errorCode $name]




		}
		"strrange" - "strreplace" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    set srcs [my ConvertIndices 0 strlen 1 2]
		    my StoreResult $tgt [$b $opcode {*}$srcs $errorCode $name]


		}







		"regexp" - "listAppend" - "listConcat" - "listLength" -
		"listRange" - "listIn" - "listNotIn" - "dictIterStart" -
		"dictAppend" - "dictIncr" - "dictLappend" - "dictSize" -
		"div" - "expon" - "mod" - "not" {

		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b $opcode {*}$srcs $errorCode $name]


		}


		"returnCode" {
		    lassign $l opcode tgt
		    set name [my LocalVarName $tgt]



		    my StoreResult $tgt [$b packInt32 [$b load $errorCode] $name]
		}
		"initException" {
		    my IssueException $l
		}
		"setReturnCode" {
		    lassign $l opcode - src

		    $b store [$b getInt32 [my LoadOrLiteral $src]] $errorCode







		}
		"dictExists" {
		    my IssueDictExists $l
		}
		"dictGet" - "dictUnset" - "listIndex" {
		    set srcs [lassign $l opcode tgt srcObj]
		    set name [my LocalVarName $tgt]
		    if {[llength $srcs] == 1} {
			# Simple case
			set srcs [list $srcObj {*}$srcs]
			append opcode ( [my ValueTypes {*}$srcs] )
			set srcs [lmap s $srcs {my LoadOrLiteral $s}]
			my StoreResult $tgt [$b $opcode {*}$srcs $errorCode $name]

		    } else {
			# Need to construct the variadic path
			set vectortypes [lmap s $srcs {my ValueTypes $s}]
			set vector [$b buildVector $vectortypes \
				  [lmap s $srcs {my LoadOrLiteral $s}]]
			append opcode ( [my ValueTypes $srcObj] )
			set srcObj [my LoadOrLiteral $srcObj]
			my StoreResult $tgt [$b $opcode $srcObj $vector $errorCode $name]

			$b clearVector $srcs $vector $vectortypes
		    }



		}
		"dictSet" - "listSet" {
		    set srcs [lassign $l opcode tgt srcObj srcValue]
		    set name [my LocalVarName $tgt]
		    if {[llength $srcs] == 1} {
			# Simple case
			set srcs [list $srcObj {*}$srcs $srcValue]
			append opcode ( [my ValueTypes {*}$srcs] )
			set srcs [lmap s $srcs {my LoadOrLiteral $s}]
			my StoreResult $tgt [$b $opcode {*}$srcs $errorCode $name]

		    } else {
			# Need to construct the variadic path
			set vectortypes [lmap s $srcs {my ValueTypes $s}]
			set vector [$b buildVector $vectortypes \
				  [lmap s $srcs {my LoadOrLiteral $s}]]
			set srcs [list $srcObj $srcValue]
			append opcode ( [my ValueTypes {*}$srcs] )
			set srcs [lmap s $srcs {my LoadOrLiteral $s}]
			my StoreResult $tgt [$b $opcode {*}$srcs $vector $errorCode $name]

			$b clearVector $srcs $vector $vectortypes
		    }


		}

		"copy" {
		    lassign $l opcode tgt src
		    set value [my LoadOrLiteral $src]
		    set type [my OperandType $tgt]


		    if {refType($type)} {
			$b printref $value "copy:"
			$b addReference($type) $value

		    }
		    my StoreResult $tgt $value
		}
		"maptoint" {
		    lassign $l opcode tgt src map def
		    set map [lindex $map 1]
		    set def [lindex $def 1]
................................................................................
		    append opcode ( [my ValueTypes $src] )
		    set src [my LoadOrLiteral $src]
		    my StoreResult $tgt [$b $opcode $src $map $def $name]
		}
		"extractExists" - "extractMaybe" {
		    my IssueExtract $l
		}























		"free" {
		    lassign $l opcode tgt src
		    set type [my OperandType $src]
		    if {$src ni $consumed} {
			if {$type eq "VOID"} {
			    # VOID is trivial to free
			} elseif {refType($type)} {
			    $b printref $variables($src) "free:"





			    $b dropReference([my ValueTypes $src]) $variables($src)

			}
			lappend consumed $src
		    }
		}
		"exists" {
		    lassign $l opcode tgt src
		    set type [my OperandType $src]
		    if {$type eq "NEXIST"} {

			set value [Const false bool]
		    } elseif {!failType($type)} {

			set value [Const true bool]
		    } else {
			set value [$b exists [my LoadOrLiteral $src]]
		    }
		    my StoreResult $tgt $value
		}
		"jumpMaybe" {
................................................................................
		    lassign $l opcode tgt src
		    set tgt [lindex $tgt 1]
		    if {failType(operandType($src))} {
			set test [my Unlikely maybe [my LoadOrLiteral $src]]
			$b condBr $test $block($tgt) $ipath($pc)
		    } else {
			# Non-FAIL types never take the branch

			$b br $ipath($pc)
		    }
		}
		"jumpMaybeNot" {
		    lassign $l opcode tgt src
		    set tgt [lindex $tgt 1]
		    if {failType(operandType($src))} {
			set test [my Unlikely maybe [my LoadOrLiteral $src]]
			$b condBr $test $ipath($pc) $block($tgt)
		    } else {
			# Non-FAIL types always take the branch

			$b br $block($tgt)
		    }
		}
		"jumpTrue" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $src]
		    set tgt [lindex $tgt 1]
................................................................................
		    set test [$b $neq [my LoadOrLiteral $src] $0 test_$name]
		    $b condBr $test $ipath($pc) $block($tgt)
		}
		"jump" {
		    $b br $block([lindex $l 1 1])
		}
		"return" {
		    lassign $l opcode -> src
		    set val [my LoadOrLiteral $src]




		    set type [nameOfType $returnType]
		    if {refType($type)} {
			$b printref $val "ret:"
			if {literal($src)} {
			    $b addReference($type) $val
			}
		    }
		    $b ret $val

		}
		"returnException" {
		    # A VOID, a FAIL, a NEXIST, are all things that are not
		    # strings.
		    if {![mightbea $returnType $STRING]} {
			$b ret [Const true bool]
		    } else {
			set type [nameOfType $returnType]
			$b ret [$b nothing $type]
		    }
		}
		"phi" {
		    set values {}
		    set sources {}
		    foreach {var origin} [lassign $l opcode tgt] {
			set spc [lindex $origin end]
			while {![info exists block($spc)]} {incr spc -1}
			set s $block($spc)
................................................................................
			    continue
			}
			lappend sources $s
			lappend values [my LoadOrLiteral $var]
		    }
		    set name phi_[my LocalVarName $tgt]
		    set value [$b phi $values $sources $name]
		    my StoreResult $tgt $value



		}



		"invoke" {
		    set arguments [my IssueInvoke $l]









		    foreach aa $arguments {
			set arguments [lassign $arguments a]
			if {$a ni $arguments && consumed($a, $pc + 1)} {
			    lappend consumed $a
			}
		    }
		}















		"strcat" {
		    set srcs [lassign $l opcode tgt src1]
		    set name [my LocalVarName $tgt]
		    set type [my OperandType $src1]
		    set val [my LoadOrLiteral $src1]
		    if {!refType($type)} {
			set result [$b stringify($type) $val $name]
................................................................................
		}
		"foreachStart" {
		    set srcs [lassign $l opcode tgt assign]
		    set listtypes [lmap s $srcs {my ValueTypes $s}]
		    set lists [$b buildVector $listtypes \
			    [lmap s $srcs {my LoadOrLiteral $s}]]
		    set result [$b foreachStart [lindex $assign 1] $lists $errorCode]



		    my StoreResult $tgt $result
		}
		"unshareList" -






		"foreachIter" - "foreachAdvance" - "foreachMayStep" -
		"dictIterKey" - "dictIterValue" - "dictIterDone" -
		"dictIterNext" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    set result [$b $opcode [my LoadOrLiteral $src] $name]
		    my StoreResult $tgt $result
		}
		"widenTo" {
		    lassign $l opcode tgt src
		    my IssueWiden $l
		}






		"initIfNotExists" {
		    my IssueValueInit $l
		}
		"throwIfNotExists" {
		    set test [my IssueThrowIfNEXIST $l]
		    $b condBr $test $block($tgt) $ipath($pc)
		}
		"throwNotExists" {
		    lassign $l opcode tgt varname
		    set name [my LiteralValue $varname]
		    set msg "can't read \"$name\": no such variable"
		    set exn [list TCL LOOKUP VARNAME $name]
		    set msg [Const $msg STRING]
		    set exn [Const $exn STRING]
		    $b initException $exn $msg $errorCode
		    $b br $block([lindex $tgt 1])
		}
		"instanceOf" - "narrowToType" {
		    lassign $l opcode tgt src
		    lassign $opcode opcode - type
		    set name [my LocalVarName $tgt]
		    set type2 [my OperandType $src]
		    if {$type eq $type2} {
			if {$opcode eq "instanceOf"} {
................................................................................
			} else {
			    set value [my LoadOrLiteral $src]
			    if {refType($type)} {
				$b printref $value "trivial-narrow:"
				$b addReference($type) $value
			    }
			}



		    } else {
			set type [string map {" " _} $type]
			append opcode . $type ( $type2 )
			set value [$b $opcode [my LoadOrLiteral $src] $name]
		    }
		    my StoreResult $tgt $value
		}
		"checkArithDomain" {
		    lassign $l opcode tgt src opname
		    lassign $opcode opcode - type
		    set tgt [lindex $tgt 1]
		    set msg [format \
			"can't use non-numeric string as operand of \"%s\"" \
			[my LiteralValue $opname]]
		    set exn "ARITH DOMAIN {non-numeric string}"
		    set type2 [my OperandType $src]
		    if {$type eq $type2} {
			$b br $ipath($pc)
		    } else {
			append opcode . $type ( [my OperandType $src] )
			set msg [Const $msg STRING]
			set exn [Const $exn STRING]
			set jmp [my Unlikely $opcode [my LoadOrLiteral $src] \
				$msg $exn $errorCode "parse.failed"]
			$b condBr $jmp $block($tgt) $ipath($pc)
		    }
		}
		"throwArithDomainError" {
		    lassign $l opcode tgt src opname
		    set msg [format \
			"can't use non-numeric string as operand of \"%s\"" \
			[my LiteralValue $opname]]
		    set exn "ARITH DOMAIN {non-numeric string}"
		    set msg [Const $msg STRING]
		    set exn [Const $exn STRING]
		    $b initException $exn $msg $errorCode
		    $b br $block([lindex $tgt 1])
		}

		"checkFunctionParam" - "narrowToParamType" -

		"narrowToNotParamType" {
		    # These are supposed to never reach here; assert it
		    return -code error \
			"opcode '[lindex $opcode 0]' sent to code issuer"
		}

		default {
		    return -code error "$cmd: unknown opcode '$opcode' in '$l'"
		}
	    }
	    } on error {msg opts} {
		dict append opts -errorinfo \
		    [format $ERROR_TEMPLATE $cmd $pc $l]
		return -options $opts $msg
	    } on return {msg opts} {
................................................................................
    #	entry" block that is reserved for the code issuer). The second
    #	dictionary says which block contains the next instruction (necessary
    #	for forking jumps); i.e., the Instruction Path. The third says which
    #	blocks are the predecessors of the current block.

    method GenerateBasicBlocks {quads} {
	# Instructions that will always jump.
	set JUMPS {jump throwNotExists throwArithDomainError}


	# Instructions that can go to either the next instruction OR the named
	# instruction.
	set FORKJUMPS {
	    jumpFalse jumpTrue
	    jumpMaybe jumpMaybeNot
	    checkArithDomain
	    throwIfNotExists
	}
	# Instructions that terminate execution of the function.
	set EXITS {return returnException}

	##############################################################
	#
	# Create basic blocks
	#

	set block(-1) [$func block]
................................................................................
	set idict {}
	foreach pc [array names ipath] {
	    dict set idict $pc $block($ipath($pc))
	}

	list [array get block] $idict $pred
    }
 





















































































    # TclCompiler:IssueInvoke --
    #
    #	Generate the code for invoking another Tcl command. Must only be
    #	called from the 'compile' method.
    #
    # Parameters:


    #	operation -
    #		The quadcode descriptor for the instruction.
    #
    # Results:
    #	The set of arguments that might have been consumed in the operation
    #	(for cleanup by the caller of this method).

    method IssueInvoke {operation} {
	set arguments [lassign $operation opcode tgt origname]
	set vname [my LocalVarName $tgt]
	set BASETYPES {ZEROONE INT DOUBLE NUMERIC STRING}


	# Is this a literal name for a function we already know the signature
	# of? If so, we can use a direct call. To work this out, we need to
	# resolve the command within the namespace context of the procedure.

	if {literal($origname)} {
	    # Resolve the name.
	    set name [my FuncName [lindex $origname 1]]
	    set fullname [list tcl $name [lmap s $arguments {my ValueTypes $s}]]
	    if {[$m function.defined $fullname]} {
		set called [[$m function.get $fullname] ref]
		set argvals [lmap arg $arguments {my LoadOrLiteral $arg}]
		set result [$b call $called $argvals $vname]


		# FIXME: Assumes that called commands produce either TCL_OK or
		# TCL_ERROR. That Ain't Necessarily So...
		set ts [lmap t $BASETYPES {Type $t?}]
		if {[TypeOf $result] in $ts} {
		    set ec [$b cast(uint) [$b maybe $result]]
		    $b store $ec $errorCode
		} elseif {[Type [TypeOf $result]?] eq [Type [my ValueTypes $tgt]]} {
		    # Managed to prove non-failure in this case...
		    set result [$b just $result]
		}

		my StoreResult $tgt $result
		return {}



	    }
	    set origname [list literal $name]
	}

	set arguments [list $origname {*}$arguments]
	set argvals [lmap s $arguments {my LoadOrLiteral $s}]

	# Dynamic dispatch via direct call is OK, *provided* someone has
	# fetched the function reference for us.

	if {[TypeOf [lindex $argvals 0]] ne [Type STRING]} {
	    set argvals [lassign $argvals called]
	    set result [$b call $called $argvals $vname]


	    # FIXME: Assumes that called commands produce either TCL_OK or
	    # TCL_ERROR. That Ain't Necessarily So...


















	    set ts [lmap t $BASETYPES {Type $t?}]
	    if {[TypeOf $result] in $ts} {






		set ec [$b cast(uint) [$b maybe $result]]
		$b store $ec $errorCode
	    }





	    my StoreResult $tgt $result
	    return {}
	}

	# Must dispatch via the Tcl command API. This is the slowest option
	# with the least type inference possible (everything goes as a
	# STRING) but it is a reasonable fallback if nothing else works.



	set types [lmap s $arguments {my ValueTypes $s}]




	set vector [$b buildVector $types $argvals]
	# TODO: Pass in the resolution context (namespace ref).
	# TODO: Make the invoke do something sensible with that namespace
	# reference (if provided).


	my StoreResult $tgt [$b invoke $vector $errorCode $vname]








































	$b clearVector $arguments $vector $types
	return $arguments
    }
 
    # TclCompiler:IssueWiden --
    #
    #	Generate the code for widening the type of a value. Must only be
................................................................................
	set srctype [my ValueTypes $src]
	set tgttype [lindex $opcode 2]
	if {$tgttype eq ""} {
	    set tgttype [my OperandType $tgt]
	}
	if {$srctype in {"VOID" "NOTHING" "NEXIST"}} {
	    switch -glob -- $tgttype {




		"FAIL *" - "NEXIST *" {
		    set t [lrange $tgttype 1 end]
		    set value [$b nothing $t $name]
		}
		"STRING" - "EMPTY" {
		    set value [my LoadOrLiteral "literal {}"]
		}
		default {
		    error "casting from VOID to $tgttype"


		}
	    }
	} elseif {[lindex $src 0] eq "literal" && "STRING" in $tgttype} {
	    set value [Const [lindex $src 1] STRING]
	} else {
	    set value [my LoadOrLiteral $src]
	    set value [my WidenedValue $value $srctype $tgttype $name]
	}
	if {[Type $tgttype] eq [Type [TypeOf $value]?]} {
	    set value [$b just $value]
	}
	if {refType($tgttype)} {
	    $b printref $value "widen:"
	    $b addReference($tgttype) $value

	}
	my StoreResult $tgt $value
	return
    }






















































    method WidenedValue {value srctype tgttype {name ""}} {
	if {$srctype eq $tgttype} {
	    return $value
	}
	if {$srctype eq "ZEROONE" && "ZEROONE" ni $tgttype} {
	    set value [$b cast(BOOLEAN) $value]
	    set srctype INT
	}













	# IMPURE to IMPURE - Copy the string value, and promote the
	# inner value

	if {[lindex $tgttype 0] eq "IMPURE" 
	    && [lindex $srctype 0] eq "IMPURE"} {
	    set itgttype [lrange $tgttype 1 end]
	    set isrctype [lrange $srctype 1 end]
	    set ivalue [my WidenedValue [$b extract $value 1] \
			    $isrctype $itgttype]
	    set svalue [$b extract $value 0]
	    $b addReference(STRING) $svalue
	    set value [$b undef [Type $tgttype]]
	    set value [$b insert $value $svalue 0]
	    set value [$b insert $value $ivalue 1 $name]
	} elseif {[lindex $srctype 0] eq "IMPURE" && "STRING" in $tgttype} {
	    set value [$b stringifyImpure $value $name]
	} elseif {[regexp {^IMPURE (.*)$} $tgttype -> innertype]} {
	    set value [$b packImpure($innertype) \
			   [my WidenedValue $value $srctype $innertype] \

			   $name]



	} elseif {refType($tgttype) != refType($srctype)} {

	    # TODO: handle other kinds of reference types


	    set value [$b stringify($srctype) $value $name]
	} elseif {$tgttype eq "DOUBLE"} {
	    set value [$b cast(DOUBLE) $value $name]
	} elseif {$tgttype eq "NEXIST $srctype"} {
	    set value [$b just $value $name]
	} elseif {$tgttype eq "NUMERIC"} {
	    if {$srctype eq "DOUBLE"} {
		set value [$b packNumericDouble $value $name]
	    } else {
		set value [$b packNumericInt $value $name]
	    }









	}
	return $value
    }
 
    # TclCompiler:IssueDictExists --
    #
    #	Generate the code for testing whether an element of a dictionary
................................................................................
	if {$type eq "NEXIST"} {
	    set value [my LoadOrLiteral $def]
	} elseif {!failType($type)} {
	    set value [my LoadOrLiteral $src]
	} else {
	    # Nope; do it at run-time.
	    set test [$b exists [my LoadOrLiteral $src]]

	    set value [$b select [$b expect $test true] \
			   [$b unmaybe [my LoadOrLiteral $src]] \
			   [my LoadOrLiteral $def]]

	}

	set type [my OperandType $tgt]
	if {refType($type)} {
	    $b printref $value "init:"
	    $b addReference($type) $value
	}
................................................................................
    # Results:
    #	LLVM int1 that is true if the target of the branch is to be taken.

    method IssueThrowIfNEXIST {operation} {
	upvar 1 tgt tgtPC
	lassign $operation opcode branchTarget src varname



	set name [my LiteralValue $varname]
	set msg "can't read \"$name\": no such variable"
	set exn [list TCL LOOKUP VARNAME $name]
	set type [my OperandType $src]
	set tgtPC [lindex $branchTarget 1]

	# Types may make this simple.
	if {$type eq "NEXIST"} {
	    set msg [Const $msg STRING]
	    set exn [Const $exn STRING]
	    $b initException $exn $msg $errorCode
	    return [Const 1 bool]
	} elseif {!failType($type)} {
	    return [Const 0 bool]
	} else {
	    # Nope, do it at run-time.
	    set msg [Const $msg STRING]
	    set exn [Const $exn STRING]
	    return [my Unlikely existsOrError [my LoadOrLiteral $src] \
		    $msg $exn $errorCode]
	}

    }
 
    # TclCompiler:IssueException --
    #
    #	Generate the code for creating a general exception (e.g., from
    #	[error], [throw] or [return] with options. Must only be called from
    #	the 'compile' method.
................................................................................
	    if {$dlen == 1 && [dict exists $s2lit -errorcode]
		    && $maintype eq "STRING"
		    && literal([lindex $srcs 1]) && literal([lindex $srcs 2])
		    && [lindex $srcs 1 1] == 1 && [lindex $srcs 2 1] == 0} {
		# Really a throw
		set exn [Const [dict get $s2lit -errorcode] STRING]
		$b initException $exn $value $errorCode

		my StoreResult $tgt [$b nothing $maintype]
		return
	    }
	    if {$dlen == 0} {
		# Blank options; substitute a NULL
		set vals [linsert [lmap s [lrange $srcs 1 end] {
		    my LoadOrLiteral $s
		}] 0 [$b null STRING]]
	    }
	} elseif {[llength $srcs] == 1 && literal($src2)} {
	    my Warn "need to analyse options: %s" [lindex $src2 1]








	}

	# No special instruction sequence; pass it all through to the
	# lower-level code issuers.
	if {![info exist vals]} {
	    set vals [lmap s $srcs {my LoadOrLiteral $s}]
	}
	my StoreResult $tgt [$b $opcode {*}$vals $value $maintype \
		$errorCode $name]






































	return
    }
 
    # TclCompiler:Unlikely --
    #
    #	Issue a (boolean-returning) instruction and mark it as being expected
    #	to produce a false.
................................................................................
    #	operand -
    #		The operand to get the typecode of.
    #
    # Results:
    #	The typecode.

    method OperandType {operand} {
	nameOfType [typeOfOperand $vtypes $operand]




















    }

    # TclCompiler:ValueTypes --
    #
    #	Convert the sequence of arguments (to an opcode) into the type
    #	signature tuple to use with the name of the method in the Build class
    #	to enable automatic type widening.
................................................................................
    #
    # Results:
    #	The name.

    method LoadOrLiteral {desc} {
	if {[info exist variables($desc)]} {
	    return $variables($desc)




	}
	lassign $desc kind value
	if {$kind ne "literal"} {
	    return -code error "unsubstitutable argument: $desc"
	}
	set type [nameOfType [typeOfLiteral $value]]
	return [my LoadTypedLiteral $value $type]
    }


















    method LoadTypedLiteral {value type} {
	if {[lindex $type 0] eq "IMPURE"} {
	    set sval [my LoadTypedLiteral $value STRING]
	    set itype [lrange $type 1 end]
	    set tval [my LoadTypedLiteral $value $itype]
	    set result [$b insert [$b insert [$b undef [Type $type]] \
				       $sval 0] $tval 1]
	    $b addReference(STRING) $sval
	    if {refType($itype)} {
		$b addReference($itype) $tval
	    }
	    return $result
	} elseif {$type eq "DOUBLE"} {
	    return [ConstReal [Type $type] $value]
	} elseif {$type eq "ZEROONE"} {

	    return [Const [expr {$value}] bool]
	} elseif {$type in {"INT" "ENTIER"}} {
	    return [$b int [expr {entier($value)}]]
	} elseif {$type in {"STRING" "EMPTY"}} {
	    set result [Const $value STRING]
	    $b assume [$b shared $result]
	    return $result
	} elseif {$type eq "ZEROONE BOOLEAN"} {
	    set result1 [Const $value STRING]
	    $b assume [$b shared $result1]
	    set result2 [Const [string is true $value] bool]
	    return [$b insert [$b insert [$b undef BOOLWORD] \
		    $result2 BOOLWORD.bool] $result1 BOOLWORD.word]
	} else {
	    return -code error \
		"unhandled type for literal \"${value}\": \"$type\""
	}
    }

    # TclCompiler:StoreResult --
................................................................................
    #	trivially unique from one another.)
    #
    # Parameters:
    #	desc -	The descriptor of the variable that the value will be written
    #		to.
    #	value -	The LLVM value reference to the value to place in the variable
    #		named by the 'desc' argument.






    #
    # Results:
    #	None.

    method StoreResult {desc value} {



	if {[info exist variables($desc)]} {
	    if {[TypeOf $variables($desc)] ne [TypeOf $value]} {
















		return -code error [format \
			"type mismatch: variable {%s} of type '%s' but was assigned value of type '%s'" \
			$desc [PrintTypeToString [TypeOf $variables($desc)]] \
			[PrintTypeToString [TypeOf $value]]]
	    }
	    ReplaceAllUsesWith $variables($desc) $value
	}
................................................................................
    #	Boolean, true if the type is a reference type.

    method ReferenceType? {type} {
	if {[string is entier -strict $type]} {
	    set type [nameOfType $type]
	}
	foreach piece $type {
	    if {$piece in {IMPURE DICTITER EMPTY STRING ENTIER BOOLWORD BOOLEAN}} {
		return 1
	    }
	}
	return 0
    }

    # TclCompiler:FailureType? --
................................................................................
	    switch [lindex $quads $search 0] {
		"free" {
		    if {[lindex $quads $search 2] eq $var} {
			return $search
		    }
		}
		"jump" - "jumpFalse" - "jumpTrue" - "return" -
		"jumpMaybe" - "jumpMaybeNot" - "returnException" {
		    return 0
		}
		default {
		    if {$var in [lindex $quads $search]} {
			return 0
		    }
		}
................................................................................
		break
	    }
	}
	if {$worthMapping} {
	    foreach indexPosition $args {
		set index [lindex $s2 $indexPosition 1]
		if {$index eq "end"} {
		    lset s2 $indexPosition "literal 0"
		    if {![info exist length]} {
			set length [$b ${lengthOp}(STRING) [lindex $s3 0]]
		    }
		    lset s3 $indexPosition $length
		} elseif {[string match "end*" $index]} {
		    lset s2 $indexPosition "literal 0"
		    if {![info exist length]} {
			set length [$b ${lengthOp}(STRING) [lindex $s3 0]]
		    }
		    set delta [list literal [string range $index 3 end]]



		    lset s3 $indexPosition \
			[$b add(INT,INT) $length [my LoadOrLiteral $delta]]
		}

	    }
	}
	append opcode ( [my ValueTypes {*}$s2] )
	return $s3
    }

    # TclCompiler:LiteralValue --
................................................................................
    # Parameters:
    #	none
    #
    # Results:
    #	The LLVM function reference that we have generated. Note that this
    #	will be an unoptimised function at this stage.


    method compile {} {

	my Compile $quadcode





    }

    # TclInterproceduralCompiler:generateThunk --
    #
    #	Generate the binding into Tcl of the function that we transformed the
    #	procedure into.
    #
................................................................................
    #		The API binding class instance.
    #
    # Results:
    #	The function reference (i.e., instance of Function class) for the
    #	binding function. (Not the bound function, which this class made.)

    method generateThunk {thunkBuilder} {





	$thunkBuilder thunk $cmd $bytecode $func
    }

    # TclInterproceduralCompiler:printTypedQuads --
    #
    #	Print the sequence of typed quadcodes that the type inference engine
    #	has transformed the procedure into.
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







|







 







|







 







>
|
>
>










>
>
>







 







|


|

<
<
>







>







 







>
>
>









|







 







>
|
>
>
>
>
>
>



|







 







>
>
>
>
>
>
>







 







>

>
>
>
>
|


>
>
>
>
>
>
>
>
>
>
>
>


|
<
<
<
<
<
<
<
<
>
>
>
>





>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
>

|
|
|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|

|
|
<
>
>
>
>






>
>
>
>
>
>
>
>
>
>
>











|
>
>
>
>





|
>
>
|
>
>
>
>
>
>
>



|
>




|
>
>
|
>
>

|

>
>
>
|






>
|
>
>
>
>
>
>
>












|
>







|
>


>
>
>









|
>








|
>


>
>
|
>
|



>
>

<

>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








>
>
>
>
>
|
>








>


>







 







>











>







 







|

>
>
>
>







|
>
|
<
<
<
<
|
<
<
<
|
<







 







|
>
>
>
|
>
>
>

|
>
>
>
>
>
>
>
>
>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>


|
>
>
>
>
>
>












>
>
>
>
>
>



<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
|






|







 







|
>
>





<
<


|







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






>
>







|
|


>








|



|
>
|
<
|
|
|
|
<
<
<
<

|
<
<
>
>
>

<










|
>
|
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>
|
<

|
>
>
>
>
|
<
|

<
<
<
>
>


>
>
>
>

<
<
<
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
|







|
>
>


<
<


|

|
<
<

<

>





>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








>
>
>
>
>
>
>
>
>
>
>
>




|
|


|

|
|
<
<
<



<
|
>
|
>
>
>

>
|
>
>



<
<






>
>
>
>
>
>
>
>
>







 







>


<
>







 







>
>

|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
>







 







>
|









|
>
>
>
>
>
>
>
>









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|
<
<
<
<
<
<


<
>







<
<
<
<
<
<







 







>
>
>
>
>
>




|
>
>
>

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







|







 







|



|

|



|
>
>
>
|
|
<
>







 







<

>
|
>
>
>
>
>







 







>
>
>
>
>







 







>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
..
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
...
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
...
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
...
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
...
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
...
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
...
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
...
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
...
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
...
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
...
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
...
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
....
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
....
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
....
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609

1610
1611
1612
1613
1614
1615
1616
1617
....
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643















1644
1645

1646
1647
1648
1649
1650
1651
1652
1653
....
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
....
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
....
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918






1919
1920

1921
1922
1923
1924
1925
1926
1927
1928






1929
1930
1931
1932
1933
1934
1935
....
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
....
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
....
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
....
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150

2151
2152
2153
2154
2155
2156
2157
2158
....
2230
2231
2232
2233
2234
2235
2236

2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
....
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
....
2284
2285
2286
2287
2288
2289
2290
2291
2292
# compile.tcl --
#
#	Engine that handles compiling and issuing code for a single Tcl
#	procedure. Note that this needs to be done within the context of an
#	LLVM module (which is approximately the same concept as a compilation
#	unit in a language like C).
#
# Copyright (c) 2014-2017 by Donal K. Fellows
# Copyright (c) 2014-2015 by Kevin B. Kenny
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
................................................................................
#
# Public properties:
#	none

oo::class create TclCompiler {
    superclass llvmEntity
    variable bytecode cmd func quads paramTypes returnType vtypes variables
    variable m b pc errorCode currentline currentprocrelline currentscript
    variable bytecodeVars namespace

    constructor {} {
	next
	namespace import \
	    ::quadcode::nameOfType \
	    ::quadcode::typeOfLiteral \
................................................................................
	    ::quadcode::dataType::mightbea
	namespace eval tcl {
	    namespace eval mathfunc {
		proc literal {descriptor} {
		    string equal [lindex $descriptor 0] "literal"
		}
		proc refType {type} {
		    expr {
			[uplevel 1 [list my ReferenceType? $type]]
			&& "CALLFRAME" ni $type
		    }
		}
		proc failType {type} {
		    uplevel 1 [list my FailureType? $type]
		}
		proc operandType {operand} {
		    uplevel 1 [list my OperandType $operand]
		}
		proc consumed {var search} {
		    uplevel 1 [list my IsConsumed $var $search]
		}
		proc callframe {operand} {
		    uplevel 1 [list my IsCallFrame $operand]
		}
	    }
	}
    }

    # TclCompiler:ByteCode --
    #
    #	Sets the bytecode description dictionary that this compiler code
................................................................................
	#

	set rtype [nameOfType $returnType]
	set returntype [Type $rtype]

	##############################################################
	#
	# Construct the function signature type and the function object.
	#

	set ft [FunctionType $returntype $argl 0]
	dict set bytecode signature [list $rtype $argn]


	set realname [my GenerateFunctionName $cmd typecodes $paramTypes]
	# Check if the function already exists; that indicates serious
	# problems in the caller.
	if {[$m function.defined $realname]} {
	    return -code error "duplicate $cmd"
	}

	set func [$m function.create $realname $ft]
	$func private
	return $func
    }
 
    # TclCompiler:Compile --
    #
    #	Generate the body for the function that we are transforming the Tcl
    #	code into.
................................................................................

	##############################################################
	#
	# Create builder, basic blocks and error code context
	#

	set b [$m builder]
	if {[dict exists $bytecode sourcefile]} {
	    $m debug file [dict get $bytecode sourcefile]
	}
	$func setAsCurrentDebuggingScope

	lassign [my GenerateBasicBlocks $quads] blockDict ipathDict pred
	array set block $blockDict
	array set ipath $ipathDict

	# NB: block(-1) is the function entry block. It's supposed to be
	# almost entirely optimized out.
	$block(-1) build-in $b
	$b @location 0
	set errorCode [$b alloc int "tcl.errorCode"]
	set curr_block $block(-1)
	set 0 [$b int 0]

	##############################################################
	#
	# Create stubs for variables in LLVM; because of loops, uses may occur
................................................................................
		if {[lindex $quads $origin 0] eq "param"} {
		    set idx [lsearch $bytecodeVars \
			[list "scalar arg" $formalname]]
		    if {$idx < 0} {
			return -code error \
			    "unmapped formal variable name: $formalname ($name)"
		    }
		    if {[catch {
			$func param $idx $formalname
		    }]} {
			# Not actually a parameter, because of default
			# arguments; set up the debugging metadata as a local
			# variable.
			$func localvar $formalname $type
		    }
		} else {
		    # Not a parameter; set up the debugging metadata as a
		    # local variable.
		    $func localvar $formalname $type
		}
	    }

	    # This is awful, but these *must* be unique things to replace, so
	    # we make them be individual loads of a memory location that has
	    # never been written to. This prevents them from being coalesced
	    # too early by the constant management engine; merely using an
................................................................................
	##############################################################
	#
	# Convert Tcl parse output, one instruction at a time.
	#

	set pc -1
	set ERROR_TEMPLATE "\n    (compiling \"%s\" @ pc %d: %s)"
	set phiAnnotations {}
	set theframe {}
	set thevarmap {}
	set syntheticargs {}
	set currentline 0
	set currentprocrelline 0
	set currentscript {}
	foreach l $quads {
	    incr pc
	    if {[info exists block($pc)]} {
		$block($pc) build-in $b
		set curr_block $block($pc)
		set consumed {}
	    }
................................................................................

	    ##########################################################
	    #
	    # Issue the code for a single quadcode instruction.
	    #

	    try {
	    $b @location $currentline
	    switch -exact -- [lindex $l 0 0] {
		"entry" {
		    lassign [my IssueEntry $l] \
			theframe thevarmap syntheticargs
		}
		"confluence" - "unset" {
		    # Do nothing; required for SSA computations only
		}
		"@debug-file" {
		}
		"@debug-line" {
		    lassign $l opcode - srcfrom
		    lassign [lindex $srcfrom 1] currentline currentprocrelline
		}
		"@debug-context" {
		}
		"@debug-script" {
		    lassign $l opcode - srcscript
		    set currentscript [lindex $srcscript 1]
		}
		"@debug-value" {
		    # Debugging directive mapping value in quadcode to Tcl
		    # source variable; except we don't do that any more.








		    # Instead, a general "assign to something that looks like
		    # a variable" is good enough anyway, and that is handled
		    # in TclCompiler:StoreResult.
		    my Warn "unexpected @debug-value opcode at ${cmd}:$pc"
		}
		"param" {
		    lassign $l opcode tgt src
		    set idx [lindex $src 1]
		    set name [lindex $tgt 1]
		    set type [my OperandType $tgt]
		    set ftype [GetElementType [$func type]]
		    if {$idx >= [CountParamTypes $ftype]} {
			set defaultdict [dict get $bytecode argumentDefaults]
			set defaultvalue [lindex $defaultdict $idx 2]
			my Warn "default injection for parameter %d of '%s'; injecting '%s'" \
			    [expr {$idx + 1}] [GetValueName [$func ref]] $defaultvalue
			set var [my LoadTypedLiteral $defaultvalue $type]
		    } else {
			set var [$func param $idx $name]
		    }
		    set variables($tgt) $var
		    if {[regexp {^IMPURE } $type]} {
			set var [$b stringifyImpure $var]
			set type STRING
		    }
		    if {refType($type)} {
			$b printref $var "param:"
			$b addReference($type) $var
			$b assume [$b shared $var]
		    }
		}
		"moveToCallFrame" {
		    set mapping [lassign $l opcode tgt src]
		    if {callframe($src)} {
			foreach {name value} $mapping {
			    set name [lindex $name 1]
			    set var [dict get $thevarmap $name]
			    if {$value ne "Nothing"} {
				set op frame.store([my ValueTypes $value])
				set value [my LoadOrLiteral $value]
				$b $op $value $theframe $var $name
			    } else {
				$b frame.unset $theframe $var $name
			    }
			}
		    }
		    my StoreResult $tgt [my LoadOrLiteral $src]
		}
		"retrieveResult" {
		    lassign $l opcode tgt src
		    if {[my ValueTypes $src] eq "CALLFRAME"} {
			set value [$b undef NOTHING]
		    } elseif {"CALLFRAME" in [my ValueTypes $src]} {
			set value [$b frame.value [my LoadOrLiteral $src]]
		    } else {
			set value [my LoadOrLiteral $src]
			my Warn "retrieveResult from non-callframe"
		    }
		    my StoreResult $tgt $value
		}
		"extractCallFrame" {
		    lassign $l opcode tgt src
		    if {callframe($src)} {
			set value [my LoadOrLiteral $src]
			if {[my ValueTypes $src] ne "CALLFRAME"} {
			    set name [my LocalVarName $tgt]
			    set value [$b frame.frame $value $name]
			}
		    } else {
			set value $theframe
		    }
		    my StoreResult $tgt $value
		}
		"moveFromCallFrame" {
		    lassign $l opcode tgt src varname
		    if {callframe($src)} {
			set name [my LocalVarName $tgt]
			set vname [lindex $varname 1]
			set var [dict get $thevarmap $vname]
			my StoreResult $tgt \
			    [$b frame.load $theframe $var $vname $name]
		    }
		}
		"result" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes $src] )
		    set src [my LoadOrLiteral $src]
		    my StoreResult $tgt [$b $opcode $src $name]
		}
		"returnOptions" {
		    lassign $l opcode tgt src ecode
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b $opcode {*}$srcs $name]
		}
		"nsupvar" - "upvar" - "variable" {
		    set srcs [lassign $l opcode tgt src]
		    set localvar [lindex $srcs 0]
		    if {[lindex $localvar 0] ne "literal"} {
			error "local variable must be literal"
		    }
		    set name [my LocalVarName $tgt]
		    set var [dict get $thevarmap [lindex $localvar 1]]
		    set op [dict get {
			nsupvar  frame.bind.nsvar
			upvar	 frame.bind.upvar
			variable frame.bind.var
		    } $opcode]
		    append op ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    set res [$b $op {*}$srcs $var $theframe $errorCode $name]
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode \
			    [$b maybe [$b frame.value $res]]
		    }
		    my StoreResult $tgt $res
		}
		"bitor" - "bitxor" - "bitand" - "lshift" - "rshift" -
		"add" - "sub" - "mult" - "uminus" - "uplus" - "land" - "lor" -
		"isBoolean" - "eq" - "neq" - "lt" - "gt" - "le" - "ge" -
		"streq" - "bitnot" - "strcase" - "strclass" - "strcmp" -
		"strfind" - "strlen" - "strmap" - "strmatch" - "strrfind" -

		"strtrim" - "resolveCmd" - "arrayExists" - "directExists" -
		"arrayElementExists" - "directArrayExists" -
		"initArrayIfNotExists" - "extractScalar" - "extractArray" -
		"arraySet" - "arrayUnset" - "arrayGet" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b $opcode {*}$srcs $name]
		}
		"originCmd" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    set res [$b $opcode {*}$srcs $errorCode $name]
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $res]
		    }
		    my StoreResult $tgt $res
		}
		"list" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    set types [split [my ValueTypes {*}$srcs] ,]
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b list $srcs $types $name]
		}
		"strindex" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    set srcs [my ConvertIndices 0 strlen 1]
		    set res [$b $opcode {*}$srcs $errorCode $name]
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $res]
		    }
		    my StoreResult $tgt $res
		}
		"strrange" - "strreplace" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    set srcs [my ConvertIndices 0 strlen 1 2]
		    set res [$b $opcode {*}$srcs $errorCode $name]
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $res]
		    }
		    my StoreResult $tgt $res
		}
		"directGet" - "directSet" - "directAppend" - "directLappend" -
		"directLappendList" - "directUnset" -
		"directArrayGet" - "directArraySet" - "directArrayAppend" -
		"directArrayLappend" - "directArrayLappendList" -
		"directArrayUnset" - "directIsArray" - "directMakeArray" -
		"regexp" - "listAppend" - "listConcat" - "listLength" -
		"listRange" - "listIn" - "listNotIn" - "dictIterStart" -
		"dictAppend" - "dictIncr" - "dictLappend" - "dictSize" -
		"div" - "expon" - "mod" - "not" - "verifyList" -
		"dictGetOrNexist" - "dictSetOrUnset" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    set res [$b $opcode {*}$srcs $errorCode $name]
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $res]
		    }
		    my StoreResult $tgt $res
		}
		"returnCode" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes $src] )
		    my StoreResult $tgt \
			[$b $opcode [my LoadOrLiteral $src] \
			     [$b load $errorCode] $name]
		}
		"initException" {
		    my IssueException $l
		}
		"setReturnCode" {
		    lassign $l opcode - src
		    append opcode ( [my ValueTypes $src] )
		    $b $opcode [my LoadOrLiteral $src] $errorCode
		}
		"procLeave" {
		    set srcs [lassign $l opcode tgt]
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes {*}$srcs] )
		    set srcs [lmap s $srcs {my LoadOrLiteral $s}]
		    my StoreResult $tgt [$b $opcode {*}$srcs $errorCode $name]
		}
		"dictExists" {
		    my IssueDictExists $l
		}
		"dictGet" - "dictUnset" - "listIndex" {
		    set srcs [lassign $l opcode tgt srcObj]
		    set name [my LocalVarName $tgt]
		    if {[llength $srcs] == 1} {
			# Simple case
			set srcs [list $srcObj {*}$srcs]
			append opcode ( [my ValueTypes {*}$srcs] )
			set srcs [lmap s $srcs {my LoadOrLiteral $s}]
			set res [$b $opcode {*}$srcs $errorCode $name]
			my StoreResult $tgt $res
		    } else {
			# Need to construct the variadic path
			set vectortypes [lmap s $srcs {my ValueTypes $s}]
			set vector [$b buildVector $vectortypes \
				  [lmap s $srcs {my LoadOrLiteral $s}]]
			append opcode ( [my ValueTypes $srcObj] )
			set srcObj [my LoadOrLiteral $srcObj]
			set res [$b $opcode $srcObj $vector $errorCode $name]
			my StoreResult $tgt $res
			$b clearVector $srcs $vector $vectortypes
		    }
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $res]
		    }
		}
		"dictSet" - "listSet" {
		    set srcs [lassign $l opcode tgt srcObj srcValue]
		    set name [my LocalVarName $tgt]
		    if {[llength $srcs] == 1} {
			# Simple case
			set srcs [list $srcObj {*}$srcs $srcValue]
			append opcode ( [my ValueTypes {*}$srcs] )
			set srcs [lmap s $srcs {my LoadOrLiteral $s}]
			set res [$b $opcode {*}$srcs $errorCode $name]
			my StoreResult $tgt $res
		    } else {
			# Need to construct the variadic path
			set vectortypes [lmap s $srcs {my ValueTypes $s}]
			set vector [$b buildVector $vectortypes \
				  [lmap s $srcs {my LoadOrLiteral $s}]]
			set srcs [list $srcObj $srcValue]
			append opcode ( [my ValueTypes {*}$srcs] )
			set srcs [lmap s $srcs {my LoadOrLiteral $s}]
			set res [$b $opcode {*}$srcs $vector $errorCode $name]
			my StoreResult $tgt $res
			$b clearVector $srcs $vector $vectortypes
		    }
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $res]
		    }
		}
		"copy" - "expand" {
		    lassign $l opcode tgt src
		    set value [my LoadOrLiteral $src]
		    set type [my OperandType $tgt]
		    set name [my LocalVarName $tgt]
		    SetValueName $value $name
		    if {refType($type)} {

			$b addReference($type) $value
			$b printref $value "copy:"
		    }
		    my StoreResult $tgt $value
		}
		"maptoint" {
		    lassign $l opcode tgt src map def
		    set map [lindex $map 1]
		    set def [lindex $def 1]
................................................................................
		    append opcode ( [my ValueTypes $src] )
		    set src [my LoadOrLiteral $src]
		    my StoreResult $tgt [$b $opcode $src $map $def $name]
		}
		"extractExists" - "extractMaybe" {
		    my IssueExtract $l
		}
		"extractFail" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes $src] )
		    set src [my LoadOrLiteral $src]
		    my StoreResult $tgt [$b $opcode $src $name]
		}
		"purify" {
		    lassign $l opcode tgt src
		    set value [my LoadOrLiteral $src]
		    if {![regexp {^IMPURE} [my OperandType $src]]} {
			return -code error \
			    "Trying to purify something that is not impure"
		    }
		    set name [my LocalVarName $tgt]
		    set value [$b impure.value $value $name]
		    set type [my OperandType $tgt]
		    if {refType($type)} {
			$b addReference($type) $value
			$b printref $value "purify:"
		    }
		    my StoreResult $tgt $value
		}
		"free" {
		    lassign $l opcode tgt src
		    set type [my OperandType $src]
		    if {$src ni $consumed} {
			if {$type eq "VOID"} {
			    # VOID is trivial to free
			} elseif {refType($type)} {
			    $b printref $variables($src) "free:"
			    if {"ARRAY" in [my ValueTypes $src]} {
				# TRICKY POINT: need variable name to unset an array
				set name [Const [my LocalVarName $tgt] STRING]
				$b dropReference([my ValueTypes $src]) $variables($src) $name
			    } else {
				$b dropReference([my ValueTypes $src]) $variables($src)
			    }
			}
			lappend consumed $src
		    }
		}
		"exists" {
		    lassign $l opcode tgt src
		    set type [my OperandType $src]
		    if {$type eq "NEXIST"} {
			my Warn "in exists with NEXIST type"
			set value [Const false bool]
		    } elseif {!failType($type)} {
			my Warn "in exists with definitely existing type"
			set value [Const true bool]
		    } else {
			set value [$b exists [my LoadOrLiteral $src]]
		    }
		    my StoreResult $tgt $value
		}
		"jumpMaybe" {
................................................................................
		    lassign $l opcode tgt src
		    set tgt [lindex $tgt 1]
		    if {failType(operandType($src))} {
			set test [my Unlikely maybe [my LoadOrLiteral $src]]
			$b condBr $test $block($tgt) $ipath($pc)
		    } else {
			# Non-FAIL types never take the branch
			my Warn "in jumpMaybe with non-fail type"
			$b br $ipath($pc)
		    }
		}
		"jumpMaybeNot" {
		    lassign $l opcode tgt src
		    set tgt [lindex $tgt 1]
		    if {failType(operandType($src))} {
			set test [my Unlikely maybe [my LoadOrLiteral $src]]
			$b condBr $test $ipath($pc) $block($tgt)
		    } else {
			# Non-FAIL types always take the branch
			my Warn "in jumpMaybeNot with non-fail type"
			$b br $block($tgt)
		    }
		}
		"jumpTrue" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $src]
		    set tgt [lindex $tgt 1]
................................................................................
		    set test [$b $neq [my LoadOrLiteral $src] $0 test_$name]
		    $b condBr $test $ipath($pc) $block($tgt)
		}
		"jump" {
		    $b br $block([lindex $l 1 1])
		}
		"return" {
		    lassign $l opcode -> frame src
		    set val [my LoadOrLiteral $src]
		    if {"CALLFRAME" in [my ValueTypes $src]} {
			# The CALLFRAME does not leave
			set val [$b frame.value $val]
		    }
		    set type [nameOfType $returnType]
		    if {refType($type)} {
			$b printref $val "ret:"
			if {literal($src)} {
			    $b addReference($type) $val
			}
		    }
		    if {$theframe ne "" && ![IsNull $theframe]} {
			$b frame.release $theframe $syntheticargs
		    }




		    $b ret $val



		}

		"phi" {
		    set values {}
		    set sources {}
		    foreach {var origin} [lassign $l opcode tgt] {
			set spc [lindex $origin end]
			while {![info exists block($spc)]} {incr spc -1}
			set s $block($spc)
................................................................................
			    continue
			}
			lappend sources $s
			lappend values [my LoadOrLiteral $var]
		    }
		    set name phi_[my LocalVarName $tgt]
		    set value [$b phi $values $sources $name]
		    my StoreResult $tgt $value "phi"
		    if {[lindex $quads [expr {$pc+1}] 0 0] ne "phi"} {
			foreach {name value} $phiAnnotations {
			    my AnnotateAssignment $name $value
			}
			set phiAnnotations {}
		    }
		}
		"invoke" {
		    set arguments [my IssueInvoke $theframe $l]
		    foreach aa $arguments {
			set arguments [lassign $arguments a]
			if {$a ni $arguments && consumed($a, $pc + 1)} {
			    lappend consumed $a
			}
		    }
		}
		"invokeExpanded" {
		    set arguments [my IssueInvokeExpanded $theframe $l]
		    foreach aa $arguments {
			set arguments [lassign $arguments a]
			if {$a ni $arguments && consumed($a, $pc + 1)} {
			    lappend consumed $a
			}
		    }
		}
		"frameArgs" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    set opcode frame.args
		    append opcode ( [my ValueTypes $src] )
		    set val [my LoadOrLiteral $src]
		    set result [$b $opcode $val $theframe $name]
		    my StoreResult $tgt $result
		}
		"frameDepth" {
		    lassign $l opcode tgt
		    set name [my LocalVarName $tgt]
		    set result [$b frame.depth $theframe $name]
		    my StoreResult $tgt $result
		}
		"strcat" {
		    set srcs [lassign $l opcode tgt src1]
		    set name [my LocalVarName $tgt]
		    set type [my OperandType $src1]
		    set val [my LoadOrLiteral $src1]
		    if {!refType($type)} {
			set result [$b stringify($type) $val $name]
................................................................................
		}
		"foreachStart" {
		    set srcs [lassign $l opcode tgt assign]
		    set listtypes [lmap s $srcs {my ValueTypes $s}]
		    set lists [$b buildVector $listtypes \
			    [lmap s $srcs {my LoadOrLiteral $s}]]
		    set result [$b foreachStart [lindex $assign 1] $lists $errorCode]
		    if {"FAIL" in [my ValueTypes $tgt]} {
			my SetErrorLine $errorCode [$b maybe $result]
		    }
		    my StoreResult $tgt $result
		}
		"unshareList" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    append opcode ( [my ValueTypes $src] )
		    set result [$b $opcode [my LoadOrLiteral $src] $name]
		    my StoreResult $tgt $result
		}
		"foreachIter" - "foreachAdvance" - "foreachMayStep" -
		"dictIterKey" - "dictIterValue" - "dictIterDone" -
		"dictIterNext" {
		    lassign $l opcode tgt src
		    set name [my LocalVarName $tgt]
		    set result [$b $opcode [my LoadOrLiteral $src] $name]
		    my StoreResult $tgt $result
		}
		"widenTo" {
		    lassign $l opcode tgt src
		    my IssueWiden $l
		}
		"initArray" {
		    lassign $l opcode tgt
		    set name [my LocalVarName $tgt]
		    set result [$b $opcode $name]
		    my StoreResult $tgt $result
		}
		"initIfNotExists" {
		    my IssueValueInit $l
		}














		"instanceOf" - "narrowToType" {
		    lassign $l opcode tgt src
		    lassign $opcode opcode - type
		    set name [my LocalVarName $tgt]
		    set type2 [my OperandType $src]
		    if {$type eq $type2} {
			if {$opcode eq "instanceOf"} {
................................................................................
			} else {
			    set value [my LoadOrLiteral $src]
			    if {refType($type)} {
				$b printref $value "trivial-narrow:"
				$b addReference($type) $value
			    }
			}
		    } elseif {"NOTHING" in $type} {
			# Should be an unreachable path
			set value [$b undef $type]
		    } else {
			set type [string map {" " _} $type]
			append opcode . $type ( $type2 )
			set value [$b $opcode [my LoadOrLiteral $src] $name]
		    }
		    my StoreResult $tgt $value
		}

































		"initParamTypeException" -
		"instanceOfParamType" {
		    # These are supposed to never reach here; assert it
		    return -code error \
			"opcode '[lindex $opcode 0]' sent to code issuer"
		}

		default {
		    return -code error "$cmd: unknown opcode '[lindex $l 0 0]' in '$l'"
		}
	    }
	    } on error {msg opts} {
		dict append opts -errorinfo \
		    [format $ERROR_TEMPLATE $cmd $pc $l]
		return -options $opts $msg
	    } on return {msg opts} {
................................................................................
    #	entry" block that is reserved for the code issuer). The second
    #	dictionary says which block contains the next instruction (necessary
    #	for forking jumps); i.e., the Instruction Path. The third says which
    #	blocks are the predecessors of the current block.

    method GenerateBasicBlocks {quads} {
	# Instructions that will always jump.
	set JUMPS {
	    jump
	}
	# Instructions that can go to either the next instruction OR the named
	# instruction.
	set FORKJUMPS {
	    jumpFalse jumpTrue
	    jumpMaybe jumpMaybeNot


	}
	# Instructions that terminate execution of the function.
	set EXITS {return}

	##############################################################
	#
	# Create basic blocks
	#

	set block(-1) [$func block]
................................................................................
	set idict {}
	foreach pc [array names ipath] {
	    dict set idict $pc $block($ipath($pc))
	}

	list [array get block] $idict $pred
    }
 
    # TclCompiler:IssueEntry --
    #
    #	Generate the code for creating a callframe at the start of a function.
    #	Must only be called from the 'compile' method.
    #
    # Parameters:
    #	quad -	The 'entry' quadcode, including its parameters.
    #
    # Results:
    #	A triple of the callframe, the local variable mapping, and a list
    #	saying which elements in the callframe are synthetic (i.e., have no
    #	existing string representation) and need to be released on function
    #	exit.

    method IssueEntry {quad} {
	lassign $quad opcode tgt vars

	# When no frame is wanted
	if {$tgt eq {}} {
	    return [list [$b null CALLFRAME] {} {}]
	}

	# Store the fact that we must generate complex metadata for this
	# function/command, and the variable where this metadata will be
	# stored.
	if {![dict exists $bytecode procmeta]} {
	    dict set bytecode procmeta \
		[$m variable [list procmeta $cmd] Proc* [$b null Proc*]]
	    dict set bytecode localcache \
		[$m variable [list localcache $cmd] LocalCache* \
		     [$b null LocalCache*]]
	}

	# Build the argument list. First, we get the Tcl descriptors of the
	# arguments, their types, etc.
	set varmeta [dict get $bytecode variables]
	set argtypes {STRING}
	set arguments [list [list literal $cmd]]
	foreach vinfo $varmeta {
	    if {"arg" in [lindex $vinfo 0]} {
		set vname [list var [lindex $vinfo 1] [llength $arguments]]
		lappend arguments $vname
		lappend argtypes [my ValueTypes $vname]
	    }
	}

	# Patch in the extra variables discovered during quadcode analysis;
	# these are never arguments as Tcl always correctly puts those in the
	# original bytecode descriptor.
	set stdnames [lmap vinfo $varmeta {lindex $vinfo 1}]
	foreach v [lindex $vars 1] {
	    if {$v ni $stdnames} {
		lappend varmeta [list scalar $v]
	    }
	}
	dict set bytecode variables $varmeta

	# Now we allocate the storage for the argument list
	set argc [Const [llength $arguments]]
	set argv [$b alloc [Type array{Tcl_Obj*,[llength $arguments]}] argv]

	# Store the arguments in the argument list
	set cell [$b gep $argv 0 0]
	$b store [Const $cmd STRING] $cell
	set idx -1
	set drop 0
	foreach v $arguments t $argtypes {
	    if {[incr idx]} {
		set val [$b stringify($t) [$func param [expr {$idx-1}]]]
		$b store $val [$b gep $argv 0 $idx]
		lappend drop [expr {!refType($t)}]
	    }
	}

	# Create the stack frame
	set procmeta [dict get $bytecode procmeta]
	set localcache [dict get $bytecode localcache]
	lassign [$b frame.create $varmeta $argc $argv \
			[$b load $procmeta "proc.metadata"] \
			[$b load $localcache "proc.localcache"]] \
	    theframe thevarmap
	my StoreResult $tgt $theframe
	return [list $theframe $thevarmap $drop]
    }
 
    # TclCompiler:IssueInvoke --
    #
    #	Generate the code for invoking another Tcl command. Must only be
    #	called from the 'compile' method.
    #
    # Parameters:
    #	callframe -
    #		The callframe.
    #	operation -
    #		The quadcode descriptor for the instruction.
    #
    # Results:
    #	The set of arguments that might have been consumed in the operation
    #	(for cleanup by the caller of this method).

    method IssueInvoke {callframe operation} {
	set arguments [lassign $operation opcode tgt thecallframe origname]
	set vname [my LocalVarName $tgt]
	set BASETYPES {ZEROONE INT DOUBLE NUMERIC STRING}
	set resolved {}

	# Is this a literal name for a function we already know the signature
	# of? If so, we can use a direct call. To work this out, we need to
	# resolve the command within the namespace context of the procedure.

	if {literal($origname)} {
	    # Resolve the name.
	    set name [my FuncName [lindex $origname 1]]
	    set fullname [my GenerateFunctionName $name arguments $arguments]
	    if {[$m function.defined $fullname]} {
		set called [[$m function.get $fullname] ref]
		set argvals [lmap arg $arguments {my LoadOrLiteral $arg}]
		my IssueInvokeFunction $tgt $called $argvals $vname
		return {}
	    }

	    if {[dict exist $vtypes $tgt]} {
		set type [nameOfType [dict get $vtypes $tgt]]
		if {"FAIL" ni $type || "STRING" ni $type} {
		    my Warn "didn't find implementation of '$fullname'"




		}
	    }


	    # Don't need to pre-resolve command names if there's a callframe
	    if {!callframe($thecallframe)} {
		set resolved [my LoadOrLiteral [list literal $name]]
	    }

	}

	set arguments [list $origname {*}$arguments]
	set argvals [lmap s $arguments {my LoadOrLiteral $s}]

	# Dynamic dispatch via direct call is OK, *provided* someone has
	# fetched the function reference for us.

	if {[TypeOf [lindex $argvals 0]] ne [Type STRING]} {
	    set argvals [lassign $argvals called]
	    my IssueInvokeFunction $tgt $called $argvals $vname
	    return {}
	}



	# Must dispatch via the Tcl command API. This is the slowest option
	# with the least type inference possible (everything goes as a
	# STRING) but it is a reasonable fallback if nothing else works.

	my IssueInvokeCommand $tgt $resolved $arguments $argvals $vname
	return $arguments
    }

    method IssueInvokeFunction {tgt func arguments vname} {
	upvar 1 callframe callframe thecallframe thecallframe
	set BASETYPES {ZEROONE INT DOUBLE NUMERIC STRING}

	set result [$b call $func $arguments $vname]
	if {[my ValueTypes $tgt] eq "FAIL"} {
	    $b store $result $errorCode
	    my SetErrorLine $errorCode
	} else {
	    set ts [lmap t $BASETYPES {Type $t?}]
	    if {[TypeOf $result] in $ts} {
		$b store [$b extract $result 0] $errorCode
	    } elseif {[Type [TypeOf $result]?] eq [Type [my ValueTypes $tgt]]} {
		# Managed to prove non-failure in this case...
		set result [$b ok $result]
	    }
	    if {"FAIL" in [my ValueTypes $tgt]} {
		my SetErrorLine $errorCode [$b maybe $result]

	    }
	}

	if {callframe($thecallframe)} {
	    set result [$b frame.pack $callframe $result]
	}
	my StoreResult $tgt $result

    }




    method IssueInvokeCommand {tgt resolved arguments argvals vname} {
	upvar 1 callframe callframe thecallframe thecallframe

	set types [lmap s $arguments {my ValueTypes $s}]
	if {$resolved ne ""} {
	    # FIXME: this causes wrong "wrong # args" messages
	    set argvals [lreplace $argvals 0 0 $resolved]
	}
	set vector [$b buildVector $types $argvals]



	set result [$b invoke $vector \
			[expr {callframe($thecallframe)}] $callframe \
			$errorCode $vname]
	$b clearVector $arguments $vector $types
	# Result type is now FAIL STRING, always.
	my SetErrorLine $errorCode [$b maybe $result]
	if {callframe($thecallframe)} {
	    set result [$b frame.pack $callframe $result]
	}
	my StoreResult $tgt $result
    }

    # TclCompiler:IssueInvokeExpanded --
    #
    #	Generate the code for invoking another Tcl command with expansion.
    #	Must only be called from the 'compile' method.
    #
    # Parameters:
    #	callframe -
    #		The callframe.
    #	operation -
    #		The quadcode descriptor for the instruction.
    #
    # Results:
    #	The set of arguments that might have been consumed in the operation
    #	(for cleanup by the caller of this method).

    method IssueInvokeExpanded {callframe operation} {
	set arguments [lassign $operation opcode tgt thecallframe]
	set vname [my LocalVarName $tgt]
	set expandPositions [lmap s $arguments {
	    expr {"EXPANDED" in [my OperandType $s]}
	}]
	set argvals [lmap s $arguments {my LoadOrLiteral $s}]
	set types [lmap s $arguments {my ValueTypes $s}]
	set vector [$b buildVector $types $argvals]
	set flags [$b buildBitArray $expandPositions]
	set result [$b invokeExpanded $vector $flags $errorCode $vname]
	my SetErrorLine $errorCode [$b maybe $result]
	if {callframe($thecallframe)} {
	    set result [$b frame.pack $callframe $result]
	}
	my StoreResult $tgt $result
	$b clearVector $arguments $vector $types
	return $arguments
    }
 
    # TclCompiler:IssueWiden --
    #
    #	Generate the code for widening the type of a value. Must only be
................................................................................
	set srctype [my ValueTypes $src]
	set tgttype [lindex $opcode 2]
	if {$tgttype eq ""} {
	    set tgttype [my OperandType $tgt]
	}
	if {$srctype in {"VOID" "NOTHING" "NEXIST"}} {
	    switch -glob -- $tgttype {
		"FAIL *" {
		    set t [lrange $tgttype 1 end]
		    set value [$b fail $t "" $name]
		}
		"NEXIST *" {
		    set t [lrange $tgttype 1 end]
		    set value [$b nothing $t $name]
		}
		"STRING" - "EMPTY" {
		    set value [my LoadOrLiteral "literal {}"]
		}
		default {
		    # Should be unreachable in practice
		    my Warn "widened void to $tgttype; result is undef"
		    set value [$b undef $tgttype]
		}
	    }


	} else {
	    set value [my LoadOrLiteral $src]
	    set value [my WidenedComplexValue $value $srctype $tgttype]
	}
	SetValueName $value $name


	if {refType($tgttype)} {

	    $b addReference($tgttype) $value
	    $b printref $value "widen:"
	}
	my StoreResult $tgt $value
	return
    }

    # Handles the type modifiers CALLFRAME, FAIL and NEXIST
    method WidenedComplexValue {value srctype tgttype {name ""}} {
	# Handle CALLFRAME-extended types
	if {"CALLFRAME" eq $srctype && "CALLFRAME" in $tgttype} {
	    set frame $value
	    set value [$b undef [lrange $tgttype 1 end]]
	    return [$b frame.pack $frame $value $name]
	} elseif {"CALLFRAME" in $srctype && "CALLFRAME" in $tgttype} {
	    set frame [$b frame.frame $value]
	    set value [$b frame.value $value]
	    set srctype [lrange $srctype 1 end]
	    set tgttype [lrange $tgttype 1 end]
	    set value [my WidenedComplexValue $value $srctype $tgttype]
	    return [$b frame.pack $frame $value $name]
	} elseif {"CALLFRAME" in $tgttype} {
	    error "callframe injection"
	}

	# Handle FAIL-extended types
	if {"FAIL" eq $srctype && "FAIL" in $tgttype} {
	    # Implementation type of pure FAIL is int32 (Tcl result code)
	    set tgttype [lrange $tgttype 1 end]
	    return [$b fail $tgttype $value]
	} elseif {"FAIL" in $srctype && "FAIL" in $tgttype} {
	    set value [$b unmaybe $value]
	    set srctype [lrange $srctype 1 end]
	    set tgttype [lrange $tgttype 1 end]
	    set value [my WidenedComplexValue $value $srctype $tgttype]
	    return [$b ok $value $name]
	} elseif {"FAIL" in $tgttype} {
	    set tgttype [lrange $tgttype 1 end]
	    set value [my WidenedComplexValue $value $srctype $tgttype]
	    return [$b ok $value $name]
	}

	# Handle NEXIST-extended types
	if {"NEXIST" in $srctype && "NEXIST" in $tgttype} {
	    set value [$b unmaybe $value]
	    set srctype [lrange $srctype 1 end]
	    set tgttype [lrange $tgttype 1 end]
	    set value [my WidenedComplexValue $value $srctype $tgttype]
	    return [$b just $value $name]
	} elseif {"NEXIST" in $tgttype} {
	    set tgttype [lrange $tgttype 1 end]
	    set value [my WidenedComplexValue $value $srctype $tgttype]
	    return [$b just $value $name]
	}

	# Delegate to the inner value handler
	tailcall my WidenedValue $value $srctype $tgttype $name
    }

    # Handle widening of basic values
    method WidenedValue {value srctype tgttype {name ""}} {
	if {$srctype eq $tgttype} {
	    return $value
	}
	if {$srctype eq "ZEROONE" && "ZEROONE" ni $tgttype} {
	    set value [$b cast(BOOLEAN) $value]
	    set srctype INT
	}

	# ARRAY or STRING to ARRAY STRING - We've got builder methods for that

	if {$tgttype eq "ARRAY STRING"} {
	    if {$srctype eq "ARRAY"} {
		set tuple [$b arraystring.from.array $value]
	    } else {
		set svalue [my WidenedValue $value $srctype STRING]
		set tuple [$b arraystring.from.scalar $svalue]
	    }
	    return $tuple
	}

	# IMPURE to IMPURE - Copy the string value, and promote the
	# inner value

	if {[lindex $tgttype 0] eq "IMPURE"
		&& [lindex $srctype 0] eq "IMPURE"} {
	    set itgttype [lrange $tgttype 1 end]
	    set isrctype [lrange $srctype 1 end]
	    set ivalue [my WidenedValue [$b impure.value $value] \
			    $isrctype $itgttype]
	    set svalue [$b impure.string $value]
	    set value [$b impure $itgttype $svalue $ivalue $name]



	} elseif {[lindex $srctype 0] eq "IMPURE" && "STRING" in $tgttype} {
	    set value [$b stringifyImpure $value $name]
	} elseif {[regexp {^IMPURE (.*)$} $tgttype -> innertype]} {

	    set widened [my WidenedValue $value $srctype $innertype]
	    set value [$b packImpure($innertype) $widened $name]
	} elseif {$tgttype eq "ZEROONE BOOLEAN"} {
	    if {$srctype in {"ZEROONE" "BOOLEAN"}} {
		# do nothing - the internal reps are the same
	    }
	} elseif {refType($tgttype) != refType($srctype)} {
	    if {refType($srctype)} {
		# TODO: handle other kinds of reference types
		my Warn "typematch %s -> %s" $srctype $tgttype
	    }
	    set value [$b stringify($srctype) $value $name]
	} elseif {$tgttype eq "DOUBLE"} {
	    set value [$b cast(DOUBLE) $value $name]


	} elseif {$tgttype eq "NUMERIC"} {
	    if {$srctype eq "DOUBLE"} {
		set value [$b packNumericDouble $value $name]
	    } else {
		set value [$b packNumericInt $value $name]
	    }
	} elseif {$srctype eq "EMPTY" && $tgttype eq "STRING"} {
	    set value [Const "" STRING]
	} elseif {$srctype ne $tgttype} {
	    my Warn "unimplemented convert from '$srctype' to '$tgttype'"
	}
	if {[Type $tgttype] eq [Type [TypeOf $value]?]} {
	    set value [$b ok $value]
	} elseif {[Type $tgttype] eq [Type [TypeOf $value]!]} {
	    set value [$b just $value]
	}
	return $value
    }
 
    # TclCompiler:IssueDictExists --
    #
    #	Generate the code for testing whether an element of a dictionary
................................................................................
	if {$type eq "NEXIST"} {
	    set value [my LoadOrLiteral $def]
	} elseif {!failType($type)} {
	    set value [my LoadOrLiteral $src]
	} else {
	    # Nope; do it at run-time.
	    set test [$b exists [my LoadOrLiteral $src]]
	    set stype [lrange $type 1 end]
	    set value [$b select [$b expect $test true] \
			   [$b unmaybe [my LoadOrLiteral $src]] \

			   [my LoadTypedLiteral [lindex $def 1] $stype]]
	}

	set type [my OperandType $tgt]
	if {refType($type)} {
	    $b printref $value "init:"
	    $b addReference($type) $value
	}
................................................................................
    # Results:
    #	LLVM int1 that is true if the target of the branch is to be taken.

    method IssueThrowIfNEXIST {operation} {
	upvar 1 tgt tgtPC
	lassign $operation opcode branchTarget src varname

	set type [my OperandType $src]
	set tgtPC [lindex $branchTarget 1]
	set name [my LiteralValue $varname]
	set msg [Const "can't read \"$name\": no such variable" STRING]
	set exn [Const [list TCL LOOKUP VARNAME $name] STRING]















	set result [my Unlikely existsOrError [my LoadOrLiteral $src] \
			$msg $exn $errorCode]

	return $result
    }
 
    # TclCompiler:IssueException --
    #
    #	Generate the code for creating a general exception (e.g., from
    #	[error], [throw] or [return] with options. Must only be called from
    #	the 'compile' method.
................................................................................
	    if {$dlen == 1 && [dict exists $s2lit -errorcode]
		    && $maintype eq "STRING"
		    && literal([lindex $srcs 1]) && literal([lindex $srcs 2])
		    && [lindex $srcs 1 1] == 1 && [lindex $srcs 2 1] == 0} {
		# Really a throw
		set exn [Const [dict get $s2lit -errorcode] STRING]
		$b initException $exn $value $errorCode
		my SetErrorLine $errorCode
		my StoreResult $tgt [$b fail $maintype [$b load $errorCode]]
		return
	    }
	    if {$dlen == 0} {
		# Blank options; substitute a NULL
		set vals [linsert [lmap s [lrange $srcs 1 end] {
		    my LoadOrLiteral $s
		}] 0 [$b null STRING]]
	    }
	} elseif {[llength $srcs] == 1 && literal($src2)} {
	    # Detect failure to optimise a case that could actually be handled
	    # neatly; [return -level 0 $x] works pretty much identically to
	    # [string cat $x].
	    if {[lindex $src2 1] eq "-level 0"} {
		my Warn "\[return -level 0\] not optimised by quadcode; applying pass-through"
		set result [$b ok $value]
		my StoreResult $tgt $result
		return
	    }
	}

	# No special instruction sequence; pass it all through to the
	# lower-level code issuers.
	if {![info exist vals]} {
	    set vals [lmap s $srcs {my LoadOrLiteral $s}]
	}
	my StoreResult $tgt [$b $opcode {*}$vals $value $maintype \
		$errorCode $name]
	if {[llength $vals] == 1} {
	    $b logCommandInfo [$b load $errorCode] $currentscript
	} else {
	    my SetErrorLine $errorCode
	}
	return
    }

    # TclCompiler:SetErrorLine --
    #
    #	Generate code to set the errorLine and errorInfo for an exception. The
    #	error information is only set if the errorCode is TCL_ERROR and the
    #	test passes.
    #
    #	Expects to only ever be called in a context where it is possible to
    #	determine what the current source line and command script text are.
    #
    # Parameters:
    #	errorCode -
    #		The LLVM int32* (i.e., pointer to variable) that the error
    #		code will be loaded from.
    #	test (optional) -
    #		The LLVM bool that will govern whether to issue the exception
    #		processing. If omitted, will be taken as being the true
    #		constant.
    #
    # Results:
    #	none

    method SetErrorLine {errorCode {test ""}} {
	if {$test eq ""} {
	    set test [Const true bool]
	}
	set line $currentprocrelline
	# The line number for the errorLine field needs to begin at 1
	incr line
	$b setErrorLine $test [$b load $errorCode] [Const $line int] \
	    $currentscript
	return
    }
 
    # TclCompiler:Unlikely --
    #
    #	Issue a (boolean-returning) instruction and mark it as being expected
    #	to produce a false.
................................................................................
    #	operand -
    #		The operand to get the typecode of.
    #
    # Results:
    #	The typecode.

    method OperandType {operand} {
	set tyname [nameOfType [typeOfOperand $vtypes $operand]]
	# Workaround: INT is actually a 64-bit capable type in codegen
	return [string map {ENTIER INT} $tyname]
    }

    # TclCompiler:IsCallFrame --
    #
    #	Get whether a particular operand is a CALLFRAME.
    #
    # Parameters:
    #	operand -
    #		The operand to test the type of.
    #
    # Results:
    #	A Tcl boolean value.

    method IsCallFrame {operand} {
	variable ::quadcode::dataType::CALLFRAME

	return [expr {[lindex $operand 0] in {"var" "temp"}
		      && ([typeOfOperand $vtypes $operand] & $CALLFRAME) != 0}]
    }

    # TclCompiler:ValueTypes --
    #
    #	Convert the sequence of arguments (to an opcode) into the type
    #	signature tuple to use with the name of the method in the Build class
    #	to enable automatic type widening.
................................................................................
    #
    # Results:
    #	The name.

    method LoadOrLiteral {desc} {
	if {[info exist variables($desc)]} {
	    return $variables($desc)
	}
	if {$desc eq "Nothing"} {
	    # NEXIST special case
	    return "Nothing"
	}
	lassign $desc kind value
	if {$kind ne "literal"} {
	    return -code error "unsubstitutable argument: $desc"
	}
	set type [nameOfType [typeOfLiteral $value]]
	return [my LoadTypedLiteral $value $type]
    }

    # TclCompiler:LoadTypedLiteral --
    #
    #	Generate the code to create a LLVM value reference, given the
    #	descriptor of what the variable should be.
    #
    # Parameters:
    #	value -	The Tcl value that we are creating a literal for.
    #	type -	The quadcode type that we are going to produce.
    #
    # Results:
    #	The name.
    #
    # Maintainer note:
    #	DO NOT do reference count management in this function! It makes things
    #	leak or triggers use-after-free crashes. Leave that to the main
    #	compiler engine (and the STRING allocator) as that gets it right.

    method LoadTypedLiteral {value type} {
	if {[lindex $type 0] eq "IMPURE"} {
	    set sval [my LoadTypedLiteral $value STRING]
	    set itype [lrange $type 1 end]
	    set tval [my LoadTypedLiteral $value $itype]
	    return [$b impure $itype $sval $tval]






	} elseif {$type eq "DOUBLE"} {
	    return [ConstReal [Type $type] $value]

	} elseif {$type in {"ZEROONE" "BOOLEAN" "ZEROONE BOOLEAN"}} {
	    return [Const [expr {$value}] bool]
	} elseif {$type in {"INT" "ENTIER"}} {
	    return [$b int [expr {entier($value)}]]
	} elseif {$type in {"STRING" "EMPTY"}} {
	    set result [Const $value STRING]
	    $b assume [$b shared $result]
	    return $result






	} else {
	    return -code error \
		"unhandled type for literal \"${value}\": \"$type\""
	}
    }

    # TclCompiler:StoreResult --
................................................................................
    #	trivially unique from one another.)
    #
    # Parameters:
    #	desc -	The descriptor of the variable that the value will be written
    #		to.
    #	value -	The LLVM value reference to the value to place in the variable
    #		named by the 'desc' argument.
    #	opcode (optional) -
    #		The quadcode opcode for which we are issuing this store. Only
    #		currently useful for enabling a different sort of debugging
    #		behaviour with phi nodes, as those must not be interleaved
    #		with debugging intrinsics (unlike with other result-producing
    #		operations).
    #
    # Results:
    #	None.

    method StoreResult {desc value {opcode ""}} {
	if {[lindex $desc 0] eq "literal"} {
	    return -code error "cannot store into literal; it makes no sense"
	}
	if {[info exist variables($desc)]} {
	    set targetType [TypeOf $variables($desc)]
	    if {$targetType ne [TypeOf $value]} {
		my Warn "variable is of type %s and assigned value (to '%s') is %s" \
		    [PrintTypeToString $targetType] \
		    $desc [PrintValueToString $value]
	    }
	}
	if {[lindex $desc 0] eq "var"} {
	    if {$opcode eq "phi"} {
		upvar 1 phiAnnotations todo
		lappend todo [lindex $desc 1] $value
	    } else {
		my AnnotateAssignment [lindex $desc 1] $value
	    }
	}
	if {[info exist variables($desc)]} {
	    if {$targetType ne [TypeOf $value]} {
		return -code error [format \
			"type mismatch: variable {%s} of type '%s' but was assigned value of type '%s'" \
			$desc [PrintTypeToString [TypeOf $variables($desc)]] \
			[PrintTypeToString [TypeOf $value]]]
	    }
	    ReplaceAllUsesWith $variables($desc) $value
	}
................................................................................
    #	Boolean, true if the type is a reference type.

    method ReferenceType? {type} {
	if {[string is entier -strict $type]} {
	    set type [nameOfType $type]
	}
	foreach piece $type {
	    if {$piece in {IMPURE DICTITER EMPTY STRING ENTIER ARRAY}} {
		return 1
	    }
	}
	return 0
    }

    # TclCompiler:FailureType? --
................................................................................
	    switch [lindex $quads $search 0] {
		"free" {
		    if {[lindex $quads $search 2] eq $var} {
			return $search
		    }
		}
		"jump" - "jumpFalse" - "jumpTrue" - "return" -
		"jumpMaybe" - "jumpMaybeNot" {
		    return 0
		}
		default {
		    if {$var in [lindex $quads $search]} {
			return 0
		    }
		}
................................................................................
		break
	    }
	}
	if {$worthMapping} {
	    foreach indexPosition $args {
		set index [lindex $s2 $indexPosition 1]
		if {$index eq "end"} {
		    lset s2 $indexPosition "literal 2"
		    if {![info exist length]} {
			set length [$b ${lengthOp}(STRING) [lindex $s3 0]]
		    }
		    set delta -1
		} elseif {[string match "end*" $index]} {
		    lset s2 $indexPosition "literal 2"
		    if {![info exist length]} {
			set length [$b ${lengthOp}(STRING) [lindex $s3 0]]
		    }
		    set delta [expr {[string range $index 3 end]-1}]
		} else {
		    continue
		}
		lset s3 $indexPosition \
		    [$b add(INT,INT) $length \

			 [my LoadOrLiteral [list literal $delta]]]
	    }
	}
	append opcode ( [my ValueTypes {*}$s2] )
	return $s3
    }

    # TclCompiler:LiteralValue --
................................................................................
    # Parameters:
    #	none
    #
    # Results:
    #	The LLVM function reference that we have generated. Note that this
    #	will be an unoptimised function at this stage.


    method compile {} {
	try {
	    my Compile $quadcode
	} on error {msg opts} {
	    dict append opts -errorinfo \
		"\n    (compiling code for \"$cmd\")"
	    return -options $opts $msg
	}
    }

    # TclInterproceduralCompiler:generateThunk --
    #
    #	Generate the binding into Tcl of the function that we transformed the
    #	procedure into.
    #
................................................................................
    #		The API binding class instance.
    #
    # Results:
    #	The function reference (i.e., instance of Function class) for the
    #	binding function. (Not the bound function, which this class made.)

    method generateThunk {thunkBuilder} {
	if {[dict exists $bytecode procmeta]} {
	    $thunkBuilder buildProcedureMetadata $cmd $bytecode \
		[dict get $bytecode procmeta]
	    dict unset bytecode procmeta
	}
	$thunkBuilder thunk $cmd $bytecode $func
    }

    # TclInterproceduralCompiler:printTypedQuads --
    #
    #	Print the sequence of typed quadcodes that the type inference engine
    #	has transformed the procedure into.
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Name change from codegen.tcl to codegen/config.tcl.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
..
16
17
18
19
20
21
22


23
24

25
26





























27
28
29
30
31
32
33
..
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
..
72
73
74
75
76
77
78



79




80
81
82
83
84
85
86
..
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
# codegen.tcl --
#
#	LLVM code generator driver. Packages the LLVM interface code into a
#	convenient form and provides the ability to configure a few things
#	(such as the logging level) simply.
#
# Copyright (c) 2014-2015 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
package require llvmtcl 3.6.2
................................................................................

namespace eval ::LLVM {
    namespace path ::llvmtcl
    variable THIS_SCRIPT [info script]

    variable counter 0
    variable debug 0


    variable time 0
    variable optimiseLevel 3

    variable dumpPre {}
    variable dumpPost {}






























    # LLVM::include --
    #
    #	Simplifying wrapper around [source].
    #
    # Parameters:
    #	filename -
................................................................................
    #		directory containing the call to the [include] command.
    #
    # Results:
    #	Whatever the result of evaluating the included script is.

    proc include filename {
	variable THIS_SCRIPT
	set name [file join [file dirname $THIS_SCRIPT] $filename]
	tailcall source -encoding utf-8 $name
    }

    # Support procedure and class definitions

    include codegen/tycon.tcl
    include codegen/struct.tcl
    include codegen/llvmbuilder.tcl
    include codegen/build.tcl
    include codegen/mathlib.tcl
    include codegen/stdlib.tcl

    include codegen/thunk.tcl
    include codegen/tclapi.tcl
    include codegen/macros.tcl
    include codegen/compile.tcl

    include codegen/debug.tcl
    include quadcode/specializer.tcl
    Module initialiseLLVM

    # LLVM::configure --
    #
    #	Provide a standard configuration interface, following the same general
    #	model as [chan configure].
    #
    # Parameters:
................................................................................
    #		parameters) then they are in "configItemName value" pairs, and
    #		will set each of those values.
    #
    # Results:
    #	Depends on number of parameters.

    proc configure args {



	set opts {-counter counter -debug debug -opt optimiseLevel -time time}




	if {[llength $args] == 0} {
	    foreach {opt varname} $opts {
		namespace upvar [namespace current] $varname var
		lappend result $opt $var
	    }
	    return $result
	} elseif {[llength $args] == 1} {
................................................................................
	foreach {opt val} $args {
	    set opt [tcl::prefix match [dict keys $opts] $opt]
	    namespace upvar [namespace current] [dict get $opts $opt] var
	    set var $val
	}
    }

    # LLVM::SelectModuleName --
    #
    #	Convert a master namespace name into a module name.
    #
    # Parameters:
    #	namespace -
    #		The name of the namespace.
    #
    # Results:
    #	The name of the module.

    proc SelectModuleName {namespace} {
	set name [regsub -all -nocase {[^a-z0-9:]+} $namespace "_"]
	set name [regsub {^:+} $name "GLOBAL_"]
	set name [regsub -all {:+} $name "_NS_"]
	set name [regsub -all {_+} $name "_"]
	return [string trim $name "_"]
    }

    # LLVM::optimise --
    #
    #	Apply the LLVM compilation and optimisation engine to a collection of
    #	procedures. Upon success, this will REPLACE the procedures with
    #	compiled commands.
    #
    # Parameters:
    #	args... -
    #		Globs for names of the procedures to replace. The names do NOT
    #		need to be fully-qualified.
    #
    # Results:
    #	The LLVM reference to the module containing the commands that have
    #	been made to replace the given collection of procedures.

    proc optimise {args} {
	variable counter
	variable debug
	variable optimiseLevel
	variable thunkBuilder
	variable time

	# Convert globs to a list of procedures
	set cmds {}
	foreach glob $args {
	    lappend cmds {*}[uplevel 1 [list info commands $glob]]
	}
	# Work out what we're *really* talking about
	set cmds [lmap p $cmds {uplevel 1 [list namespace which $p]}]
	# Strip any duplicates
	set cmds [lsort -unique $cmds]

	timeit init-module {
	    set ns [uplevel 1 {namespace current}]
	    set name [SelectModuleName $ns]
	    set module [Module new $name]

	    # Get an instance of the system that glues things to the Tcl
	    # runtime.
	    set thunkBuilder [ThunkBuilder new $module]
	    set sp [quadcode::specializer new $cmds]
	}

	try {
	    set required {}
	    set compiledProcs {}
	    set publicInterface {}

	    timeit register {
		foreach cmd $cmds {
		    $sp register $cmd
		    set r [lmap - [info args $cmd] {
			set quadcode::dataType::STRING
		    }]
		    $sp require $cmd $r
		    dict set required $cmd $r
		}
	    }

	    timeit specialise {
		$sp computeTypes
		foreach triple [$sp instancesNeeded] {
		    lassign $triple cmd argTypes
		    set c [TclInterproceduralCompiler new $sp $cmd $argTypes]
		    lappend compiledProcs $c
		    if {$argTypes eq [dict get $required $cmd]} {
			lappend publicInterface $c
		    }
		}
	    }

	    timeit generate {
		# Now we generate declarations for the functions we'll build
		foreach c $compiledProcs {
		    $c generateDeclaration $module
		}

		# Spit the code out
		foreach c $compiledProcs {
		    if {$debug} {
			$c printTypedQuads stdout
		    }
		    $c compile
		}

		# For code that needs to bind to Tcl, make the thunks. Then
		# finalise the thunks, which finishes building the module's
		# init function.
		foreach c $publicInterface {
		    $c generateThunk $thunkBuilder
		}
		$thunkBuilder finalize
	    }

	    # Save the current IR
	    variable dumpPre [$module dump]

	    # Check that what we have is actually correct!
	    $module verify
	    if {$debug} {
		parray ::useCount
	    }

	    timeit optimize {
		# Run the LLVM IR optimizer. The configuration of this is in
		# llvmtcl and is due to Jos Decoster.
		$module optimize $optimiseLevel
	    }

	    # Save the current IR
	    variable dumpPost [$module dump]

	    timeit assemble {
		# Call the package init function. This causes native code to
		# be issued and linked.
		$module mcjit
		$thunkBuilder install
	    }

	    # Return the LLVM handle to the module, just in case.
	    #
	    # Note that it is *UNSAFE* to uninstall this package (unless all
	    # commands it creates are deleted, since we don't do any custom
	    # Tcl_ObjType magic or other awkward stuff).
	    return [$module ref]
	} finally {
	    # Note, this *doesn't* destroy the module or any of the compiled
	    # procedures it contains at the LLVM level
	    $module destroy
	    foreach cp $compiledProcs {
		$cp destroy
	    }
	    $sp destroy
	}
    }

    # LLVM::pre --
    #
    #	Report the LLVM IR that was produced prior to applying the LLVM
    #	optimisation engine.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	LLVM IR code, in human-readable form.

    proc pre {} {
	variable dumpPre
	return [string trim $dumpPre]
    }

    # LLVM::post --
    #
    #	Report the LLVM IR that was produced after applying the LLVM
    #	optimisation engine.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	LLVM IR code, in human-readable form.

    proc post {} {
	variable dumpPost
	return [string trim $dumpPost]
    }

    namespace export configure optimise pre post
    namespace ensemble create
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# End:
|

|
|
|

|







 







>
>


>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|




>
|
|
|
|
|
|
>
|
|
|
|
>
|
|
<







 







>
>
>
|
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|








1
2
3
4
5
6
7
8
9
10
11
12
13
14
..
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
..
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
...
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
...
134
135
136
137
138
139
140



























































































































































































141
142
143
144
145
146
147
148
149
# config.tcl --
#
#	LLVM code generator configuration and high-level driver. Packages the
#	LLVM interface code into a convenient form and provides the ability to
#	configure a few things (such as the logging level) simply.
#
# Copyright (c) 2014-2017 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
package require llvmtcl 3.6.2
................................................................................

namespace eval ::LLVM {
    namespace path ::llvmtcl
    variable THIS_SCRIPT [info script]

    variable counter 0
    variable debug 0
    # Turn on debugging metadata from llvmtcl 3.6.3 onwards
    variable debugmeta [package vsatisfies [package require llvmtcl] 3.6.3]
    variable time 0
    variable optimiseLevel 3
    variable quadcode-log {}
    variable dumpPre {}
    variable dumpPost {}
    variable useStubs 0
    variable OptExecutable [file join $::llvmtcl::llvmbindir opt]
    variable LlcExecutable [file join $::llvmtcl::llvmbindir llc]
    variable LinkerExecutable
    apply {{} {
	variable LinkerExecutable
	variable ::llvmtcl::llvmbindir
	global env
	if {[info exists env(CC)]} {
	    set LinkerExecutable [file normalize $env(CC)]
	} else {
	    foreach option {clang gcc cc ld} {
		foreach ext {"" .exe} {
		    set f [file join $llvmbindir $option$ext]
		    if {[file executable $f]} {
			set LinkerExecutable $f
			puts "Linker: $f"
			break
		    }
		}
		if {[info exist LinkerExecutable]} break
		set f [lindex [auto_execok $option] 0]
		if {$f ne ""} {
		    set LinkerExecutable $f
		    break
		}
	    }
	}
    } ::LLVM}

    # LLVM::include --
    #
    #	Simplifying wrapper around [source].
    #
    # Parameters:
    #	filename -
................................................................................
    #		directory containing the call to the [include] command.
    #
    # Results:
    #	Whatever the result of evaluating the included script is.

    proc include filename {
	variable THIS_SCRIPT
	set name [file normalize [file join [file dirname $THIS_SCRIPT] $filename]]
	tailcall source -encoding utf-8 $name
    }

    # Support procedure and class definitions
    uplevel #0 [list LLVM::include ../quadcode/transformer.tcl]
    include tycon.tcl
    include struct.tcl
    include llvmbuilder.tcl
    include build.tcl
    include mathlib.tcl
    include stdlib.tcl
    include varframe.tcl
    include thunk.tcl
    include tclapi.tcl
    include macros.tcl
    include compile.tcl
    include debug.tcl
    include jit.tcl
    include ../quadcode/specializer.tcl


    # LLVM::configure --
    #
    #	Provide a standard configuration interface, following the same general
    #	model as [chan configure].
    #
    # Parameters:
................................................................................
    #		parameters) then they are in "configItemName value" pairs, and
    #		will set each of those values.
    #
    # Results:
    #	Depends on number of parameters.

    proc configure args {
	set opts {
	    -counter counter
	    -debug debug
	    -opt optimiseLevel
	    -quadcode-log quadcode-log
	    -time time
	    -stubs useStubs
	}
	if {[llength $args] == 0} {
	    foreach {opt varname} $opts {
		namespace upvar [namespace current] $varname var
		lappend result $opt $var
	    }
	    return $result
	} elseif {[llength $args] == 1} {
................................................................................
	foreach {opt val} $args {
	    set opt [tcl::prefix match [dict keys $opts] $opt]
	    namespace upvar [namespace current] [dict get $opts $opt] var
	    set var $val
	}
    }




























































































































































































    namespace export configure optimise pre post compiletodll compilepackagetodll
    namespace ensemble create
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# End:

Changes to codegen/debug.tcl.

26
27
28
29
30
31
32
33
34
35
36
37
38

39
40
41
42
43
44
45
..
47
48
49
50
51
52
53






54
55
56
57
58
59
60
61
62
63
64
..
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
...
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
...
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
...
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
...
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
...
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
...
295
296
297
298
299
300
301
302
303
304
305
306






























307
308
309
310
311
312
313
...
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
...
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
...
413
414
415
416
417
418
419

420
#	line -	The current line number for instructions.
#	main -	The main debugging scope of the module.
#	ref -	The llvmtcl debugging builder handle.
#	scope -	The current scope of debugging assertions.

oo::class create Debugging {
    superclass llvmEntity
    variable b main currentScope currentFile currentLine builder
    variable typeSizes alignedSizes

    constructor {module {filename "/dev/null"}} {
	next
	set filename [file normalize $filename]

	set filedir [file dirname $filename]
	set filetail [file tail $filename]
	set b [DebugInfo CreateBuilder [$module ref]]
	set currentLine 0
	# Need better way to describe
	set versioninfo [lmap pkg {tclquadcode llvmtcl Tcl} {
	    string cat $pkg " " [package require $pkg]
................................................................................
	set producer [join $versioninfo "/"]
	set main [DebugInfo CompileUnit $b $filetail $filedir $producer]
	set currentScope $main
	my file $filename
	set builder [$module builder]
	array set typeSizes {}
	array set alignedSizes {}






    }

    destructor {
	DebugInfo DisposeBuilder $b 
    }

    # Debugging:main (property) --
    #
    #	Get the principal debugging scope that this class is adding
    #	information to.

................................................................................
    #		The value that is being assigned.
    #	script (optional) -
    #		A script to evaluate with the scope assigned.

    method scope {{scope ""} {script ""}} {
	if {$script ne ""} {
	    set s $currentScope

	    try {
		set currentScope $scope
		return [uplevel 1 $script]
	    } finally {
		set currentScope $s

	    }
	}
	if {$scope eq ""} {
	    return $currentScope
	} else {
	    set currentScope $scope
	    return
	}
    }













    # Debugging:line (property, settable) --
    #
    #	Get or set the current line for location annotations.

    method line {{line ""}} {
	if {$line eq ""} {
................................................................................
    #	name -	The name of the namespace.
    #
    # Results:
    #	The LLVM metadata node.

    method namespace {name} {
	DebugInfo Namespace $b \
	    $currentScope $name $currentFile $currentLine
    }

    # Debugging:location --
    #
    #	Create the debugging metadata for a source code location.
    #
    # Parameters:
    #	line -	The line number of the location.
    #	column -
    #		The column number of the location.
    #
    # Results:
    #	The LLVM metadata node.

    method location {line column} {
	DebugInfo Location $currentScope $line $column





















    }

    # Debugging:voidType --
    #
    #	Create the debugging metadata for a void type.
    #
    # Parameters:
................................................................................
    #		The debugging metadata that this is an alias for.
    #
    # Results:
    #	The LLVM metadata node.

    method aliasType {name originalType} {
	set t [DebugInfo AliasType $b \
	    $originalType $name $currentFile $currentLine $currentScope]
	set typeSizes($t) $typeSizes($originalType)
	set alignedSizes($t) $alignedSizes($originalType)
	return $t
    }

    # Debugging:intType --
    #
................................................................................
	if {$bitSize == 1} {
	    set type 0x02;	# DW_ATE_boolean
	} else {
	    set type 0x05;	# DW_ATE_signed
	}
	set t [DebugInfo BasicType $b $name $bitSize $type]
	set typeSizes($t) [expr {($bitSize + 7) >> 3}]
	# Assume we're 4-byte aligned
	set alignedSizes($t) [expr {$bitSize > 32 ? 8 : 4}]
	return $t
    }

    # Debugging:floatType --
    #
    #	Create the debugging metadata for a floating-point type.
    #
................................................................................
    #
    # Results:
    #	The LLVM metadata node.

    method floatType {name bitSize} {
	set t [DebugInfo BasicType $b $name $bitSize 0x04]; # DW_ATE_float
	set typeSizes($t) [expr {($bitSize + 7) >> 3}]
	# Assume we're 4-byte aligned
	set alignedSizes($t) [expr {$bitSize > 32 ? 8 : 4}]
	return $t
    }

    # Debugging:pointerType --
    #
    #	Create the debugging metadata for a pointer type.
    #
................................................................................
    #	The LLVM metadata node.

    method pointerType {name pointee} {
	global tcl_platform
	set type [DebugInfo PointerType $b $pointee]
	if {$name ne ""} {
	    set type [DebugInfo AliasType $b \
			  $type $name $currentFile $currentLine $currentScope]
	}
	set typeSizes($type) $tcl_platform(pointerSize)
	set alignedSizes($type) $tcl_platform(pointerSize)
	return $type
    }

    # Debugging:structType --
................................................................................
	foreach t $args {
	    incr size $alignedSizes($t)
	    if {$alignedSizes($t) == 0} {
		my Warn "using improper type as member of structure"
	    }
	}
	set t [DebugInfo StructType $b \
	    $currentScope $name $currentFile $currentLine $size {*}$args]
	set typeSizes($t) $size
	set alignedSizes($t) $size
	return $t
    }































    # Debugging:functionType --
    #
    #	Create the debugging metadata for a function type.
    #
    # Parameters:
    #	returnType -
................................................................................
    # Debugging:function --
    #
    #	Create the debugging metadata for a function.
    #
    # Parameters:
    #	function -
    #		The LLVM reference to the function.
    #	name -	The name of the function in the source.
    #	type -	The metadata node of the function type.
    #	linkName (optional) -
    #		The name of function in the generated code. If omitted, it is
    #		assumed to be the same as the name of the function.
    #
    # Results:
    #	The LLVM metadata node.

    method function {function name type {linkName ""}} {
	if {$linkName eq ""} {




	    set linkName $name
	}
	set md [DebugInfo Function $b \
	    $currentScope $name $linkName $currentFile $currentLine $type]
	DebugInfo AttachToFunction $function $md

	return $md
    }

    # Debugging:parameter --
    #
    #	Create the debugging metadata for a function parameter.
    #
................................................................................
    #
    #	Insert a @llvm.dbg.value in the current instruction stream.
    #
    # Parameters:
    #	value -	The value that is being assigned.
    #	variableInfo -
    #		The debugging description of the variable that is being
    #		assigned to.
    #
    # Results:
    #	None.

    method value {value variableInfo} {
	upvar 0 [info object namespace $builder]::b bRef
	set location [$builder @loc]
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







|





>







 







>
>
>
>
>
>



|







 







>





>









>
>
>
>
>
>
>
>
>
>
>
>







 







|








|





|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







<
|







 







<
|







 







|







 







|




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<

<
<
<




|
|
>
>
>
>
|


|

>







 







|







 







>

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
..
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
..
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
...
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
...
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
...
267
268
269
270
271
272
273

274
275
276
277
278
279
280
281
...
286
287
288
289
290
291
292

293
294
295
296
297
298
299
300
...
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
...
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
...
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
...
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
...
484
485
486
487
488
489
490
491
492
#	line -	The current line number for instructions.
#	main -	The main debugging scope of the module.
#	ref -	The llvmtcl debugging builder handle.
#	scope -	The current scope of debugging assertions.

oo::class create Debugging {
    superclass llvmEntity
    variable b main currentScope currentFile currentLine builder functions
    variable typeSizes alignedSizes

    constructor {module {filename "/dev/null"}} {
	next
	set filename [file normalize $filename]
	set functions {}
	set filedir [file dirname $filename]
	set filetail [file tail $filename]
	set b [DebugInfo CreateBuilder [$module ref]]
	set currentLine 0
	# Need better way to describe
	set versioninfo [lmap pkg {tclquadcode llvmtcl Tcl} {
	    string cat $pkg " " [package require $pkg]
................................................................................
	set producer [join $versioninfo "/"]
	set main [DebugInfo CompileUnit $b $filetail $filedir $producer]
	set currentScope $main
	my file $filename
	set builder [$module builder]
	array set typeSizes {}
	array set alignedSizes {}
	namespace eval tcl::mathfunc {
	    proc align x {
		set y [expr {$::tcl_platform(wordSize) - 1}]
		expr {($x + $y) &~ $y}
	    }
	}
    }

    destructor {
	DebugInfo DisposeBuilder $b
    }

    # Debugging:main (property) --
    #
    #	Get the principal debugging scope that this class is adding
    #	information to.

................................................................................
    #		The value that is being assigned.
    #	script (optional) -
    #		A script to evaluate with the scope assigned.

    method scope {{scope ""} {script ""}} {
	if {$script ne ""} {
	    set s $currentScope
	    set l [$builder @loc]
	    try {
		set currentScope $scope
		return [uplevel 1 $script]
	    } finally {
		set currentScope $s
		$builder @loc $l
	    }
	}
	if {$scope eq ""} {
	    return $currentScope
	} else {
	    set currentScope $scope
	    return
	}
    }

    # Debugging:Scope --
    #
    #	Get the current scope, which is the main module if none other is
    #	defined.

    method Scope {} {
	if {$currentScope eq ""} {
	    return $main
	}
	return $currentScope
    }

    # Debugging:line (property, settable) --
    #
    #	Get or set the current line for location annotations.

    method line {{line ""}} {
	if {$line eq ""} {
................................................................................
    #	name -	The name of the namespace.
    #
    # Results:
    #	The LLVM metadata node.

    method namespace {name} {
	DebugInfo Namespace $b \
	    [my Scope] $name $currentFile $currentLine
    }

    # Debugging:location --
    #
    #	Create the debugging metadata for a source code location.
    #
    # Parameters:
    #	line -	The line number of the location.
    #	column (optional) -
    #		The column number of the location.
    #
    # Results:
    #	The LLVM metadata node.

    method location {line {column 0}} {
	DebugInfo Location [my Scope] $line $column
    }

    # Debugging:setInstructionLocation --
    #
    #	Describe the source location of the instruction.
    #
    # Parameters:
    #	instruction -
    #		The LLVM reference to the instruction.
    #	location (optional) -
    #		The location metadata handle. If omitted, the current line
    #		(as set by the 'line' property) will be used.
    #
    # Results:
    #	None.

    method setInstructionLocation {instruction {location "\u0000"}} {
	if {$location eq "\u0000"} {
	    set location [my location $currentLine]
	}
	DebugInfo Instruction.SetLocation $instruction $location
    }

    # Debugging:voidType --
    #
    #	Create the debugging metadata for a void type.
    #
    # Parameters:
................................................................................
    #		The debugging metadata that this is an alias for.
    #
    # Results:
    #	The LLVM metadata node.

    method aliasType {name originalType} {
	set t [DebugInfo AliasType $b \
	    $originalType $name $currentFile $currentLine [my Scope]]
	set typeSizes($t) $typeSizes($originalType)
	set alignedSizes($t) $alignedSizes($originalType)
	return $t
    }

    # Debugging:intType --
    #
................................................................................
	if {$bitSize == 1} {
	    set type 0x02;	# DW_ATE_boolean
	} else {
	    set type 0x05;	# DW_ATE_signed
	}
	set t [DebugInfo BasicType $b $name $bitSize $type]
	set typeSizes($t) [expr {($bitSize + 7) >> 3}]

	set alignedSizes($t) [expr {align($typeSizes($t))}]
	return $t
    }

    # Debugging:floatType --
    #
    #	Create the debugging metadata for a floating-point type.
    #
................................................................................
    #
    # Results:
    #	The LLVM metadata node.

    method floatType {name bitSize} {
	set t [DebugInfo BasicType $b $name $bitSize 0x04]; # DW_ATE_float
	set typeSizes($t) [expr {($bitSize + 7) >> 3}]

	set alignedSizes($t) [expr {align($typeSizes($t))}]
	return $t
    }

    # Debugging:pointerType --
    #
    #	Create the debugging metadata for a pointer type.
    #
................................................................................
    #	The LLVM metadata node.

    method pointerType {name pointee} {
	global tcl_platform
	set type [DebugInfo PointerType $b $pointee]
	if {$name ne ""} {
	    set type [DebugInfo AliasType $b \
			  $type $name $currentFile $currentLine [my Scope]]
	}
	set typeSizes($type) $tcl_platform(pointerSize)
	set alignedSizes($type) $tcl_platform(pointerSize)
	return $type
    }

    # Debugging:structType --
................................................................................
	foreach t $args {
	    incr size $alignedSizes($t)
	    if {$alignedSizes($t) == 0} {
		my Warn "using improper type as member of structure"
	    }
	}
	set t [DebugInfo StructType $b \
	    [my Scope] $name $currentFile $currentLine $size {*}$args]
	set typeSizes($t) $size
	set alignedSizes($t) $size
	return $t
    }

    # Debugging:arrayType --
    #
    #	Create the debugging metadata for a pointer type.
    #
    # Parameters:
    #	name -	The name of the type.
    #	elementType -
    #		The metadata node for the type pointed to.
    #	elementCount -
    #		The number of elements in this array.
    #
    # Results:
    #	The LLVM metadata node.

    method arrayType {name elementType elementCount} {
	global tcl_platform
	if {$alignedSizes($elementType) == 0} {
	    my Warn "using improper type as member of array"
	}
	set type [DebugInfo ArrayType $b \
		$elementType $elementCount $typeSizes($elementType)]
	if {$name ne ""} {
	    set type [DebugInfo AliasType $b \
			  $type $name $currentFile $currentLine [my Scope]]
	}
	set typeSizes($type) [expr {$elementCount * $typeSizes($elementType)}]
	set alignedSizes($type) [expr {align($typeSizes($type))}]
	return $type
    }

    # Debugging:functionType --
    #
    #	Create the debugging metadata for a function type.
    #
    # Parameters:
    #	returnType -
................................................................................
    # Debugging:function --
    #
    #	Create the debugging metadata for a function.
    #
    # Parameters:
    #	function -
    #		The LLVM reference to the function.

    #	type -	The metadata node of the function type.



    #
    # Results:
    #	The LLVM metadata node.

    method function {function type} {
	set name [GetValueName $function]
	if {[llength $name] == 3} {
	    set link $name
	    set name [lindex $name 1]
	} else {
	    set link ""
	}
	set md [DebugInfo Function $b \
	    [my Scope] $name $link $currentFile $currentLine $type]
	DebugInfo AttachToFunction $function $md
	lappend functions $md
	return $md
    }

    # Debugging:parameter --
    #
    #	Create the debugging metadata for a function parameter.
    #
................................................................................
    #
    #	Insert a @llvm.dbg.value in the current instruction stream.
    #
    # Parameters:
    #	value -	The value that is being assigned.
    #	variableInfo -
    #		The debugging description of the variable that is being
    #		assigned to. A handle produced by Debugging:variable.
    #
    # Results:
    #	None.

    method value {value variableInfo} {
	upvar 0 [info object namespace $builder]::b bRef
	set location [$builder @loc]
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Added codegen/jit.tcl.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# jit.tcl --
#
#	LLVM code generator driver for in-process compilation (and,
#	eventually, JIT compilation). Packages the LLVM interface code into a
#	convenient form.
#
# Copyright (c) 2014-2017 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
namespace eval ::LLVM {
    variable objectExtension ".o"
    namespace path ::llvmtcl
    Module initialiseLLVM

    # LLVM::SelectModuleName --
    #
    #	Convert a master namespace name into a module name.
    #
    # Parameters:
    #	namespace -
    #		The name of the namespace.
    #
    # Results:
    #	The name of the module.

    proc SelectModuleName {namespace} {
	set name [regsub -all -nocase {[^a-z0-9:]+} $namespace "_"]
	set name [regsub {^:+} $name "GLOBAL_"]
	set name [regsub -all {:+} $name "_NS_"]
	set name [regsub -all {_+} $name "_"]
	return [string totitle [string trim $name "_"]]
    }

    # LLVM::opt --
    #
    #	Apply the standalone LLVM optimisation program ("opt") to some
    #	bitcode.
    #
    # Parameters:
    #	bitcode -
    #		The (binary) LLVM bitcode to pass in. This procedure will
    #		handle correctly conveying this to the "opt" program.
    #	args... -
    #		Arguments to be passed to "opt". -S is recommended if
    #		human-readable output is desired. An optimisation level is
    #		also recommended (e.g., -O3 -Os or -Oz).
    #
    # Results:
    #	Whatever output the "opt" program produces, which depends on the
    #	arguments passed in.

    proc opt {bitcode args} {
	variable OptExecutable
	set f [file tempfile n tcl.bc]
	try {
	    fconfigure $f -translation binary
	    puts -nonewline $f $bitcode
	    close $f
	    return [exec $OptExecutable {*}$args [file normalize $n] 2>@stderr]
	} finally {
	    file delete $n
	}
    }

    # LLVM::optimise --
    #
    #	Apply the LLVM compilation and optimisation engine to a collection of
    #	procedures. Upon success, this will REPLACE the procedures with
    #	compiled commands.
    #
    # Parameters:
    #	args... -
    #		Globs for names of the procedures to replace. The names do NOT
    #		need to be fully-qualified.
    #
    # Results:
    #	The LLVM reference to the module containing the commands that have
    #	been made to replace the given collection of procedures.

    proc optimise {args} {
	variable counter
	variable debug
	variable optimiseLevel
	variable thunkBuilder
	variable time

	timeit get-command-list {
	    # Convert globs to a list of procedures
	    set cmds {}
	    foreach glob $args {
		lappend cmds {*}[uplevel 1 [list info commands $glob]]
	    }
	    # Work out what we're *really* talking about
	    set cmds [lmap p $cmds {uplevel 1 [list namespace which $p]}]
	    # Strip any duplicates
	    set cmds [lsort -unique $cmds]
	}

	timeit init-module {
	    set ns [uplevel 1 {namespace current}]
	    set name [SelectModuleName $ns]
	    set module [Module new $name]

	    # Get an instance of the system that glues things to the Tcl
	    # runtime.
	    set thunkBuilder [ThunkBuilder new $module]
	    set sp [quadcode::specializer new]
	}

	try {
	    set required {}
	    set compiledProcs {}
	    set publicInterface {}

	    timeit register {
		foreach cmd $cmds {
		    $sp register $cmd
		    set r [lmap - [info args $cmd] {
			set quadcode::dataType::STRING
		    }]
		    $sp require $cmd $r
		    dict set required $cmd $r
		}
	    }

	    timeit specialise {
		$sp computeTypes
		foreach triple [$sp instancesNeeded] {
		    lassign $triple cmd argTypes
		    set c [TclInterproceduralCompiler new $sp $cmd $argTypes]
		    lappend compiledProcs $c
		    if {$argTypes eq [dict get $required $cmd]} {
			lappend publicInterface $c
		    }
		}
	    }

	    timeit generate {
		# Now we generate declarations for the functions we'll build
		foreach c $compiledProcs {
		    $c generateDeclaration $module
		}

		# Spit the code out
		foreach c $compiledProcs {
		    if {$debug} {
			$c printTypedQuads stdout
		    }
		    $c compile
		}

		# For code that needs to bind to Tcl, make the thunks. Then
		# finalise the thunks, which finishes building the module's
		# init function.
		foreach c $publicInterface {
		    $c generateThunk $thunkBuilder
		}
		$thunkBuilder finalize
	    }

	    timeit dump-pre {
		# Save the current IR
		variable dumpPre [$module dump]
		variable bitcodePre [$module bitcode]
	    }

	    # Check that what we have is actually correct!
	    $module verify
	    if {$debug} {
		parray ::useCount
	    }

	    timeit optimize {
		# Run the LLVM IR optimizer. The configuration of this is in
		# llvmtcl and is due to Jos Decoster.
		$module optimize $optimiseLevel
	    }

	    timeit dump-post {
		# Save the current IR
		variable dumpPost [$module dump]
		variable bitcodePost [$module bitcode]
	    }

	    timeit assemble {
		# Call the package init function. This causes native code to
		# be issued and linked.
		$module mcjit
		$thunkBuilder install
	    }

	    # Return the LLVM handle to the module, just in case.
	    #
	    # Note that it is *UNSAFE* to uninstall this package (unless all
	    # commands it creates are deleted, since we don't do any custom
	    # Tcl_ObjType magic or other awkward stuff).
	    return [$module ref]
	} finally {
	    # Note, this *doesn't* destroy the module or any of the compiled
	    # procedures it contains at the LLVM level
	    $module destroy
	    foreach cp $compiledProcs {
		$cp destroy
	    }
	    $sp destroy
	}
    }

    # LLVM::compiletodll --
    #
    #	Apply the LLVM compilation and optimisation engine to a collection of
    #	procedures. Upon success, this will write code to implement the
    #	procedures to the given shared library file; [load]ing that file would
    #	REPLACE the procedures with compiled commands.
    #
    # Parameters:
    #	filename -
    #		The name of the file to create. The system shared library
    #		extension will be appended if the file has no extension.
    #		Giving the path to the file is RECOMMENDED.
    #	args... -
    #		Globs for names of the procedures to replace. The names do NOT
    #		need to be fully-qualified.
    #
    # Results:
    #	The name of the module in the file, as required for [load].

    proc compiletodll {filename args} {
	variable counter
	variable debug
	variable optimiseLevel
	variable thunkBuilder
	variable time
	variable objectExtension

	if {[file extension $filename] eq ""} {
	    append filename [info sharedlibextension]
	}

	# Convert globs to a list of procedures
	set cmds {}
	foreach glob $args {
	    lappend cmds {*}[uplevel 1 [list info commands $glob]]
	}
	# Work out what we're *really* talking about
	set cmds [lmap p $cmds {uplevel 1 [list namespace which $p]}]
	# Strip any duplicates
	set cmds [lsort -unique $cmds]

	set ns [uplevel 1 {namespace current}]
	set name [SelectModuleName $ns]
	set module [Module new $name]

	# Get an instance of the system that glues things to the Tcl runtime.
	set thunkBuilder [ThunkBuilder new $module]
	set sp [quadcode::specializer new]

	try {
	    set required {}
	    set compiledProcs {}
	    set publicInterface {}

	    foreach cmd $cmds {
		$sp register $cmd
		set r [lmap - [info args $cmd] {
		    set quadcode::dataType::STRING
		}]
		$sp require $cmd $r
		dict set required $cmd $r
	    }

	    $sp computeTypes
	    foreach triple [$sp instancesNeeded] {
		lassign $triple cmd argTypes
		set c [TclInterproceduralCompiler new $sp $cmd $argTypes]
		lappend compiledProcs $c
		if {$argTypes eq [dict get $required $cmd]} {
		    lappend publicInterface $c
		}
	    }

	    # Now we generate declarations for the functions we'll build
	    foreach c $compiledProcs {
		$c generateDeclaration $module

		if {$debug} {
		    $c printTypedQuads stdout
		}
	    }

	    # Spit the code out
	    foreach c $compiledProcs {
		$c compile
	    }

	    # For code that needs to bind to Tcl, make the thunks. Then
	    # finalise the thunks, which finishes building the module's init
	    # function.
	    foreach c $publicInterface {
		$c generateThunk $thunkBuilder
	    }
	    $thunkBuilder finalize

	    # Save the current IR
	    variable dumpPre [$module dump]
	    variable bitcodePre [$module bitcode]

	    # Check that what we have is actually correct!
	    $module verify

	    $module optimize $optimiseLevel

	    # Convert to DLL
	    set f [file tempfile infile $name.bc]
	    close [file tempfile outfile $name$objectExtension]
	    try {
		fconfigure $f -translation binary
		puts -nonewline $f [$module bitcode]
		close $f

		Llc $infile $outfile
		Link $outfile $filename
	    } finally {
		file delete $infile
		file delete $outfile
	    }

	    return [regsub {_Init$} [[$module getInitFunction] name] ""]
	} finally {
	    # Note, this *doesn't* destroy the module or any of the compiled
	    # procedures it contains at the LLVM level
	    $module destroy
	    foreach cp $compiledProcs {
		$cp destroy
	    }
	    $sp destroy
	}
    }

    # LLVM::compilepackagetodll --
    #
    #	Apply the LLVM compilation and optimisation engine to the procedures
    #	in a package, under the assumption that the package defines its
    #	procedures eagerly. Upon success, this will write code to implement
    #	the procedures to the given shared library file; [load]ing that file
    #	would REPLACE the procedures with compiled commands.
    #
    #	Any packages that are depended-upon and which shouldn't be compiled
    #	should be [package require]d first.
    #
    # Parameters:
    #	package -
    #		The name of the package to compile. If a two-element list, the
    #		second element is the version of the package to request.
    #	filename (optional) -
    #		The name of the file to create. The system shared library
    #		extension will be appended if the file has no extension.
    #		Giving the path to the file is RECOMMENDED. If not supplied,
    #		the current directory is used, the filename prefix 'lib' is
    #		used, then the package name, then the shared library suffix.
    #		The version is not inserted by default.
    #
    # Results:
    #	The full name of the module in the file, as required for [load].

    proc compilepackagetodll {package {filename ""}} {
	variable counter
	variable debug
	variable optimiseLevel
	variable thunkBuilder
	variable time
	variable packageProcedures
	variable objectExtension

	lassign $package packageName packageVersion
	if {$filename eq ""} {
	    set filename [pwd]/lib$packageName
	}
	if {[file extension $filename] eq ""} {
	    append filename [info sharedlibextension]
	}

	# Discover the procedures in the package; assumes no lazy loading!
	#
	# First, we reload the package DB. Then we resolve the package version
	# if we hadn't already done so. Finally, we load the package with an
	# execution trace in place so that procedures get logged as needing
	# compilation as soon as they are created.

	catch {package require THERE_IS_NO_SUCH_PACKAGE}
	if {$packageVersion eq ""} {
	    set packageVersion [lindex [package versions $packageName] 0]
	}

	set p_id [list $packageName $packageVersion]
	set packageProcedures($p_id) {}
	set traceCallback [list apply [list {p_id cmd code info op} {
	    variable packageProcedures
	    if {$code == 0} {
		set realcmd [uplevel 1 [list \
			namespace which -command [lindex $cmd 1]]]
		lappend packageProcedures($p_id) $realcmd
	    }
	} [namespace current]] $p_id]

	try {
	    trace add execution proc leave $traceCallback
	    package require {*}$p_id
	} finally {
	    trace remove execution proc leave $traceCallback
	}
	set pkgfile /dev/null
	set IfneededParserRE {\ysource (?:\{([^{}]+)\}|([^ ;]+))}
	if {[regexp $IfneededParserRE [package ifneeded {*}$p_id] - fa fb]} {
	    # One of these will be set to the filename we want; the other will
	    # be an empty string.
	    set pkgfile [file normalize $fa$fb]
	    set idxfile [file join [file dirname $pkgfile] pkgIndex.tcl]
	    if {[file exists $idxfile]} {
		set pkgfile $idxfile
	    }
	}

	# Convert list of commands and package name into what the compiler
	# really wants.
	set cmds [lsort -unique $packageProcedures($p_id)]
	unset -nocomplain packageProcedures($p_id)
	set name [SelectModuleName $packageName]
	set module [Module new $name $pkgfile]

	# Get an instance of the system that glues things to the Tcl runtime.
	set thunkBuilder [ThunkBuilder new $module]
	set sp [quadcode::specializer new]

	try {
	    set required {}
	    set compiledProcs {}
	    set publicInterface {}

	    foreach cmd $cmds {
		if {[catch {info args $cmd}]} {
		    puts "WARNING: skipping $cmd because it isn't a procedure"
		    continue
		}
		if {[catch {
		    $sp register $cmd
		} msg]} {
		    puts "WARNING: skipping $cmd:\n$msg"
		    continue
		}
		set r [lmap - [info args $cmd] {
		    set quadcode::dataType::STRING
		}]
		$sp require $cmd $r
		dict set required $cmd $r
	    }

	    $sp computeTypes
	    foreach triple [$sp instancesNeeded] {
		lassign $triple cmd argTypes
		set c [TclInterproceduralCompiler new $sp $cmd $argTypes]
		lappend compiledProcs $c
		if {$argTypes eq [dict get $required $cmd]} {
		    lappend publicInterface $c
		}
	    }

	    # Now we generate declarations for the functions we'll build
	    foreach c $compiledProcs {
		$c generateDeclaration $module

		if {$debug} {
		    $c printTypedQuads stdout
		}
	    }

	    # Spit the code out
	    foreach c $compiledProcs {
		$c compile
	    }

	    # For code that needs to bind to Tcl, make the thunks. Then
	    # finalise the thunks, which finishes building the module's init
	    # function.
	    foreach c $publicInterface {
		$c generateThunk $thunkBuilder
	    }
	    set pkginfo [$thunkBuilder finalize $packageVersion]

	    # Check that what we have is actually correct!
	    $module verify

	    # Do the optimization itself
	    $module optimize $optimiseLevel

	    # Apply garbage collection
	    $module gcfuncs

	    # In debug mode, print the LLVM IR at this point
	    if {$debug} {
		puts "===DUMPING MODULE IR==="
		puts [$module dump]
	    }

	    # Convert to DLL
	    close [file tempfile outfile $name$objectExtension]
	    try {
		$module writeobject $outfile
		Link $outfile $filename
	    } finally {
		file delete $outfile
	    }

	    set initfunc [regsub {_Init$} [[$module getInitFunction] name] ""]
	    return [list package ifneeded {*}$pkginfo [list load $filename $initfunc]]
	} finally {
	    # Note, this *doesn't* destroy the module or any of the compiled
	    # procedures it contains at the LLVM level
	    $module destroy
	    foreach cp $compiledProcs {
		$cp destroy
	    }
	    $sp destroy
	}
    }

    # LLVM::Llc --
    #
    #	Run the LLVM llc program to convert a bitcode file into an object file.
    #
    #	It is up to the caller to use the right extensions.
    #
    # Parameters:
    #	inputFilename -
    #		The name of the bitcode file containing the implementation.
    #	outputFilename -
    #		The name of the object file to create.
    #
    # Results:
    #	None.

    proc Llc {inputFilename outputFilename} {
	variable LlcExecutable

	# TODO: Are these the best options?
	set optimizations {
	    -O=1
	    -relocation-model=pic
	    -thread-model=single
	}
	# -funit-at-a-time

	exec $LlcExecutable {*}$optimizations -filetype=obj 2>@stderr \
	    -o [file normalize $outputFilename] [file normalize $inputFilename]
	return
    }

    # LLVM::Link --
    #
    #	Run the linker to convert an object file into a loadable DLL.
    #
    #	It is up to the caller to use the right extensions.
    #
    # Parameters:
    #	objectFilename -
    #		The name of the object file containing the implementation.
    #	libraryFilename -
    #		The name of the DLL to create.
    #
    # Results:
    #	None.

    proc Link {objectFilename libraryFilename} {
	variable useStubs
	variable LinkerExecutable
	if {![info exists LinkerExecutable]} {
	    return -code error \
		"could not determine suitable system object linker"
	}

	if {$::tcl_platform(os) eq "Darwin"} {
	    # TODO: are these the right flags?
	    set linkflags {
		-dynamiclib
		-prebind
		-headerpad_max_install_names
		-Wl,-search_paths_first
		-Wl,-single_module
	    }
	} else {
	    # These seem to work on Linux
	    set linkflags {-shared -fPIC}
	}

	if {!$useStubs} {
	    set libdir [tcl::pkgconfig get libdir,runtime]
	    # MacOSX is tricky: builds don't need to use the framework system
	    if {[string match "*/Tcl.framework/*" $libdir]} {
		lappend linkflags -F$libdir -framework Tcl
	    } else {
		lappend linkflags -L$libdir -ltcl[info tclversion]
	    }
	}

	exec $LinkerExecutable {*}$linkflags \
	    -o [file normalize $libraryFilename] \
	    [file normalize $objectFilename] 2>@stderr
	return
    }

    # LLVM::pre --
    #
    #	Report the LLVM IR that was produced prior to applying the LLVM
    #	optimisation engine.
    #
    # Parameters:
    #	bitcode (optional) -
    #		Whether to return the bitcode version of the code. If false
    #		(the default), returns the human-readable IR.
    #
    # Results:
    #	LLVM IR code, in human-readable form, or bitcode (machine-readable
    #	only).

    proc pre {{bitcode false}} {
	variable dumpPre
	variable bitcodePre
	if {$bitcode} {
	    return $bitcodePre
	}
	return [string trim $dumpPre]
    }

    # LLVM::post --
    #
    #	Report the LLVM IR that was produced after applying the LLVM
    #	optimisation engine.
    #
    # Parameters:
    #	bitcode (optional) -
    #		Whether to return the bitcode version of the code. If false
    #		(the default), returns the human-readable IR.
    #
    # Results:
    #	LLVM IR code, in human-readable form, or bitcode (machine-readable
    #	only).

    proc post {{bitcode false}} {
	variable dumpPost
	variable bitcodePost
	if {$bitcode} {
	    return $bitcodePost
	}
	return [string trim $dumpPost]
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/llvmbuilder.tcl.

193
194
195
196
197
198
199

200







201
202
203
204
205
206
207
208
...
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
....
1333
1334
1335
1336
1337
1338
1339













1340
1341
1342
1343
1344
1345

1346
	    ? $n > [llength $arguments]
	    : $n != [llength $arguments]
	} then {
	    return -code error [format \
		"wrong # args to function '%s': expected %d but got %d" \
		[GetValueName $function] $n [llength $arguments]]
	}

	foreach ptype [GetParamTypes $ftype] arg $arguments {







	    if {[incr i] > $n} break
	    if {$ptype ne [TypeOf $arg]} {
		return -code error [format \
			"argument %d to %s: expected type '%s' but got '%s'" \
			$i [GetValueName $function] [PrintTypeToString $ptype]\
			[PrintValueToString $arg]]
	    }
	}
................................................................................
    method offsetof {type field} {
	my @validToIssue
	set t [Type $type]
	if {[GetTypeKind $t] ne "LLVMStructTypeKind"} {
	    return -code error \
		"can only get offsets of fields in named structures"
	}
	set n [my gep [my castInt2Ptr [Const 0] $t*] $type.$field]
	return [my castPtr2Int $n int32 "$type.$field.offset"]
    }

    # Builder:or --
    #
    #	Generate code to compute the bitwise-or of two integers of the same
    #	bit width.
................................................................................
    # Just adds some type-checking
    method LABEL {block} {
	if {[info object class $block] ne "::LLVM::Block"} {
	    return -code error -level 2 "block must be a basic block"
	}
	return [$block ref]
    }













}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







>

>
>
>
>
>
>
>
|







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>






>

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
...
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
....
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
	    ? $n > [llength $arguments]
	    : $n != [llength $arguments]
	} then {
	    return -code error [format \
		"wrong # args to function '%s': expected %d but got %d" \
		[GetValueName $function] $n [llength $arguments]]
	}
	set i 0
	foreach ptype [GetParamTypes $ftype] arg $arguments {
	    if {$arg eq ""} {
		if {$ptype eq ""} {
		    set ptype [Type void*]
		}
		set arg [my null $ptype]
		lset arguments $i $arg
	    }
	    if {[incr i] > $n} continue
	    if {$ptype ne [TypeOf $arg]} {
		return -code error [format \
			"argument %d to %s: expected type '%s' but got '%s'" \
			$i [GetValueName $function] [PrintTypeToString $ptype]\
			[PrintValueToString $arg]]
	    }
	}
................................................................................
    method offsetof {type field} {
	my @validToIssue
	set t [Type $type]
	if {[GetTypeKind $t] ne "LLVMStructTypeKind"} {
	    return -code error \
		"can only get offsets of fields in named structures"
	}
	set n [my gep [my castInt2Ptr [Const 0] $t*] 0 $type.$field]
	return [my castPtr2Int $n int32 "$type.$field.offset"]
    }

    # Builder:or --
    #
    #	Generate code to compute the bitwise-or of two integers of the same
    #	bit width.
................................................................................
    # Just adds some type-checking
    method LABEL {block} {
	if {[info object class $block] ne "::LLVM::Block"} {
	    return -code error -level 2 "block must be a basic block"
	}
	return [$block ref]
    }

    method AddLineDirectives {lineNumber file body} {
	set script ""
	foreach line [split $body "\n"] {
	    if {[info complete $script]} {
		append script [list [self] @location $lineNumber $file] ";"
	    }
	    incr lineNumber
	    append script $line "\n"
	}
	return $script
    }
    export AddLineDirectives
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/macros.tcl.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
..
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
..
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
...
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
...
154
155
156
157
158
159
160
161
162
163

164




165
166
167
168
169
170
171
...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
...
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
...
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
...
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
...
400
401
402
403
404
405
406

407




408
409
410
411
412
413
414
...
445
446
447
448
449
450
451

452






453





454
455
456
457
458
459
460
...
511
512
513
514
515
516
517

518
519

520
521
522
523
524
525
526
...
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
...
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
...
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
...
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
...
730
731
732
733
734
735
736

737
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.Tcl_IncrRefCount {} {
	set f [$m local Tcl_IncrRefCount void<-Tcl_Obj*]
	my closure Tcl_IncrRefCount objPtr {
	    $b Call $Tcl_IncrRefCount $objPtr
	    return
	}

	params objPtr
	build {
................................................................................
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.Tcl_DecrRefCount {} {
	set f [$m local Tcl_DecrRefCount void<-Tcl_Obj*]
	my closure Tcl_DecrRefCount objPtr {
	    $b Call $Tcl_DecrRefCount $objPtr
	    return
	}

	params objPtr
	build {
................................................................................
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.TclFreeIntRep {} {
	set f [$m local TclFreeIntRep void<-Tcl_Obj*]
	my closure TclFreeIntRep objPtr {
	    $b Call $TclFreeIntRep $objPtr
	    return
	}

	params objPtr
	build {
	    nonnull $objPtr
	    set typeField [$b gep $objPtr 0 Tcl_Obj.typePtr]
	    set typePtr [$b load $typeField "typePtr"]
	    $b condBr [$b nonnull $typePtr] $check $done 
	label check:
	    set freeIntRepProc [$b dereference $typePtr 0 \
		    Tcl_ObjType.freeIntRepProc]
	    $b condBr [$b nonnull $freeIntRepProc] $free $clear
	label free:
	    set freeIntRep [$b cast(ptr) $freeIntRepProc \
		    func{void<-Tcl_Obj*} "freeIntRep"]
	    $b Call $freeIntRep $objPtr
	    $b br $clear
	label clear:
	    $b store [$b null Tcl_ObjType*] $typeField
	    $b br $done
	label done:
	    $b ret
	}

	oo::objdefine [self] export TclFreeIntRep
    }
................................................................................
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.TclInvalidateStringRep {} {
	set f [$m local TclInvalidateStringRep void<-Tcl_Obj*]
	my closure TclInvalidateStringRep objPtr {
	    $b Call $TclInvalidateStringRep $objPtr
	    return
	}

	params objPtr
	build {
................................................................................
	    set bytesField [$b gep $objPtr 0 Tcl_Obj.bytes]
	    set bytes [$b load $bytesField "bytes"]
	    $b condBr [$b nonnull $bytes] $actblock $doneblock
	label actblock "act"
	    $b condBr [$b neq $bytes [my tclEmptyStringRep]] \
		$freeblock $clearblock
	label freeblock "free"
	    set bytes [$b cast(ptr) $bytes void]
	    my Tcl_Free $bytes
	    if {![info exist ::env(NOASSERTS)]} {

		$b Call [$m intrinsic lifetime.end] [Const -1 int64] $bytes




	    }
	    $b br $clearblock
	label clearblock "clear"
	    $b store [$b null char*] $bytesField
	    $b br $doneblock
	label doneblock "done"
	    $b ret
................................................................................
    #
    # ThunkBuilder:Tcl_GetHashValue --
    #
    #	Get the value from a hash entry.
    #
    # Parameters:
    #	hashEntryPtr -
    #		The LLVM value reference to the Tcl_HashEntry*.
    #	type (optional) -
    #		The desired type of the result, to which the value will be
    #		cast. If omitted, the default (void*) will be used.
    #
    # Results:
    #	The hash value in the hash entry.
    #
................................................................................
    #
    # ThunkBuilder:Tcl_SetHashValue --
    #
    #	Set the value in a hash entry.
    #
    # Parameters:
    #	hashEntryPtr -
    #		The LLVM value reference to the Tcl_HashEntry*.
    #	value -	The value to be set in the hash entry.
    #
    # Results:
    #	None.
    #
    # ------------------------------------------------------------------
    #
    # ThunkBuilder:TclCreateHashEntry --
    #
    #	Create the entry for a hash key.
    #
    # Parameters:
    #	hashTablePtr -
    #		The LLVM value reference to the Tcl_HashTable*.
    #	key -	The key to be looked up in the hash table.
    #	isNew (optional) -
    #		Where to store the flag as to whether the entry is new or not.
    #
    # Results:
    #	The LLVM value reference to the Tcl_HashEntry*.
    #
    # ------------------------------------------------------------------
    #
    # ThunkBuilder:TclFindHashEntry --
    #
    #	Get the entry for a hash key.
    #
    # Parameters:
    #	hashTablePtr -
    #		The LLVM value reference to the Tcl_HashTable*.
    #	key -	The key to be looked up in the hash table.
    #
    # Results:
    #	The LLVM value reference to the Tcl_HashEntry*.

    method @macros.TclHashTable {} {
	my closure Tcl_GetHashValue {hashEntryPtr {type ""}} {
	    set value [$b dereference $hashEntryPtr 0 Tcl_HashEntry.clientData]
	    if {$type ne ""} {
		set type [Type $type]
		switch [GetTypeKind $type] {
		    "LLVMPointerTypeKind" {
			set value [$b castPtr2Ptr $value $type]
		    }
		    "LLVMIntegerTypeKind" {
................................................................................
	    }
	    return $value
	}

	my closure Tcl_SetHashValue {hashEntryPtr value} {
	    switch [GetTypeKind [TypeOf $value]] {
		"LLVMPointerTypeKind" {
		    set value [$b castPtr2Ptr $value [Type void*]]
		}
		"LLVMIntegerTypeKind" {
		    set value [$b castInt2Ptr $value [Type void*]]
		}
		default {
		    return -code error \
			"can only store pointers and integers safely"
		}
	    }
	    $b store $value [$b gep $hashEntryPtr 0 Tcl_HashEntry.clientData]
	    return
	}

	my closure TclFindHashEntry {hashTablePtr key} {
	    switch [GetTypeKind [TypeOf $key]] {
		"LLVMPointerTypeKind" {
		    set key [$b castPtr2Ptr $key [Type void*] "key"]
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	LLVM value reference to pointer to the allocated memory.

    method @macros.ckalloc {size_t} {
	my closure ckalloc {size {type ""} {name "ptr"}} {

	    if {[string is integer -strict $size]} {
		set size [Const $size $size_t]

	    }
	    if {[::tcl::pkgconfig get debug]} {
		set frameinfo [info frame -1]
		set file "/dev/null"
		if {[dict exists $frameinfo file]} {
		    set file [dict get $frameinfo file]
		}
		set file [$b constString $file "source.filename"]
		set line [Const [dict get $frameinfo line]]
		set block [my Tcl_DbCkalloc $size $file $line]
	    } else {
		set block [my Tcl_Alloc $size]
	    }

	    SetValueName $block $name

	    if {![info exist ::env(NOASSERTS)]} {

		$b Call [$m intrinsic lifetime.start] [Const -1 int64] $block





	    }
	    if {$type ne ""} {
		set block [$b cast(ptr) $block $type $name]
	    }
	    return $block
	}

................................................................................
		set file [$b constString $file "source.filename"]
		set line [Const [dict get $frameinfo line]]
		my Tcl_DbCkfree $block $file $line
	    } else {
		my Tcl_Free $block
	    }
	    if {![info exist ::env(NOASSERTS)]} {

		$b Call [$m intrinsic lifetime.end] [Const -1 int64] $block




	    }
	    return
	}
    }

    # ------------------------------------------------------------------
    #
................................................................................
		set newblock [my Tcl_DbCkrealloc $oldblock $size $file $line]
	    } else {
		set newblock [my Tcl_Realloc $oldblock $size]
	    }
	    SetValueName $newblock "$name.new"
	    if {![info exist ::env(NOASSERTS)]} {
		set flag [Const -1 int64]

		$b Call [$m intrinsic lifetime.end] $flag $oldblock






		$b Call [$m intrinsic lifetime.start] $flag $newblock





	    }
	    return [$b cast(ptr2ptr) $newblock [TypeOf $object] $name]
	}
    }
 
    # ------------------------------------------------------------------
    #
................................................................................
	    set var [$m variable $name Tcl_Obj* [$b null Tcl_Obj*]]
	    set obj.constants.defined($name) $var

	    if {!$existing} {
		set str [$b constString $content $name2]
		set len [Const [string bytelength $content] int]
		if {[info exist metathunkblock]} {

		    $metathunkblock build $b {
			$b Call ${tcl.obj.constant} $var $str $len

		    }
		} else {
		    lappend obj.constants.pending $var $str $len
		}
	    }

	    set obj [$b loadInvariant $var]
................................................................................
    #
    # Parameters:
    #	constant -
    #		The Tcl string containing the dictionary mapping strings to
    #		small positive integers.
    #
    # Results:
    #	LLVM value reference to the Tcl_HashTable*.

    method @macros.jumptable.constant {} {
	set f [$m local "bootstrap.JumpTable.constant" \
		void<-Tcl_HashTable*,Tcl_Obj* noinline]
	params theHash:hashPtr theData:objPtr
	build {
	    noalias $theHash $theData
	    nonnull $theHash $theData
	    my Tcl_InitObjHashTable $theHash
	    set searchPtr [$b alloc Tcl_DictSearch "search"]
	    set keyPtr [$b alloc Tcl_Obj* "key"]
	    set valuePtr [$b alloc Tcl_Obj* "value"]
	    set donePtr [$b alloc int "done"]
	    set jumpPtr [$b alloc int "jump"]
	    my Tcl_DictObjFirst {} $theData $searchPtr \
		    $keyPtr $valuePtr $donePtr
	    $b condBr [$b eq [$b load $donePtr "done"] [Const 0]] \
................................................................................
	my closure jumptable.constant {content} {
	    variable metathunkblock
	    variable jumptablecounter

	    # verify map to int
	    foreach v [dict values $content] {incr v 0}
	    set name jumptable.[incr jumptablecounter]
	    set var [$m variable $name Tcl_HashTable [$b undef Tcl_HashTable]]

	    $metathunkblock build $b {
		set init [my obj.constant $content]
		set call [$b Call [$f ref] $var $init]
		AddCallAttribute $call 1 nocapture
		AddCallAttribute $call 2 nocapture

	    }
	    return $var
	}
	oo::objdefine $b forward @jumptable.constant [self] jumptable.constant
    }
 
    method @macros {} {
	upvar 1 size_t size_t


	my @macros.Tcl_IncrRefCount
	my @macros.Tcl_DecrRefCount
	my @macros.TclFreeIntRep
	my @macros.TclInvalidateStringRep
	my @macros.TclHashTable
	my @macros.ckalloc $size_t

	my @macros.ckfree
	my @macros.ckrealloc $size_t
	my @macros.obj.constant
	my @macros.jumptable.constant


	# ------------------------------------------------------------------
	#
	# ThunkBuilder:writeline --
	#
	#	Debugging helper that writes a string to standard out as its
	#	own line.
................................................................................
	# Parameters:
	#	s -	The Tcl string to write.
	#
	# Results:
	#	None.

	set f [$m local writeline void<-char*,int noinline]















	my closure writeline s {
	    append s "\n"
	    $b Call writeline [$b constString $s] \
		[Const [string bytelength $s]]
	    return
	}
	params string length
	build {
	    nonnull $string
	    set signature func{int<-int,void*,int}
	    set write [$m function.extern write [Type $signature]]
	    $b call $write [list [Const 1] $string $length]
	    $b ret
	}

	# ------------------------------------------------------------------
	#
	# ThunkBuilder:writeint --
	#
	#	Debugging helper that writes an unsigned 32-bit number to
	#	standard out as its own line. The number is written in
................................................................................
	#		This is a Tcl string.
	#
	# Results:
	#	None.

	set f [$m local writeint void<-int noinline]
	params n

	build {
	    set s [$b constString "0123456789ABCDEF"]
	    $b condBr [$b eq $n [Const 0]] $zero $num

	label zero:
	    $b Call writeline [$b getelementptr $s [Const 0]] [Const 1]
	    $b br $done
	label num:
	    set nn [$b alloc int]
	    $b store $n $nn
	    $b br $test
	label test:
	    set n_ [$b load $nn]
	    $b condBr [$b eq $n_ [Const 0]] $done $body

	label body:
	    set nd [$b div $n_ [Const 16]]
	    set n0 [$b sub $n_ [$b mult $nd [Const 16]]]
	    $b store $nd $nn
	    $b Call writeline [$b getelementptr $s $n0] [Const 1]
	    $b br $test
	label done:
	    my writeline ""
	    $b ret
	}











	my closure writeint {i {msg ""}} {
	    if {$msg ne ""} {
		$b Call writeline [$b constString $msg] \
		    [Const [string bytelength $msg]]
	    }
	    $b Call writeint $i
	}




























































































	# ------------------------------------------------------------------
	#
	# ThunkBuilder:stork --
	#
	#	Helper for enforcement of Tcl's 'stork' property of Tcl_Objs,
	#	i.e., that values must always have at least one a string
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







|
|







 







|
|







 







|
|










|

|
|
|

<
<



|







 







|
|







 







|
|

>
|
>
>
>
>







 







|







 







|













|





|









|



|



|







 







|


|






|







 







>


>













>
|
>

>
|
>
>
>
>
>







 







>
|
>
>
>
>







 







>
|
>
>
>
>
>
>
|
>
>
>
>
>







 







>
|
|
>







 







|



|





|







 







|
>
|
|
|
|
|
>






|
<
|
>
|
|
|
|
<
<
>
|
<
<
<
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






<
<
<
<
<
<
<
<







 







>
|
|
|
>
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
..
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
..
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
...
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
...
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
...
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
...
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
...
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
...
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
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
...
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
...
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
...
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
...
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
...
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
...
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
...
873
874
875
876
877
878
879
880
881
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.Tcl_IncrRefCount {{inline {}}} {
	set f [$m local Tcl_IncrRefCount void<-Tcl_Obj* {*}$inline]
	my closure Tcl_IncrRefCount objPtr {
	    $b Call $Tcl_IncrRefCount $objPtr
	    return
	}

	params objPtr
	build {
................................................................................
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.Tcl_DecrRefCount {{inline {}}} {
	set f [$m local Tcl_DecrRefCount void<-Tcl_Obj* {*}$inline]
	my closure Tcl_DecrRefCount objPtr {
	    $b Call $Tcl_DecrRefCount $objPtr
	    return
	}

	params objPtr
	build {
................................................................................
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.TclFreeIntRep {{inline {}}} {
	set f [$m local TclFreeIntRep void<-Tcl_Obj* {*}$inline]
	my closure TclFreeIntRep objPtr {
	    $b Call $TclFreeIntRep $objPtr
	    return
	}

	params objPtr
	build {
	    nonnull $objPtr
	    set typeField [$b gep $objPtr 0 Tcl_Obj.typePtr]
	    set typePtr [$b load $typeField "typePtr"]
	    $b condBr [$b nonnull $typePtr] $check $done
	label check:
	    set freeIntRep [$b dereference $typePtr 0 \
		    ObjType.freeIntRepProc]
	    $b condBr [$b nonnull $freeIntRep] $free $clear
	label free:


	    $b Call $freeIntRep $objPtr
	    $b br $clear
	label clear:
	    $b store [$b null ObjType*] $typeField
	    $b br $done
	label done:
	    $b ret
	}

	oo::objdefine [self] export TclFreeIntRep
    }
................................................................................
    # Parameters:
    #	objPtr -
    #		The LLVM value reference to the Tcl_Obj*.
    #
    # Results:
    #	None.

    method @macros.TclInvalidateStringRep {{inline {}}} {
	set f [$m local TclInvalidateStringRep void<-Tcl_Obj* {*}$inline]
	my closure TclInvalidateStringRep objPtr {
	    $b Call $TclInvalidateStringRep $objPtr
	    return
	}

	params objPtr
	build {
................................................................................
	    set bytesField [$b gep $objPtr 0 Tcl_Obj.bytes]
	    set bytes [$b load $bytesField "bytes"]
	    $b condBr [$b nonnull $bytes] $actblock $doneblock
	label actblock "act"
	    $b condBr [$b neq $bytes [my tclEmptyStringRep]] \
		$freeblock $clearblock
	label freeblock "free"
	    set rbytes [$b cast(ptr) $bytes void]
	    my Tcl_Free $rbytes
	    if {![info exist ::env(NOASSERTS)]} {
		if {[catch {
		    $b Call [$m intrinsic lifetime.end] [Const -1 int64] $bytes
		}]} {
		    $b Call [$m intrinsic lifetime.end [TypeOf $bytes]] \
			[Const -1 int64] $bytes
		}
	    }
	    $b br $clearblock
	label clearblock "clear"
	    $b store [$b null char*] $bytesField
	    $b br $doneblock
	label doneblock "done"
	    $b ret
................................................................................
    #
    # ThunkBuilder:Tcl_GetHashValue --
    #
    #	Get the value from a hash entry.
    #
    # Parameters:
    #	hashEntryPtr -
    #		The LLVM value reference to the HashEntry*.
    #	type (optional) -
    #		The desired type of the result, to which the value will be
    #		cast. If omitted, the default (void*) will be used.
    #
    # Results:
    #	The hash value in the hash entry.
    #
................................................................................
    #
    # ThunkBuilder:Tcl_SetHashValue --
    #
    #	Set the value in a hash entry.
    #
    # Parameters:
    #	hashEntryPtr -
    #		The LLVM value reference to the HashEntry*.
    #	value -	The value to be set in the hash entry.
    #
    # Results:
    #	None.
    #
    # ------------------------------------------------------------------
    #
    # ThunkBuilder:TclCreateHashEntry --
    #
    #	Create the entry for a hash key.
    #
    # Parameters:
    #	hashTablePtr -
    #		The LLVM value reference to the HashTable*.
    #	key -	The key to be looked up in the hash table.
    #	isNew (optional) -
    #		Where to store the flag as to whether the entry is new or not.
    #
    # Results:
    #	The LLVM value reference to the HashEntry*.
    #
    # ------------------------------------------------------------------
    #
    # ThunkBuilder:TclFindHashEntry --
    #
    #	Get the entry for a hash key.
    #
    # Parameters:
    #	hashTablePtr -
    #		The LLVM value reference to the HashTable*.
    #	key -	The key to be looked up in the hash table.
    #
    # Results:
    #	The LLVM value reference to the HashEntry*.

    method @macros.TclHashTable {} {
	my closure Tcl_GetHashValue {hashEntryPtr {type ""}} {
	    set value [$b dereference $hashEntryPtr 0 HashEntry.clientData]
	    if {$type ne ""} {
		set type [Type $type]
		switch [GetTypeKind $type] {
		    "LLVMPointerTypeKind" {
			set value [$b castPtr2Ptr $value $type]
		    }
		    "LLVMIntegerTypeKind" {
................................................................................
	    }
	    return $value
	}

	my closure Tcl_SetHashValue {hashEntryPtr value} {
	    switch [GetTypeKind [TypeOf $value]] {
		"LLVMPointerTypeKind" {
		    set value [$b castPtr2Ptr $value [Type ClientData]]
		}
		"LLVMIntegerTypeKind" {
		    set value [$b castInt2Ptr $value [Type ClientData]]
		}
		default {
		    return -code error \
			"can only store pointers and integers safely"
		}
	    }
	    $b store $value [$b gep $hashEntryPtr 0 HashEntry.clientData]
	    return
	}

	my closure TclFindHashEntry {hashTablePtr key} {
	    switch [GetTypeKind [TypeOf $key]] {
		"LLVMPointerTypeKind" {
		    set key [$b castPtr2Ptr $key [Type void*] "key"]
................................................................................
    #		A name to give to the result value.
    #
    # Results:
    #	LLVM value reference to pointer to the allocated memory.

    method @macros.ckalloc {size_t} {
	my closure ckalloc {size {type ""} {name "ptr"}} {
	    set sizeconst [Const -1 int64]
	    if {[string is integer -strict $size]} {
		set size [Const $size $size_t]
		set sizeconst [Const $size int64]
	    }
	    if {[::tcl::pkgconfig get debug]} {
		set frameinfo [info frame -1]
		set file "/dev/null"
		if {[dict exists $frameinfo file]} {
		    set file [dict get $frameinfo file]
		}
		set file [$b constString $file "source.filename"]
		set line [Const [dict get $frameinfo line]]
		set block [my Tcl_DbCkalloc $size $file $line]
	    } else {
		set block [my Tcl_Alloc $size]
	    }
	    if {$type eq ""} {
		SetValueName $block $name
	    }
	    if {![info exist ::env(NOASSERTS)]} {
		if {[catch {
		    $b Call [$m intrinsic lifetime.start] \
			$sizeconst $block
		}]} {
		    $b Call [$m intrinsic lifetime.start [TypeOf $block]] \
			$sizeconst $block
		}
	    }
	    if {$type ne ""} {
		set block [$b cast(ptr) $block $type $name]
	    }
	    return $block
	}

................................................................................
		set file [$b constString $file "source.filename"]
		set line [Const [dict get $frameinfo line]]
		my Tcl_DbCkfree $block $file $line
	    } else {
		my Tcl_Free $block
	    }
	    if {![info exist ::env(NOASSERTS)]} {
		if {[catch {
		    $b Call [$m intrinsic lifetime.end] [Const -1 int64] $block
		}]} {
		    $b Call [$m intrinsic lifetime.end [TypeOf $block]] \
			[Const -1 int64] $block
		}
	    }
	    return
	}
    }

    # ------------------------------------------------------------------
    #
................................................................................
		set newblock [my Tcl_DbCkrealloc $oldblock $size $file $line]
	    } else {
		set newblock [my Tcl_Realloc $oldblock $size]
	    }
	    SetValueName $newblock "$name.new"
	    if {![info exist ::env(NOASSERTS)]} {
		set flag [Const -1 int64]
		if {[catch {
		    $b Call [$m intrinsic lifetime.end] \
			[Const -1 int64] $oldblock
		}]} {
		    $b Call [$m intrinsic lifetime.end [TypeOf $oldblock]] \
			[Const -1 int64] $oldblock
		}
		if {[catch {
		    $b Call [$m intrinsic lifetime.start] \
			[Const -1 int64] $newblock
		}]} {
		    $b Call [$m intrinsic lifetime.start [TypeOf $newblock]] \
			[Const -1 int64] $newblock
		}
	    }
	    return [$b cast(ptr2ptr) $newblock [TypeOf $object] $name]
	}
    }
 
    # ------------------------------------------------------------------
    #
................................................................................
	    set var [$m variable $name Tcl_Obj* [$b null Tcl_Obj*]]
	    set obj.constants.defined($name) $var

	    if {!$existing} {
		set str [$b constString $content $name2]
		set len [Const [string bytelength $content] int]
		if {[info exist metathunkblock]} {
		    my buildInSection initConstant {
			$metathunkblock build $b {
			    $b Call ${tcl.obj.constant} $var $str $len
			}
		    }
		} else {
		    lappend obj.constants.pending $var $str $len
		}
	    }

	    set obj [$b loadInvariant $var]
................................................................................
    #
    # Parameters:
    #	constant -
    #		The Tcl string containing the dictionary mapping strings to
    #		small positive integers.
    #
    # Results:
    #	LLVM value reference to the HashTable*.

    method @macros.jumptable.constant {} {
	set f [$m local "bootstrap.JumpTable.constant" \
		void<-HashTable*,Tcl_Obj* noinline]
	params theHash:hashPtr theData:objPtr
	build {
	    noalias $theHash $theData
	    nonnull $theHash $theData
	    my Tcl_InitObjHashTable $theHash
	    set searchPtr [$b alloc DictSearch "search"]
	    set keyPtr [$b alloc Tcl_Obj* "key"]
	    set valuePtr [$b alloc Tcl_Obj* "value"]
	    set donePtr [$b alloc int "done"]
	    set jumpPtr [$b alloc int "jump"]
	    my Tcl_DictObjFirst {} $theData $searchPtr \
		    $keyPtr $valuePtr $donePtr
	    $b condBr [$b eq [$b load $donePtr "done"] [Const 0]] \
................................................................................
	my closure jumptable.constant {content} {
	    variable metathunkblock
	    variable jumptablecounter

	    # verify map to int
	    foreach v [dict values $content] {incr v 0}
	    set name jumptable.[incr jumptablecounter]
	    set var [$m variable $name HashTable [$b undef HashTable]]
	    my buildInSection initConstant {
		$metathunkblock build $b {
		    set init [my obj.constant $content]
		    set call [$b Call [$f ref] $var $init]
		    AddCallAttribute $call 1 nocapture
		    AddCallAttribute $call 2 nocapture
		}
	    }
	    return $var
	}
	oo::objdefine $b forward @jumptable.constant [self] jumptable.constant
    }
 
    # ------------------------------------------------------------------

    #
    # Macros for debugging prints. Note that if you define the environment
    # variable TQC_AVOID_MEMORY_IN_DEBUG_PRINT, you get a message printing
    # system that does not depend in Tcl's memory being free of corruption,
    # but which instead prints numbers and pointers backwards (in order to
    # keep the printing code simpler).



    method @macros.debugprint {} {



	global env tcl_platform

	# ------------------------------------------------------------------
	#
	# ThunkBuilder:writeline --
	#
	#	Debugging helper that writes a string to standard out as its
	#	own line.
................................................................................
	# Parameters:
	#	s -	The Tcl string to write.
	#
	# Results:
	#	None.

	set f [$m local writeline void<-char*,int noinline]
	params string length
	build {
	    nonnull $string
	    if {[info exists env(TQC_AVOID_MEMORY_IN_DEBUG_PRINT)]} {
		set signature func{int<-int,void*,int}
		set write [$m function.extern write [Type $signature]]
		$b call $write [list [Const 1] $string $length]
	    } else {
		set chan [my Tcl_GetStdChannel [Const [expr 1<<3]]]
		my Tcl_WriteChars $chan $string $length
		my Tcl_Flush $chan
	    }
	    $b ret
	}

	my closure writeline s {
	    append s "\n"
	    $b Call writeline [$b constString $s] \
		[Const [string bytelength $s]]
	    return
	}









	# ------------------------------------------------------------------
	#
	# ThunkBuilder:writeint --
	#
	#	Debugging helper that writes an unsigned 32-bit number to
	#	standard out as its own line. The number is written in
................................................................................
	#		This is a Tcl string.
	#
	# Results:
	#	None.

	set f [$m local writeint void<-int noinline]
	params n
	if {[info exists env(TQC_AVOID_MEMORY_IN_DEBUG_PRINT)]} {
	    build {
		set s [$b constString "0123456789ABCDEF"]
		$b condBr [$b eq $n [Const 0]] \
		    $zero $num
	    label zero:
		$b Call writeline [$b getelementptr $s [Const 0]] [Const 1]
		$b br $done
	    label num:
		set nn [$b alloc int]
		$b store $n $nn
		$b br $test
	    label test:
		set n_ [$b load $nn "n"]
		$b condBr [$b eq $n_ [Const 0]] \
		    $done $body
	    label body:
		set nd [$b div $n_ [Const 16]]
		set n0 [$b sub $n_ [$b mult $nd [Const 16]]]
		$b store $nd $nn
		$b Call writeline [$b getelementptr $s $n0] [Const 1]
		$b br $test
	    label done:
		my writeline ""
		$b ret
	    }
	} else {
	    build {
		set str [my Tcl_ObjPrintf [$b constString "0x%X"] $n]
		set chan [my Tcl_GetStdChannel [Const [expr 1<<3]]]
		my Tcl_WriteObj $chan $str
		my Tcl_DecrRefCount $str
		my writeline ""
		$b ret
	    }
	}

	my closure writeint {i {msg ""}} {
	    if {$msg ne ""} {
		$b Call writeline [$b constString $msg] \
		    [Const [string bytelength $msg]]
	    }
	    $b Call writeint $i
	}

	# ------------------------------------------------------------------
	#
	# ThunkBuilder:writeptr --
	#
	#	Debugging helper that writes a pointer to standard out as its
	#	own line. The pointer is written in hexadecimal.
	#
	# Parameters:
	#	i -	The LLVM int32 to write.
	#	msg (optional) -
	#		An optional prefix string to write, useful for
	#		indicating which call site was generating the number.
	#		This is a Tcl string.
	#
	# Results:
	#	None.

	set f [$m local writeptr void<-void* noinline]
	params n
	set intptr_t [Type int[expr {8 * $tcl_platform(pointerSize)}]]
	if {[info exists env(TQC_AVOID_MEMORY_IN_DEBUG_PRINT)]} {
	    build {
		set s [$b constString "0123456789ABCDEF"]
		$b condBr [$b eq $n [$b null void*]] \
		    $zero $num
	    label zero:
		$b Call writeline [$b constString "<NULL>"] [Const 6]
		$b br $done
	    label num:
		set nn [$b alloc $intptr_t]
		$b store [$b cast(ptr2int) $n $intptr_t] $nn
		$b br $test
	    label test:
		set n_ [$b load $nn]
		$b condBr [$b eq $n_ [Const 0 $intptr_t]] \
		    $done $body
	    label body:
		set nd [$b div $n_ [Const 16 $intptr_t]]
		set n0 [$b sub $n_ [$b mult $nd [Const 16 $intptr_t]]]
		$b store $nd $nn
		$b Call writeline [$b getelementptr $s $n0] [Const 1]
		$b br $test
	    label done:
		my writeline ""
		$b ret
	    }
	} else {
	    if {$tcl_platform(pointerSize) == 4} {
		set pat "0x%08X"
	    } else {
		set pat "0x%016lX"
	    }
	    build {
		set n [$b cast(ptr2int) $n $intptr_t]
		set str [my Tcl_ObjPrintf [$b constString $pat] $n]
		set chan [my Tcl_GetStdChannel [Const [expr 1<<3]]]
		my Tcl_WriteObj $chan $str
		my Tcl_DecrRefCount $str
		my writeline ""
		$b ret
	    }
	}

	my closure writeptr {ptr {msg ""}} {
	    if {$msg ne ""} {
		$b Call writeline [$b constString $msg] \
		    [Const [string bytelength $msg]]
	    }
	    $b Call writeptr [$b cast(ptr2ptr) $ptr void*]
	}
    }
 
    method @macros {} {
	upvar 1 size_t size_t

	set inline {}
	if {[info exists ::env(TQC_AVOID_INLINING_MACROS)]} {
	    set inline noinline
	}
	my @macros.Tcl_IncrRefCount $inline
	my @macros.Tcl_DecrRefCount $inline
	my @macros.TclFreeIntRep $inline
	my @macros.TclInvalidateStringRep $inline
	my @macros.TclHashTable
	my @macros.ckalloc $size_t
	my @macros.ckfree
	my @macros.ckrealloc $size_t
	my @macros.obj.constant
	my @macros.jumptable.constant
	my @macros.debugprint

	# ------------------------------------------------------------------
	#
	# ThunkBuilder:stork --
	#
	#	Helper for enforcement of Tcl's 'stork' property of Tcl_Objs,
	#	i.e., that values must always have at least one a string
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/mathlib.tcl.

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
...
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
...
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
...
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
...
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
...
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
....
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
....
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
....
1540
1541
1542
1543
1544
1545
1546

1547
    variable tcl.eq tcl.ne tcl.lt tcl.le tcl.gt tcl.ge
    variable tcl.not tcl.neg tcl_div
    variable tcl.land tcl.land.double tcl.lor tcl.lor.double
    variable tcl.add.numeric tcl.sub.numeric tcl.mult.numeric tcl.div.numeric
    variable tcl.pow.numeric tcl.land.numeric tcl.lor.numeric tcl.not.numeric
    variable tcl.neg.numeric tcl.eq.numeric tcl.ne.numeric tcl.lt.numeric
    variable tcl.le.numeric tcl.gt.numeric tcl.ge.numeric
    variable tcl.checkNumeric tcl.checkDouble tcl.checkInteger
    variable tcl.isNumeric tcl.isDouble tcl.isInteger
    variable tcl.extractNumeric tcl.extractDouble tcl.extractInteger
    variable tcl.stringify.double tcl.stringify.int tcl.stringify.numeric
    variable tcl.cmp.strstr tcl.cmp.strnum

    # Builder:GrowingBinaryFunction --
    #
................................................................................
	label 64bit "op.64bit"
	    set x [my getInt64 $x_struct "x.64"]
	    set y [my getInt64 $y_struct "y.64"]
	    set z [my Call tcl.div.64 $x $y]
	    my ret [my cast(INT?) $z]
	label error:
	    my MathException $ecvar ARITH DIVZERO "divide by zero"
	    my ret [my nothing INT]
	}

	##### Function tcl.div.double #####
	#
	# Type signature: x:DOUBLE * y:DOUBLE * ecvar:int* -> DOUBLE?
	#
	# Quadcode implementation ('div').
................................................................................
	    noalias $ecvar
	    set zero [Const 0.0 DOUBLE]
	    my condBr [my and \
		    [my eq(DOUBLE,DOUBLE) $x $zero] \
		    [my eq(DOUBLE,DOUBLE) $y $zero]] \
		$error $normal
	label normal:
	    my ret [my just [my div $x $y]]
	label error:
	    my MathException $ecvar ARITH DOMAIN \
		"domain error: argument not in valid range"
	    my ret [my nothing DOUBLE]
	}

	##### Function tcl.mod #####
	#
	# Type signature: x:INT * y:INT * ecvar:int* -> INT?
	#
	# Quadcode implementation ('mod').
................................................................................
	label 64bit "op.64bit"
	    set x [my getInt64 $x_struct "x.64"]
	    set y [my getInt64 $y_struct "y.64"]
	    set z [my sub $x [my mult $y [my Call tcl.div.64 $x $y]]]
	    my ret [my cast(INT?) $z]
	label error:
	    my MathException $ecvar ARITH DIVZERO "divide by zero"
	    my ret [my nothing INT]
	}

	##### Function tcl.div.numeric #####
	#
	# Type signature: left:NUMERIC * right:NUMERIC * ecvar:int*
	#			-> NUMERIC?
	#
................................................................................
		$ordinary $failRange
	label check0toNeg "check.zeroToNegative"
	    my condBr [my and \
		    [my eq(DOUBLE,INT) $x [my int 0]] \
		    [my lt(DOUBLE,INT) $y [my int 0]]] \
		$fail0toNeg $ordinary
	label ordinary:
	    my ret [my just [my Call $pow $x $y]]
	label failRange "fail.negativeToFraction"
	    my MathException $ecvar ARITH DOMAIN \
		"domain error: argument not in valid range"
	    my ret [my nothing DOUBLE]
	label fail0toNeg "fail.zeroToNegative"
	    my MathException $ecvar ARITH DOMAIN \
		"exponentiation of zero by negative power"
	    my ret [my nothing DOUBLE]
	}

	##### Function tcl.powi #####
	#
	# Type signature: x:DOUBLE * y:INT * ecvar:int* -> DOUBLE?
	#
	# Part of a quadcode implementation ('expon').
................................................................................
	label checkfalse32:
	    set y [my int.64 $y]
	    my condBr [my expect [my in32range $y] true] $false32 $outofrange
	label false32:
	    set y2 [my cast(int) $y]
	    my br $dopow
	label outofrange "out.of.range"
	    my ret [my just [my Call $pow $x [my castInt2Dbl $y]]]
	label dopow "apply.powi"
	    set y [my phi [list $y1 $y2] [list $real32 $false32]]
	    my ret [my just [my Call $powi $x $y]]
	label fail0toNeg "fail.zeroToNegative"
	    my MathException $ecvar ARITH DOMAIN \
		"exponentiation of zero by negative power"
	    my ret [my nothing DOUBLE]
	}

	##### Function tcl.ipow.bypow2 #####
	#
	# Type signature: x:INT * y:INT -> INT
	#
	# Part of a quadcode implementation ('expon').
................................................................................
	    my br $ok
	label 64 "ipow.64"
	    set r64 [my Call tcl.ipow64 $x $y]
	    my br $ok
	label ok:
	    set sources [list $pow0 $pow1 $32 $64]
	    set result [my phi [list $r0 $x $r32 $r64] $sources "result"]
	    my ret [my just $result]
	label fail0toNeg "fail.zeroToNegative"
	    my MathException $ecvar ARITH DOMAIN \
		"exponentiation of zero by negative power"
	    my ret [my nothing INT]
	}

	##### Function tcl.pow.numeric #####
	#
	# Type signature: x:NUMERIC * y:NUMERIC * ecvar:int* -> NUMERIC?
	#
	# Part of a quadcode implementation ('expon').
................................................................................
	set f [$m local "tcl.extractInteger" INT<-STRING]
	params value
	build {
	    nonnull $value
	    my ret [my packInt64 [my extract [my GetWide $value] 1]]
	}

	##### Function tcl.checkNumeric #####
	#
	# Type signature: value:STRING * msg:STRING * exn:STRING
	#			* ecvar:int* -> bool
	#
	# Try to parse a STRING as a NUMERIC and generate an exception (using
	# the given msg and exn-code) if it is not. Part of the implementation
	# of quadcode "checkArithDomain".

	set f [$m local "tcl.checkNumeric" bool<-STRING,STRING,STRING,int*]
	params value msg exn ecvar
	build {
	    nonnull $value
	    noalias $ecvar
	    my condBr [my extract [my GetDouble $value] 0] $ok $err
	label ok:
	    my condBr [my isDouble $value] $done $intCheck
	label intCheck:
	    my condBr [my isInteger $value] $extractInt $err
	label extractInt:
	    my condBr [my extract [my GetWide $value] 0] $done $err
	label done:
	    my ret [Const 0 bool]
	label err:
	    my initException $exn $msg $ecvar
	    my ret [Const 1 bool]
	}

	##### Function tcl.checkDouble #####
	#
	# Type signature: value:STRING * msg:STRING * exn:STRING
	#			* ecvar:int* -> bool
	#
	# Try to parse a STRING as a DOUBLE and generate an exception (using
	# the given msg and exn-code) if it is not. Part of the implementation
	# of quadcode "checkArithDomain".

	set f [$m local "tcl.checkDouble" bool<-STRING,STRING,STRING,int*]
	params value msg exn ecvar
	build {
	    nonnull $value
	    noalias $ecvar
	    set isDouble [my extract [my GetDouble $value] 0]
	    my condBr $isDouble $done $err
	label err:
	    my initException $exn $msg $ecvar
	    my br $done
	label done:
	    my ret [my not $isDouble]
	}

	##### Function tcl.checkInteger #####
	#
	# Type signature: value:STRING * msg:STRING * exn:STRING
	#			* ecvar:int* -> bool
	#
	# Try to parse a STRING as an INT and generate an exception (using the
	# given msg and exn-code) if it is not. Part of the implementation of
	# quadcode "checkArithDomain".

	set f [$m local "tcl.checkInteger" bool<-STRING,STRING,STRING,int*]
	params value msg exn ecvar
	build {
	    nonnull $value
	    noalias $ecvar
	    set ok [my extract [my GetWide $value] 0]
	    my condBr $ok $done $err
	label err:
	    my initException $exn $msg $ecvar
	    my br $done
	label done:
	    my ret [my not $ok]
	}

	##### Function tcl.cmp.strstr #####
	#
	# Type signature: value1Ptr:STRING * value2Ptr:STRING -> int
	#
	# Returns the relationship between the two string arguments where
	# numeric comparisons are preferred; -1 if 'value1Ptr' precedes in
	# standard ordering, 1 if 'value2Ptr' precedes, and 0 if they are
................................................................................
    export @supportFunctions
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







<







 







|







 







|



|







 







|







 







|



|



|







 







|


|



|







 







|



|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>

25
26
27
28
29
30
31

32
33
34
35
36
37
38
...
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
...
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
...
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
...
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
...
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
....
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
....
1384
1385
1386
1387
1388
1389
1390










































































1391
1392
1393
1394
1395
1396
1397
....
1465
1466
1467
1468
1469
1470
1471
1472
1473
    variable tcl.eq tcl.ne tcl.lt tcl.le tcl.gt tcl.ge
    variable tcl.not tcl.neg tcl_div
    variable tcl.land tcl.land.double tcl.lor tcl.lor.double
    variable tcl.add.numeric tcl.sub.numeric tcl.mult.numeric tcl.div.numeric
    variable tcl.pow.numeric tcl.land.numeric tcl.lor.numeric tcl.not.numeric
    variable tcl.neg.numeric tcl.eq.numeric tcl.ne.numeric tcl.lt.numeric
    variable tcl.le.numeric tcl.gt.numeric tcl.ge.numeric

    variable tcl.isNumeric tcl.isDouble tcl.isInteger
    variable tcl.extractNumeric tcl.extractDouble tcl.extractInteger
    variable tcl.stringify.double tcl.stringify.int tcl.stringify.numeric
    variable tcl.cmp.strstr tcl.cmp.strnum

    # Builder:GrowingBinaryFunction --
    #
................................................................................
	label 64bit "op.64bit"
	    set x [my getInt64 $x_struct "x.64"]
	    set y [my getInt64 $y_struct "y.64"]
	    set z [my Call tcl.div.64 $x $y]
	    my ret [my cast(INT?) $z]
	label error:
	    my MathException $ecvar ARITH DIVZERO "divide by zero"
	    my ret [my fail INT]
	}

	##### Function tcl.div.double #####
	#
	# Type signature: x:DOUBLE * y:DOUBLE * ecvar:int* -> DOUBLE?
	#
	# Quadcode implementation ('div').
................................................................................
	    noalias $ecvar
	    set zero [Const 0.0 DOUBLE]
	    my condBr [my and \
		    [my eq(DOUBLE,DOUBLE) $x $zero] \
		    [my eq(DOUBLE,DOUBLE) $y $zero]] \
		$error $normal
	label normal:
	    my ret [my ok [my div $x $y]]
	label error:
	    my MathException $ecvar ARITH DOMAIN \
		"domain error: argument not in valid range"
	    my ret [my fail DOUBLE]
	}

	##### Function tcl.mod #####
	#
	# Type signature: x:INT * y:INT * ecvar:int* -> INT?
	#
	# Quadcode implementation ('mod').
................................................................................
	label 64bit "op.64bit"
	    set x [my getInt64 $x_struct "x.64"]
	    set y [my getInt64 $y_struct "y.64"]
	    set z [my sub $x [my mult $y [my Call tcl.div.64 $x $y]]]
	    my ret [my cast(INT?) $z]
	label error:
	    my MathException $ecvar ARITH DIVZERO "divide by zero"
	    my ret [my fail INT]
	}

	##### Function tcl.div.numeric #####
	#
	# Type signature: left:NUMERIC * right:NUMERIC * ecvar:int*
	#			-> NUMERIC?
	#
................................................................................
		$ordinary $failRange
	label check0toNeg "check.zeroToNegative"
	    my condBr [my and \
		    [my eq(DOUBLE,INT) $x [my int 0]] \
		    [my lt(DOUBLE,INT) $y [my int 0]]] \
		$fail0toNeg $ordinary
	label ordinary:
	    my ret [my ok [my Call $pow $x $y]]
	label failRange "fail.negativeToFraction"
	    my MathException $ecvar ARITH DOMAIN \
		"domain error: argument not in valid range"
	    my ret [my fail DOUBLE]
	label fail0toNeg "fail.zeroToNegative"
	    my MathException $ecvar ARITH DOMAIN \
		"exponentiation of zero by negative power"
	    my ret [my fail DOUBLE]
	}

	##### Function tcl.powi #####
	#
	# Type signature: x:DOUBLE * y:INT * ecvar:int* -> DOUBLE?
	#
	# Part of a quadcode implementation ('expon').
................................................................................
	label checkfalse32:
	    set y [my int.64 $y]
	    my condBr [my expect [my in32range $y] true] $false32 $outofrange
	label false32:
	    set y2 [my cast(int) $y]
	    my br $dopow
	label outofrange "out.of.range"
	    my ret [my ok [my Call $pow $x [my castInt2Dbl $y]]]
	label dopow "apply.powi"
	    set y [my phi [list $y1 $y2] [list $real32 $false32]]
	    my ret [my ok [my Call $powi $x $y]]
	label fail0toNeg "fail.zeroToNegative"
	    my MathException $ecvar ARITH DOMAIN \
		"exponentiation of zero by negative power"
	    my ret [my fail DOUBLE]
	}

	##### Function tcl.ipow.bypow2 #####
	#
	# Type signature: x:INT * y:INT -> INT
	#
	# Part of a quadcode implementation ('expon').
................................................................................
	    my br $ok
	label 64 "ipow.64"
	    set r64 [my Call tcl.ipow64 $x $y]
	    my br $ok
	label ok:
	    set sources [list $pow0 $pow1 $32 $64]
	    set result [my phi [list $r0 $x $r32 $r64] $sources "result"]
	    my ret [my ok $result]
	label fail0toNeg "fail.zeroToNegative"
	    my MathException $ecvar ARITH DOMAIN \
		"exponentiation of zero by negative power"
	    my ret [my fail INT]
	}

	##### Function tcl.pow.numeric #####
	#
	# Type signature: x:NUMERIC * y:NUMERIC * ecvar:int* -> NUMERIC?
	#
	# Part of a quadcode implementation ('expon').
................................................................................
	set f [$m local "tcl.extractInteger" INT<-STRING]
	params value
	build {
	    nonnull $value
	    my ret [my packInt64 [my extract [my GetWide $value] 1]]
	}











































































	##### Function tcl.cmp.strstr #####
	#
	# Type signature: value1Ptr:STRING * value2Ptr:STRING -> int
	#
	# Returns the relationship between the two string arguments where
	# numeric comparisons are preferred; -1 if 'value1Ptr' precedes in
	# standard ordering, 1 if 'value2Ptr' precedes, and 0 if they are
................................................................................
    export @supportFunctions
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/stdlib.tcl.

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
...
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
...
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
...
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
...
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
...
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
....
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
....
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
....
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
....
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
....
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
....
1692
1693
1694
1695
1696
1697
1698



1699
























1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
....
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
....
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
....
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
....
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
....
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
....
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
....
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
....
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
....
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
....
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
....
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
....
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
....
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
....
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
....
2529
2530
2531
2532
2533
2534
2535
















2536
2537
2538
2539
2540
2541
2542
....
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
....
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
....
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697



























2698



2699
2700
2701
2702
2703
2704
2705
....
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
....
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
....
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
....
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810























2811
2812
2813
2814
2815
2816
2817
....
2821
2822
2823
2824
2825
2826
2827


















2828
2829
2830
2831
2832
2833
2834
....
2847
2848
2849
2850
2851
2852
2853
2854


2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
....
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
....
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
....
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
....
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
....
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373

3374
3375
3376
3377
3378
3379
3380
....
3382
3383
3384
3385
3386
3387
3388


































3389
3390
3391
3392
3393
3394
3395
....
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
....
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
....
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
....
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
....
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
....
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662















































































































































3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687

3688
3689
3690
3691
3692


3693

































































































3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
....
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748


3749







































































3750
3751
3752
3753
3754
3755
3756
3757
3758

3759
#	added onto the Builder class, so that it can issue them by just
#	generating a call to the implementation function. This allows us to
#	inject extra basic blocks without disturbing the analysis from the
#	reasoning engine.
#
#	See build.tcl for where these functions are called from.
#
# Copyright (c) 2015-2016 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
oo::define Builder {
    # Variables holding implementations of Tcl's string operators
    variable tcl.stringify.double tcl.stringify.int tcl.stringify.numeric
    variable tcl.addReference tcl.dropReference
    variable tcl.addMaybeReference tcl.dropMaybeReference




    variable tcl.unshare tcl.unshare.copy
    variable tcl.strlen tcl.append.string tcl.streq tcl.strcmp tcl.strmatch
    variable tcl.stridx tcl.stridx.idx
    variable tcl.strrange tcl.strrange.idx tcl.strreplace tcl.strreplace.idx
    variable tcl.strfind.fwd tcl.strfind.rev
    variable tcl.strmap tcl.strtrim tcl.strcase tcl.strclass
    variable tcl.regexp tcl.concatenate tcl.booleanTest tcl.not.string


    # Variables holding implementations of Tcl's list operators
    variable tcl.list.create tcl.list.length tcl.list.append tcl.list.concat
    variable tcl.list.foreach.getStep tcl.list.foreach.mayStep
    variable tcl.list.foreach.nextStep tcl.list.foreach.start tcl.list.unshare
    variable tcl.list.range tcl.list.range1 tcl.list.in
    variable tcl.list.index tcl.list.index1 tcl.list.indexList
    variable tcl.list.set tcl.list.set1 tcl.list.setList

    # Variables holding implementations of Tcl's dict operators
    variable tcl.dict.get1 tcl.dict.get tcl.dict.set1 tcl.dict.set
    variable tcl.dict.exists1 tcl.dict.exists tcl.dict.unset1 tcl.dict.unset
    variable tcl.dict.iterStart tcl.dict.iterNext tcl.dict.iterDone
    variable tcl.dict.iterKey tcl.dict.iterValue tcl.dict.addIterReference

    variable tcl.dict.dropIterReference tcl.dict.dropIterFailReference
    variable tcl.dict.append tcl.dict.lappend tcl.dict.incr tcl.dict.size

    variable tcl.maptoint

    # Variables holding implementations of Tcl's exception-handling machinery
    variable tcl.getresult tcl.getreturnopts tcl.initExceptionOptions
    variable tcl.initExceptionSimple tcl.processReturn
    variable tcl.existsOrError tcl.invoke.command


    # Helper functions
    variable tcl.impl.trimleft tcl.impl.trimright
    variable tcl.impl.getIndex tcl.impl.listDupe

    # Reference to the module object
    variable m
 
    # Builder:ReferenceFunctions --
    #
................................................................................
	params value:objPtr
	build {
	    nonnull $value
	    $api Tcl_DecrRefCount $value
	    my ret
	}

	##### tcl.addMaybeReference #####
	#
	# Type signature: objPtr:Tcl_Obj*? -> void






































	#
	# Increment the reference count of a Tcl_Obj reference if the
	# object is supplied

	set f [$m local "tcl.addMaybeReference" void<-Tcl_Obj*?]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $incr
	label incr "action.required"
	    set value [my unmaybe $value "objPtr"]
	    $api Tcl_IncrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropMaybeReference #####
	#
	# Type signature: objPtr:Tcl_Obj*? -> void
	#
	# Decrement the reference count of a Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropMaybeReference" void<-Tcl_Obj*?]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $decr
	label decr "action.required"
	    set value [my unmaybe $value "objPtr"]
	    $api Tcl_DecrRefCount $value
	    my ret











































































	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.unshare #####
	#
	# Type signature: objPtr:Tcl_Obj* -> Tcl_Obj*
................................................................................
	##### Closure Build:printref #####
	#
	# Type signature: val:STRING -> void
	#
	# Print a description of the given Tcl_Obj reference. Used for
	# debugging reference counts.







































































	my closure printref {val {prefix ""}} {
	    if {![info exists ::env(PRINT_REFERENCE_MANAGEMENT)]} {
		return
	    }
	    if {[TypeOf $val] ne [Type STRING]} {



		if {[TypeOf $val] ne [Type STRING?]} {
		    return








		}
		set val [my unmaybe $val]
	    }






	    if {$prefix ne ""} {
		$api printf [my constString "%s"] [my constString $prefix]


	    }
	    variable prcount
	    set pr [incr prcount]
	    set name [format %.30s... [PrintValueToString $val]]
	    set rc [my refCount $val]
	    $api printf [my constString "%d:%p(%.30s) => %d\n"] \
		[Const $pr] $val [$api Tcl_GetString $val] $rc
	    $api fflush [$api stdout]

	    return
	}

	##### Closure Build:memcpy #####
	#
	# Type signature: target:?* * source:?* * length:int32 -> void
	#
	# Copy memory of size 'length' from 'source' to 'target'.

	my closure memcpy {target source length} {

	    set memcpy [$m intrinsic memcpy \
		    [TypeOf $target] [TypeOf $source] $size_t]





	    my Call $memcpy $target $source $length \
		    [Const 0] [Const false bool]
	    return
	}
























	##### Closure Build:memcmp #####
	#
	# Type signature: a:?* * b:?* * length:int32 -> int
	#
	# Compare memory of size 'length' between 'a' and 'b'.

	set memcmp [$m function.extern memcmp \
		[Type func{int<-void*,void*,$size_t}] readonly]
	my closure memcmp {bytes1 bytes2 length {name "cmp"}} {
	    my call $memcmp [list \

		    [my cast(ptr) $bytes1 void] \


		    [my cast(ptr) $bytes2 void] \




		    $length] $name
	}

	my StringInspectionFunctions $api
	my StringWritingFunctions $api


	my StringComparisonFunctions $api

	return
    }
 
    # Builder:StringInspectionFunctions --
    #
................................................................................
	    my ret $res
	}
	unset -nocomplain valueObj

	##### Function tcl.impl.getWide #####
	##### MAPPED CALL TO METHOD: Build:GetWide #####
	#
	# Type signature: valueObj:STRING -> int * int64
	#
	# Gets an int64 from a Tcl string. Wrapper around Tcl API to ensure
	# that scope lifetime gets better understood.

	set f [$m local "tcl.impl.getWide" struct{int1,int64}<-STRING]
	my closure GetWide {valueObj} {
	    my call ${tcl.impl.getWide} [list $valueObj] "result"
	}
	params valueObj
	build {
	    nonnull $valueObj
	    set intVar [my alloc int64 "intPtr"]
	    set code [$api Tcl_GetWideIntFromObj {} $valueObj $intVar]
	    set res [my undef struct{int1,int64}]
	    set res [my insert $res [my eq $code [Const 0]] 0]
	    set res [my insert $res [my load $intVar "int"] 1 "result"]
	    my ret $res
	}
	unset -nocomplain valueObj

	##### Function tcl.impl.getString #####
................................................................................
	label fail:
	    my ret [Const false bool]
	}

	##### Function tcl.impl.getIndex #####
	##### Closure Build:GetIndex #####
	#
	# Type signature: interp:Tcl_Interp* * objPtr:Tcl_Obj* * end:int
	#			-> int1 * int
	#
	# Converts an index string into an offset into something (i.e., a
	# string or list). Returns a tuple of whether the conversion succeeded
	# (a boolean) and the index.

	set f [$m local "tcl.impl.getIndex" struct{bool,int}<-Tcl_Interp*,Tcl_Obj*,int readonly]

	unset -nocomplain objPtr end
	my closure GetIndex {interp objPtr end {indexVar dummy}} {
	    upvar 1 $indexVar index
	    if {$interp eq ""} {
		set interp [my null Tcl_Interp*]
	    }
	    set res [my Call tcl.impl.getIndex $interp $objPtr $end]
	    set index [my extract $res 1 "getIndex.index"]
	    return [my extract $res 0 "getIndex.result"]
	}
	params interp objPtr end
	build {
................................................................................
    # that this is necessarily so.
    method StringWritingFunctions {api} {
	upvar 1 sizeof sizeof 0 0 1 1 -1 -1

	##### Function tcl.setFromAny #####
	##### Closure Build:setFromAny #####
	#
	# Type signature: typePtr:Tcl_ObjType* * interp:Tcl_Interp*
	#			* objPtr:STRING -> int
	#
	# Call the given type's setFromAnyProc on the given object.

	set f [$m local "tcl.setFromAny" int<-Tcl_ObjType*,Tcl_Interp*,STRING]
	params typePtr interp objPtr
	build {
	    noalias $typePtr $interp $objPtr
	    nonnull $typePtr $objPtr
	    set func [my dereference $typePtr 0 Tcl_ObjType.setFromAnyProc]
	    set func [my cast(ptr) $func func{int<-Tcl_Interp*,Tcl_Obj*} "setFromAny"]
	    set code [my Call $func $interp $objPtr]
	    SetValueName $code "code"
	    AddCallAttribute $code 1 nocapture
	    AddCallAttribute $code 2 nocapture
	    my ret $code
	}
	my closure setFromAny {TYPE INTERP VALUE {name "code"}} {
................................................................................
	    set unicodeResult [$api Tcl_NewStringObj $buf $len]
	    my br $done
	label done:
	    set result [my phi \
		    [list $emptyResult $byteResult $asciiResult $unicodeResult] \
		    [list $empty $baIdx $byteIndex $strIdx] "result"]
	    my addReference(STRING) $result
	    my ret [my just $result]
	label failed:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.strrange #####
	#
	# Type signature: objPtr:STRING * fromInt:INT * toInt:INT -> STRING
	#
	# Quadcode implementation ('strrange')
................................................................................
	label realSubstring:
	    set value2 [$api Tcl_GetRange $str $from $to]
	    my br $finish
	label finish:
	    set result [my phi [list $value1 $value2] \
		    [list $empty $realSubstring] "result"]
	    my addReference(STRING) $result
	    my ret [my just $result]
	label failed:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.strreplace #####
	#
	# Type signature: objPtr:STRING * fromInt:INT * toInt:INT
	#			* substringPtr:STRING -> STRING
	#
................................................................................
	label getTo:
	    my condBr [my GetIndex $interp $toIdx $end to] \
		$rangeCheck $failed
	label rangeCheck:
	    set from [my packInt32 $from]
	    set to [my packInt32 $to]
	    set replaced [my Call tcl.strreplace $str $from $to $substr]
	    my ret [my just $replaced]
	label failed:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.strmap #####
	#
	# Type signature: sourceObj:STRING * targetObj:STIRNG *
	#			stringObj:STRING -> STRING
	#
................................................................................
	label releaseIntRep "release.internal.representation"
	    $api TclFreeIntRep $string
	    my br $done
	label done:
	    my addReference(STRING) $string
	    my ret $string
	}



























































	##### Function tcl.impl.listDupe #####
	##### Closure Build:ListDupe #####
	#
	# Type signature: interp:Tcl_Interp* * obj:STRING -> STRING
	#
	# Replacement for non-exposed TclListObjCopy().

	set f [$m local "tcl.impl.listDupe" STRING<-Tcl_Interp*,STRING]
	unset -nocomplain interp objPtr name
	my closure ListDupe {interp objPtr {name ""}} {
	    if {$interp eq ""} {
		set interp [my null Tcl_Interp*]
	    }
	    my call ${tcl.impl.listDupe} [list $interp $objPtr] $name
	}
	params interp obj
	build {
	    noalias $interp $obj
	    nonnull $obj
................................................................................
		$forceType $ok
	label forceType:
	    my condBr [my eq [my setFromAny $listType $interp $obj] $0] \
		$ok $fail
	label ok:
	    set new [$api Tcl_NewObj]
	    $api TclInvalidateStringRep $new
	    set func [my cast(ptr) \
		    [my dereference $listType 0 Tcl_ObjType.dupIntRepProc]\
		    func{void<-Tcl_Obj*,Tcl_Obj*} "dupIntRep"]
	    set call [my Call $func $obj $new]
	    AddCallAttribute $call 1 nocapture
	    AddCallAttribute $call 2 nocapture
	    my ret $new
	label fail:
	    my ret [my null STRING]
	}
................................................................................
	    noalias $list $ecvar
	    nonnull $list $ecvar
	    set interp [$api tclInterp]
	    set var [my alloc int "length"]
	    set code [$api Tcl_ListObjLength $interp $list $var]
	    my condBr [my eq $code $0] $ok $fail
	label ok:



	    my ret [my cast(INT?) [my load $var]]
























	label fail:
	    my store $1 $ecvar
	    my ret [my nothing INT]
	}

	##### Function tcl.list.append #####
	#
	# Type signature: list:STRING * value:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listAppend')
................................................................................
	    $api TclInvalidateStringRep $list
	    my addReference(STRING) $list
	    my condBr [my shared $value] $exit $extraRef
	label extraRef "add.extra.reference.to.value"
	    my addReference(STRING) $value
	    my br $exit
	label exit:
	    my ret [my just $list]
	label error:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.concat #####
	#
	# Type signature: list:STRING * value:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listConcat')
................................................................................
	    my br $concat
	label concat:
	    set working [my phi [list $list $copy] [list $checkDupe $dupe] "list"]
	    set objc [my load $objc "objc"]
	    set objv [my load $objv "objv"]
	    $api Tcl_ListObjReplace {} $working $len $0 $objc $objv
	    my addReference(STRING) $working
	    my ret [my just $working]
	label error:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.index #####
	#
	# Type signature: list:STRING * idxc:int * idxv:STRING* * ecvar:int*
	#			-> STRING?
	#
................................................................................
	    my condBr [my lt $i $idxc] $loopIndexValidityCheck $loopEmpty
	label loopEmpty:
	    my store [set list [$api Tcl_NewObj]] $listPtr
	    my addReference(STRING) $list
	    my br $loopNext
	label loopIndexValidityCheck:
	    my condBr [my GetIndex $interp \
		    [my load [my getelementptr $idxv [list $i]]] [Const -1]] \
		$loopIndexOutOfRange $loopIndexBad
	label loopIndexBad:
	    my dropReference $sublistCopy
	    my br $error
	label loopNext:
	    my dropReference $sublistCopy
	    my store [my add [my load $iPtr "i"] $1] $iPtr
	    my br $loopTest
	label done:
	    set list [my load $listPtr "list"]
	    my ret [my just $list]
	label error:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.index1 #####
	#
	# Type signature: list:STRING * index:INT * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listIndex')
................................................................................
	label ok:
	    my condBr [my and [my ge $idx $0] [my lt $idx [my load $objc]]] \
		$realIndex $outOfBounds
	label realIndex "real.index"
	    set objv [my load $objv "objv"]
	    set obj [my load [my getelementptr $objv [list $idx]] "objPtr"]
	    my addReference(STRING) $obj
	    my ret [my just $obj]
	label outOfBounds "out.of.bounds"
	    set obj [$api Tcl_NewObj]
	    my addReference(STRING) $obj
	    my ret [my just $obj]
	label fail:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.indexList #####
	#
	# Type signature: list:STRING * index:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listIndex')
................................................................................
	    set objc [my alloc int "objc"]
	    set objv [my alloc STRING* "objv"]
	    set code [$api Tcl_ListObjGetElements $interp $list $objc $objv]
	    my condBr [my eq $code $0] $checkType $notList
	label notList:
	    # We're not a list and we know it right now
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	label checkType:
	    my condBr [my neq [my dereference $index 0 Tcl_Obj.typePtr] \
			[$api tclListType]] \
		$checkIndex $slowPath
	label checkIndex:
	    set len [my load $objc]
	    my condBr [my GetIndex {} $index $len idx] \
................................................................................
	label immediateIndex:
	    my condBr [my and [my ge $idx $0] [my lt $idx $len]] \
		$realIndex $outOfBounds
	label realIndex "real.index"
	    set objv [my load $objv "objv"]
	    set obj [my load [my getelementptr $objv [list $idx]] "objPtr"]
	    my addReference(STRING) $obj
	    my ret [my just $obj]
	label outOfBounds "out.of.bounds"
	    set obj [$api Tcl_NewObj]
	    my addReference(STRING) $obj
	    my ret [my just $obj]
	label slowPath:
	    set dupe [my ListDupe $interp $index "copy"]
	    my condBr [my nonnull $dupe] $okIndex $notList
	label okIndex:
	    set listRep [my load [my cast(ptr) \
		    [my gep $dupe 0 Tcl_Obj.internalRep 0] \
		    TclList*] "listRep"]
................................................................................
		$sublistInplaceFree $sublistInplaceDone
	label sublistInplaceFree "sublist.inPlace.loop.body"
	    ReplaceAllUsesWith $loopIndex [my add $index $1 "index"]
	    set obj [my load [my getelementptr $objv [list $index]] "objPtr"]
	    my dropReference $obj
	    my br $sublistInplaceFreeTest
	label sublistInplaceDone "sublist.inPlace.done"
	    my store $onePast [my gep $listPtr 0 TclList.elemCount]
	    my store $1 [my gep $listPtr 0 TclList.canonicalFlag]
	    $api TclInvalidateStringRep $list
	    my br $ok
	label sublistNew "sublist.new"
	    set r1 [$api Tcl_NewListObj [my add [my sub $to $from] $1] \
		    [my getelementptr $objv [list $from]]]
	    my br $ok
	label empty:
	    set r2 [$api Tcl_NewObj]
	    my br $ok
	label ok:
	    set sources [list $sublistInplaceDone $sublistNew $empty]
	    set result [my phi [list $list $r1 $r2] $sources "result"]
	    my addReference(STRING) $result
	    my ret [my just $result]
	label error:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.range1 #####
	#
	# Type signature: list:STRING * from:INT * to:INT -> STRING?
	#
	# Core of quadcode implementation ('listRangeImm')
................................................................................
		$sublistInplaceFree $sublistInplaceDone
	label sublistInplaceFree "sublist.inPlace.free"
	    ReplaceAllUsesWith $loopIndex [my add $index $1 "index"]
	    set obj [my load [my getelementptr $objv [list $index]] "objPtr"]
	    my dropReference $obj
	    my br $sublistInplaceFreeTest
	label sublistInplaceDone "sublist.inPlace.done"
	    my store $onePast [my gep $listPtr 0 TclList.elemCount]
	    my store $1 [my gep $listPtr 0 TclList.canonicalFlag]
	    $api TclInvalidateStringRep $list
	    my br $ok
	label sublistNew "sublist.new"
	    set r1 [$api Tcl_NewListObj [my add [my sub $to $from] $1] \
		    [my getelementptr $objv [list $from]]]
	    my br $ok
	label empty:
	    set r2 [$api Tcl_NewObj]
	    my br $ok
	label ok:
	    set sources [list $sublistInplaceDone $sublistNew $empty]
	    set result [my phi [list $list $r1 $r2] $sources "result"]
	    my addReference(STRING) $result
	    my ret [my just $result]
	label error:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.set #####
	#
	# Type signature: list:STRING * idxc:int * idxv:STRING* * elem:STRING
	#			* ecvar:int* -> STRING?
	#
................................................................................
	build {
	    noalias $idxv $ecvar
	    nonnull $list $idxv $elem $ecvar
	    set interp [$api tclInterp]
	    my condBr [my eq $idxc $0] $doNothing $sharedCheck
	label doNothing:
	    my addReference(STRING) $list
	    my ret [my just $list]
	label sharedCheck:
	    my condBr [my shared $list] $duplicate $prepareToLoop
	label duplicate:
	    set dupe [$api Tcl_DuplicateObj $list]
	    my br $prepareToLoop
	label prepareToLoop:
	    set sources [list $sharedCheck $duplicate]
................................................................................
	    my condBr [my neq $retValue $list] \
		$loopFailDropOverall $loopFailExit
	label loopFailDropOverall:
	    my dropReference $retValue
	    my br $loopFailExit
	label loopFailExit:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	label loopEnd:
	    set sublist [my load $subList]
	    set obj [my load $chain]
	    my condBr [my nonnull $obj] $loopEndDrop $terminalSet
	label loopEndDrop:
	    set ptr2 \
		[my cast(ptr) [my gep $obj 0 Tcl_Obj.internalRep 1] STRING]
................................................................................
	    $api TclInvalidateStringRep $sublist
	    my addReference(STRING) $retValue
	    my condBr [my shared $elem] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $elem
	    my br $exit2
	label exit2 "exit"
	    my ret [my just $retValue]
	}

	##### Function tcl.list.set1 #####
	#
	# Type signature: list:STRING * index:INT * elem:STRING * ecvar:int*
	#			-> STRING?
	#
................................................................................
	    $api TclInvalidateStringRep $list
	    my addReference(STRING) $list
	    my condBr [my shared $elem] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $elem
	    my br $exit2
	label exit2 "exit"
	    my ret [my just $list]
	label outRange "failure.outOfRange"
	    $api Tcl_SetObjResult $interp \
		[$api obj.constant "list index out of range"]
	    $api Tcl_SetObjErrorCode $interp \
		[$api obj.constant {TCL OPERATION LSET BADINDEX}]
	    my br $out
	label out "failure.exit"
	    my Call obj.cleanup $duped
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.list.setList #####
	#
	# Type signature: list:STRING * idxArg:STRING * elem:STRING
	#			* ecvar:int* -> STRING?
	#
................................................................................
	    my condBr [my eq [my memcmp $bytes1 $bytes2 $len1] $0] \
		$done $loopNext
	label loopNext:
	    ReplaceAllUsesWith $iLoop [set i [my add $i $1 "i"]]
	    my condBr [my lt $i $objc] $loop $done
	label fail:
	    my store $1 $ecVar
	    my ret [my nothing ZEROONE]
	label done:
	    set flag [my phi [list [Const false bool] [Const false bool] [Const true bool]] \
		    [list $realCheck $loopNext $loopCompare] "flag"]
	    my ret [my just $flag]
	}

	##### Function tcl.list.unshare #####
	#
	# Type signature: list:STRING -> STRING
	#
	# Core of quadcode implementation ('unshareList')
................................................................................
	    ReplaceAllUsesWith $maxLoop [my max $iterTmp $max "max"]
	    ReplaceAllUsesWith $iLoop [my add $i $1 "i"]
	    my br $loopStart
	label ok:
	    set pair [my undef FOREACH]
	    set pair [my insert $pair $0 FOREACH.val]
	    set pair [my insert $pair $max FOREACH.max]
	    my ret [my just $pair]
	label fail:
	    my store $1 $ecVar
	    my ret [my nothing FOREACH]
	}

	##### Function tcl.list.foreach.getStep #####
	#
	# Type signature: pair:FOREACH -> INT
	#
	# Core of quadcode implementation ('foreachIter')
................................................................................

	set f [$m local "tcl.list.foreach.nextStep" FOREACH<-FOREACH readnone]
	params pair
	build {
	    set val [my extract $pair FOREACH.val]
	    my ret [my insert $pair [my add $val $1] FOREACH.val]
	}

















	##### Function tcl.dict.exists1 #####
	#
	# Type signature: dict:STRING * key:STRING -> ZEROONE
	#
	# Tests if a key is in a dictionary.

................................................................................
	    noalias $ecvar
	    nonnull $dict $ecvar
	    set interp [$api tclInterp]
	    set size [my alloc int "size"]
	    set code [$api Tcl_DictObjSize $interp $dict $size]
	    my condBr [my eq $code $0] $ok $fail
	label ok:
	    my ret [my cast(INT?) [my load $size]]
	label fail:
	    my store $1 $ecvar
	    my ret [my nothing INT]
	}

	##### Function tcl.dict.get1 #####
	#
	# Type signature: dict:STRING * key:STRING * ecvar:int32* -> STRING?
	#
	# Gets a value by key from a dictionary.  Can fail if the "dict" is
................................................................................
	    set result [$api Tcl_DictObjGet $interp $dict $key $resvar]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    set value [my load $resvar "value"]
	    my condBr [my nonnull $value] $return $fail
	label return:
	    my addReference(STRING) $value
	    my ret [my just $value]
	label fail:
	    set keyval [$api Tcl_GetString $key]
	    $api Tcl_SetObjResult $interp \
		[$api Tcl_ObjPrintf [my constString \
			"key \"%s\" not known in dictionary"] \
		    $keyval]
	    $api Tcl_SetErrorCode $interp \
		[my constString TCL] [my constString LOOKUP] \
		[my constString DICT] $keyval [my null char*]
	    my br $notOK
	label notOK:
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.dict.get #####
	#
	# Type signature: dict:STRING * pathlen:int * pathobjs:STRING*
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    my condBr [my eq $result $0] $OK $fail
	label OK:
	    set value [my load $resvar "value"]
	    my condBr [my nonnull $value] $return $fail
	label return:
	    set value [my phi [list $dict $value] [list $verify $OK] "value"]
	    my addReference(STRING) $value
	    my ret [my just $value]
	label fail:
	    set keyval [$api Tcl_GetString $key]
	    $api Tcl_SetObjResult $interp \
		[$api Tcl_ObjPrintf [my constString \
			"key \"%s\" not known in dictionary"] \
		    $keyval]
	    $api Tcl_SetErrorCode $interp \
		[my constString TCL] [my constString LOOKUP] \
		[my constString DICT] $keyval [my null char*]
	    my br $notOK
	label notOK:
	    my store $1 $ecvar



























	    my ret [my nothing STRING]



	}

	##### Function tcl.dict.set1 #####
	#
	# Type signature: dict:STRING * key:STRING * value:STRING
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	label OK:
	    my addReference(STRING) $dict
	    my condBr [my shared $value] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $value
	    my br $exit2
	label exit2 "exit"
	    my ret [my just $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.dict.set #####
	#
	# Type signature: dict:STRING * pathlen:int * pathobjs:STRING*
	#			* value:STRING * ecvar:int32* -> STRING?
	#
................................................................................
	label OK:
	    my addReference(STRING) $dict
	    my condBr [my shared $value] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $value
	    my br $exit2
	label exit2 "exit"
	    my ret [my just $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.dict.unset1 #####
	#
	# Type signature: dict:STRING * key:STRING * ecvar:int32* -> STRING?
	#
	# Removes a key from a dictionary.  Can fail if the "dict" is not a
................................................................................
	    nonnull $dict $key $ecvar
	    set interp [$api tclInterp]
	    set dd [my Dedup dict]
	    set result [$api Tcl_DictObjRemove $interp $dict $key]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    my addReference(STRING) $dict
	    my ret [my just $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.dict.unset #####
	#
	# Type signature: dict:STRING * pathlen:int * pathobjs:STRING*
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    noalias $dict $pathobjs $ecvar
	    nonnull $dict $pathobjs $ecvar
	    set interp [$api tclInterp]
	    set dd [my Dedup dict]
	    set result [$api Tcl_DictObjRemoveKeyList $interp $dict $pathlen $pathobjs]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    my ret [my just $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]























	}

	##### Function tcl.dict.addIterReference #####
	#
	# Type signature: iter:DICTITER -> void
	#
	# Increments the reference count inside a dictionary iteration state.
................................................................................
	build {
	    nonnull $iter
	    set ref [my gep $iter 0 DICTFOR.ref]
	    set rc [my load $ref]
	    my store [my add $rc $1] $ref
	    my ret
	}



















	##### Function tcl.dict.iterStart #####
	#
	# Type signature: dict:STRING * ecvar:int* -> DICTITER?
	#
	# Starts iterating over a dictionary. The current state of the
	# iteration (assuming we don't get an error) is stored inside the
................................................................................
	    SetValueName $value "valuePtr"
	    set done [my alloc int "done"]
	    set search [my gep $iter 0 DICTFOR.search]
	    set code [$api Tcl_DictObjFirst $interp $dict \
			$search $key $value $done]
	    my condBr [my eq $code $0] $ok $failed
	label ok:
	    my store $dict [my gep $iter 0 DICTFOR.dict]


	    my addReference(STRING) $dict
	    my store $0 [my gep $iter 0 DICTFOR.ref]
	    my store [my neq [my load $done] $0] [my gep $iter 0 DICTFOR.done]
	    my Call tcl.dict.addIterReference $iter
	    my ret [my just $iter]
	label failed:
	    $api ckfree $iter
	    my store $1 $ecvar
	    my ret [my nothing DICTITER]
	}

	##### Function tcl.dict.iterNext #####
	#
	# Type signature: iter:DICTITER -> DICTITER
	#
	# Continues iterating over a dictionary. The current state of the
................................................................................
	    set key [my gep $iter 0 DICTFOR.key]
	    SetValueName $key "keyPtr"
	    set value [my gep $iter 0 DICTFOR.value]
	    SetValueName $value "valuePtr"
	    set done [my alloc int "done"]
	    set search [my gep $iter 0 DICTFOR.search]
	    $api Tcl_DictObjNext $search $key $value $done
	    my store [my neq [my load $done] $0] [my gep $iter 0 DICTFOR.done]
	    my br $finished
	label finished:
	    my Call tcl.dict.addIterReference $iter
	    my ret $iter
	}

	##### Function tcl.dict.dropIterReference #####
................................................................................
	    set dictVal2 [$api Tcl_DuplicateObj $dictVal]
	    $api Tcl_AppendObjToObj $dictVal2 $value
	    set c [$api Tcl_DictObjPut {} $dict $key $dictVal2]
	    AddCallAttribute $c 3 nocapture
	    my br $done
	label done:
	    my addReference(STRING) $dict
	    my ret [my just $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.dict.incr #####
	#
	# Type signature: dict:STRING * key:STRING * value:INT
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    my br $done
	label done:
	    set resultValue [my phi [list $strVal $addVal] \
		    [list $set $doAdd] "value"]
	    # No failure mode at this point: we know we've got a dictionary.
	    set c [$api Tcl_DictObjPut {} $dict $key $resultValue]
	    my addReference(STRING) $dict
	    my ret [my just $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.dict.lappend #####
	#
	# Type signature: dict:STRING * key:STRING * value:STRING
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    my condBr [my eq $result $0] $dupeUpdateOK $dupeNotOK
	label dupeUpdateOK:
	    set c [$api Tcl_DictObjPut {} $dict $key $dictVal]
	    AddCallAttribute $c 3 nocapture
	    my br $done
	label done:
	    my addReference(STRING) $dict
	    my ret [my just $dict]
	label dupeNotOK:
	    my dropReference $dictVal
	    my br $notOK
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.maptoint #####
	#
	# Type signature: value:STRING * mapping:STRING * notThere:int -> INT
	#
	# Quadcode implementation ('maptoint')
	#
	# Returns the INT looked up in 'mapping' that corresponds to 'value'.
	# If the value is absent, returns the 'notThere' value.

	set f [$m local "tcl.maptoint" INT<-STRING,Tcl_HashTable*,int]
	params value mapping notThere
	build {
	    nonnull $value $mapping
	    set offset [$api TclFindHashEntry $mapping $value]
	    SetValueName $offset "offsetPtr"
	    my condBr [my nonnull $offset] $present $absent
	label present:
	    set offset [$api Tcl_GetHashValue $offset int]
	    SetValueName $offset "offset"
	    my ret [my packInt32 $offset]
	label absent:
	    my ret [my packInt32 $notThere]
	}

	##### Function tcl.concatenate #####
	#
	# Type signature: len:int * ary:STRING* -> STRING
	#
	# Quadcode implementation ('concat')
	#
	# Returns the application of Tcl_ConcatObj() to the given values, so
	# much so that it is just a very thin wrapper around that function.

	set f [$m local "tcl.concatenate" STRING<-int,STRING*]
	params len ary
	build {
	    nonnull $ary
	    set result [$api Tcl_ConcatObj $len $ary]
	    my addReference(STRING) $result
	    my ret $result
	}
    }
 
    # Builder:StringComparisonFunctions --
    #
    #	Generate the functions that implement the string comparators. Only
    #	called from StringFunctions method.
................................................................................
		    [my getInt32 $flags]]
	    my condBr [my nonnull $RE] $exec $err
	label exec "re.exec"
	    set match [$api Tcl_RegExpExecObj $interp $RE $stringObj $0 $0 $0]
	    my condBr [my ge $match $0] $done $err
	label done "re.done"
	    my store $0 $errVar
	    my ret [my just [my gt $match $0]]
	label err "re.error"
	    my store $1 $errVar
	    my ret [my nothing ZEROONE]
	}

    }
 
    # Builder:@apiFunctions --
    #
    #	Generate the quadcode operator implementations that require access to
    #	the Tcl API to work.
    #
................................................................................
    #	api -	The handle of the Tcl API object (currently an instance of the
    #		Thunk class).
    #
    # Results:
    #	None.

    method @apiFunctions {module api} {


































	my StringifyFunctions $api
	my ReferenceFunctions $api
	my StringFunctions $api

	# Builder:MathException --
	#
	#	Generate one of the standard math exceptions that are produced
................................................................................

	set f [$module local "tcl.initExceptionSimple" void<-STRING,STRING]
	params message errorcode
	build {
	    nonnull $message $errorcode
	    set interp [$api tclInterp]
	    $api Tcl_SetObjResult $interp $message
	    set field [my gep $interp 0 Tcl_Interp.returnOpts]
	    set ro [my load $field]
	    set newOpts [$api Tcl_NewObj]
	    set key [$api obj.constant "-errorcode"]
	    $api Tcl_DictObjPut {} $newOpts $key $errorcode
	    my store $newOpts $field
	    my addReference(STRING) $newOpts
	    my condBr [my nonnull $ro] $dropold $testForError
	label dropold "swap.dropOld"
	    my dropReference $ro
	    my br $testForError
	label testForError "test.for.error"
	    set field [my gep $interp 0 Tcl_Interp.errorInfo]
	    set ei [my load $field]
	    my condBr [my nonnull $ei] $clearEI $setEC
	label clearEI "error.clearErrorInfo"
	    my dropReference $ei
	    my store [my null STRING] $field
	    my br $setEC
	label setEC "error.setErrorCode"
	    $api Tcl_SetObjErrorCode $interp $errorcode
	    set field [my gep $interp 0 Tcl_Interp.flags]
	    my store [my or [my load $field] [Const 0x800]] $field
	    my ret
	}

	##### Function tcl.processReturn #####
	#
	# Type signature: result:STRING * code:int * level:int
................................................................................
	set f [$module local "tcl.processReturn" int<-STRING,int,int,STRING]
	params result code level returnOpts
	build {
	    nonnull $result
	    set interp [$api tclInterp]
	    $api Tcl_SetObjResult $interp $result
	    set valuePtr [my alloc STRING "valuePtr"]
	    set field [my gep $interp 0 Tcl_Interp.returnOpts]
	    set ro [my load $field]
	    my condBr [my neq $ro $returnOpts] $swap $testForError
	label swap:
	    my condBr [my nonnull $ro] $swapdropold $swapinnew
	label swapdropold "swap.dropOld"
	    my dropReference $ro
	    my condBr [my nonnull $returnOpts] $swapinnew $totallyNew
................................................................................
	label swapinnew "swap.inNew"
	    my store $returnOpts $field
	    my addReference(STRING) $returnOpts
	    my br $testForError
	label testForError "test.for.error"
	    my condBr [my eq $code $1] $error $testForReturn
	label error:
	    set field [my gep $interp 0 Tcl_Interp.errorInfo]
	    set ei [my load $field]
	    my condBr [my nonnull $ei] $clearEI $getEI
	label clearEI "error.clearErrorInfo"
	    my dropReference $ei
	    my store [my null STRING] $field
	    my br $getEI
	label getEI "error.getErrorInfo"
................................................................................
	label installEI "error.installErrorInfo"
	    set infoLen [my alloc int "infoLen"]
	    $api Tcl_GetStringFromObj $value $infoLen
	    my condBr [my neq [my load $infoLen] $0] $installEI2 $getES
	label installEI2 "error.setErrorInfo"
	    my store $value $field
	    my addReference(STRING) $value
	    set field [my gep $interp 0 Tcl_Interp.flags]
	    my store [my or [my load $field] [Const 4]] $field
	    my br $getES
	label getES "error.getErrorStack"
	    my condBr [my nonnull $returnOpts] $testES $getEC
	label testES "error.testHaveErrorStack"
	    $api Tcl_DictObjGet {} $returnOpts \
		[$api obj.constant "-errorstack"] $valuePtr
	    set value [my load $valuePtr "errorStack"]
	    my condBr [my nonnull $value] $installES $getEC
	label installES "error.installErrorStack"
	    set field [my gep $interp 0 Tcl_Interp.errorStack]
	    my condBr [my shared [my load $field]] $dedupES $getESElems
	label dedupES "error.deduplicateErrorStack"
	    set oldobj [my load $field]
	    set newobj [$api Tcl_DuplicateObj $oldobj]
	    my dropReference $oldobj
	    my addReference(STRING) $newobj
	    my store $newobj $field
................................................................................
	    set objvPtr [my alloc STRING*]
	    my condBr [my neq $0 \
		[$api Tcl_ListObjGetElements $interp $value $objcPtr $objvPtr]]\
		$notList $setES
	label notList "error.getErrorStackElements.notList"
	    my ret $1
	label setES "error.setErrorStack"
	    my store $0 [my gep $interp 0 Tcl_Interp.resetErrorStack]
	    set lenPtr [my alloc int]
	    set es [my load $field]
	    $api Tcl_ListObjLength $interp $es $lenPtr
	    $api Tcl_ListObjReplace $interp \
		$es $0 [my load $lenPtr "len"] \
		[my load $objcPtr "objc"] [my load $objvPtr "objv"]
	    my br $getEC
................................................................................
		[$api obj.constant "-errorcode"] $valuePtr
	    set value [my load $valuePtr "errorCode"]
	    my condBr [my nonnull $value] $installEC $installNone
	label installEC "error.installErrorCode"
	    $api Tcl_SetObjErrorCode $interp $value
	    my br $getEL
	label installNone "error.installNONE"
	    $api Tcl_SetErrorCode $interp [my constString NONE] [my null char*]
	    my br $getEL
	label getEL "error.getErrorLine"
	    my condBr [my nonnull $returnOpts] $testEL $testForReturn
	label testEL "error.testHaveErrorInfo"
	    $api Tcl_DictObjGet {} $returnOpts \
		[$api obj.constant "-errorline"] $valuePtr
	    set value [my load $valuePtr "errorLine"]
	    my condBr [my nonnull $value] $installEL $testForReturn
	label installEL "error.installErrorLine"
	    $api Tcl_GetIntFromObj {} $value \
		[my gep $interp 0 Tcl_Interp.errorLine]
	    my br $testForReturn
	label testForReturn "test.for.return"
	    my condBr [my neq $level $0] $processReturn $retestForError
	label processReturn "return.process"
	    my store $level [my gep $interp 0 Tcl_Interp.returnLevel]
	    my store $code [my gep $interp 0 Tcl_Interp.returnCode]
	    my ret [Const 2];	# TCL_RETURN
	label retestForError "test.for.error"
	    my condBr [my eq $code $1] $addFlag $done
	label addFlag "error.addFlag"
	    set field [my gep $interp 0 Tcl_Interp.flags]
	    my store [my or [my load $field] [Const 0x800]] $field
	    my br $done
	label done:
	    my ret $code
	}
















































































































































	##### Function tcl.booleanTest #####
	#
	# Type signature: objPtr:Tcl_Obj* -> ZEROONE
	#
	# Part of quadcode implementation ('isBoolean')
	#
	# Returns whether the string 'objPtr' is a boolean value.

	set f [$m local "tcl.booleanTest" ZEROONE<-Tcl_Obj*]
	params objPtr
	build {
	    nonnull $objPtr
	    set NULL [my null Tcl_Interp*]
	    set code [my setFromAny [$api tclBooleanType] $NULL $objPtr]
	    my ret [my eq $code $0]
	}

	##### Function tcl.invoke.command #####
	#
	# Type signature: objc:int * objv:STRING* * ecvar:int* -> STRING?
	#
	# Calls the Tcl interpreter to invoke a Tcl command, and packs the
	# result into a STRING FAIL.

	set f [$module local "tcl.invoke.command" STRING?<-int,STRING*,int*]

	params objc objv ecvar
	build {
	    noalias $objv $ecvar
	    nonnull $objv $ecvar
	    set interp [$api tclInterp]


	    set code [$api Tcl_EvalObjv $interp $objc $objv $0]

































































































	    my condBr [my eq $code $0] $ok $fail
	label ok:
	    set result [$api Tcl_GetObjResult $interp]
	    my addReference(STRING) $result
	    my ret [my just $result]
	label fail:
	    my store $code $ecvar
	    my ret [my nothing STRING]
	}

	##### Function tcl.existsOrError #####
	#
	# Type signature: exists:int1 * message:STRING * ecvar:int* -> int1
	#
	# Conditionally generates an error about a non-existing variable.
................................................................................
	    noalias $ecvar
	    nonnull $value $ecvar
	    set interp [$api tclInterp]
	    set bvar [my alloc int]
	    set code [$api Tcl_GetBooleanFromObj $interp $value $bvar]
	    my condBr [my eq $code [Const 0]] $ok $fail
	label fail:
	    my store $code $ecvar
	    my ret [my nothing ZEROONE]
	label ok:
	    my ret [my just [my neq [my load $bvar "bool"] [Const 1]]]
	}



	my @numericConverterFunctions $api







































































    }

    export @apiFunctions
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







|










|
>
>
>
>







>







|






>


>




|
|
>


|







 







|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|











|

|




|







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|


|
>
>
>
|
<
>
>
>
>
>
>
>
>
|
<
|
>
>
>
>
>
>

|
>
>


|
|
<
<
<
<
>





|




>
|
|
>
>
>
>
>
|




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|






|
>
|
>
>
|
>
>
>
>
|




>
>







 







|





|
|






|







 







|






|
>




|







 







|




|




|
<







 







|


|







 







|


|







 







|


|







 








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|



|



|







 







<
|
<







 







>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|







 







|


|







 







|


|







 







|










|


|







 







|



|


|







 







|







 







|



|







 







|
|













|


|







 







|
|













|


|







 







|







 







|







 







|







 







|









|







 







|



|







 







|


|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|


|







 







|








|



|







 







|








|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>







 







|



|







 







|



|







 







|



|







 







|



|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|
>
>

<
<

|



|







 







|







 







|



|







 







|



|







 







|






|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|


|

>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|











|








|







 







|







 







|







 







|










|







 







|







 







|










|




|
|




|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












|











|
>
|

|


>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|


|







 







|
|

|


>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>









>

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
...
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
...
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
...
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
....
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
....
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
....
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
....
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
....
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
....
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
....
1945
1946
1947
1948
1949
1950
1951

1952

1953
1954
1955
1956
1957
1958
1959
....
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
....
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
....
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
....
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
....
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
....
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
....
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
....
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
....
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
....
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
....
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
....
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
....
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
....
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
....
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
....
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
....
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
....
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
....
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
....
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
....
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
....
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
....
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
....
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
....
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270


3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
....
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
....
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
....
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
....
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556










































3557
3558
3559
3560
3561
3562
3563
....
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
....
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
....
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
....
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
....
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
....
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
....
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
....
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
....
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
#	added onto the Builder class, so that it can issue them by just
#	generating a call to the implementation function. This allows us to
#	inject extra basic blocks without disturbing the analysis from the
#	reasoning engine.
#
#	See build.tcl for where these functions are called from.
#
# Copyright (c) 2015-2017 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
oo::define Builder {
    # Variables holding implementations of Tcl's string operators
    variable tcl.stringify.double tcl.stringify.int tcl.stringify.numeric
    variable tcl.addReference tcl.dropReference
    variable tcl.addFailReference tcl.dropFailReference
    variable tcl.addNExistReference tcl.dropNExistReference
    variable tcl.dropFailNExistReference
    variable tcl.dropReference.failImpureInt tcl.dropReference.failImpureDouble
    variable tcl.dropReference.failImpureZeroOneBoolean
    variable tcl.unshare tcl.unshare.copy
    variable tcl.strlen tcl.append.string tcl.streq tcl.strcmp tcl.strmatch
    variable tcl.stridx tcl.stridx.idx
    variable tcl.strrange tcl.strrange.idx tcl.strreplace tcl.strreplace.idx
    variable tcl.strfind.fwd tcl.strfind.rev
    variable tcl.strmap tcl.strtrim tcl.strcase tcl.strclass
    variable tcl.regexp tcl.concatenate tcl.booleanTest tcl.not.string
    variable tcl.resolveCmd tcl.originCmd

    # Variables holding implementations of Tcl's list operators
    variable tcl.list.create tcl.list.length tcl.list.append tcl.list.concat
    variable tcl.list.foreach.getStep tcl.list.foreach.mayStep
    variable tcl.list.foreach.nextStep tcl.list.foreach.start tcl.list.unshare
    variable tcl.list.range tcl.list.range1 tcl.list.in
    variable tcl.list.index tcl.list.index1 tcl.list.indexList
    variable tcl.list.set tcl.list.set1 tcl.list.setList tcl.list.verify

    # Variables holding implementations of Tcl's dict operators
    variable tcl.dict.get1 tcl.dict.get tcl.dict.set1 tcl.dict.set
    variable tcl.dict.exists1 tcl.dict.exists tcl.dict.unset1 tcl.dict.unset
    variable tcl.dict.iterStart tcl.dict.iterNext tcl.dict.iterDone
    variable tcl.dict.iterKey tcl.dict.iterValue tcl.dict.addIterReference
    variable tcl.dict.addIterFailReference
    variable tcl.dict.dropIterReference tcl.dict.dropIterFailReference
    variable tcl.dict.append tcl.dict.lappend tcl.dict.incr tcl.dict.size
    variable tcl.dict.get1.empty tcl.dict.set1.empty
    variable tcl.maptoint

    # Variables holding implementations of Tcl's exception-handling machinery
    variable tcl.getresult tcl.getreturnopts tcl.initExceptionOptions
    variable tcl.initExceptionSimple tcl.processReturn tcl.procedure.return
    variable tcl.setErrorLine tcl.existsOrError tcl.logCommandInfo
    variable tcl.handleExceptionResult tcl.invoke.command tcl.invoke.expanded

    # Helper functions
    variable tcl.impl.trimleft tcl.impl.trimright obj.cleanup
    variable tcl.impl.getIndex tcl.impl.listDupe

    # Reference to the module object
    variable m
 
    # Builder:ReferenceFunctions --
    #
................................................................................
	params value:objPtr
	build {
	    nonnull $value
	    $api Tcl_DecrRefCount $value
	    my ret
	}

	##### tcl.addFailReference #####
	#
	# Type signature: objPtr:Tcl_Obj*? -> void
	#
	# Increment the reference count of a Tcl_Obj reference if the
	# object is supplied

	set f [$m local "tcl.addFailReference" void<-Tcl_Obj*?]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $incr
	label incr "action.required"
	    set value [my unmaybe $value "objPtr"]
	    $api Tcl_IncrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropFailReference #####
	#
	# Type signature: objPtr:Tcl_Obj*? -> void
	#
	# Decrement the reference count of a Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropFailReference" void<-Tcl_Obj*?]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $decr
	label decr "action.required"
	    set value [my unmaybe $value "objPtr"]
	    $api Tcl_DecrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.addNExistReference #####
	#
	# Type signature: objPtr:Tcl_Obj*! -> void
	#
	# Increment the reference count of a Tcl_Obj reference if the
	# object is supplied

	set f [$m local "tcl.addNExistReference" void<-Tcl_Obj*!]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $incr
	label incr "action.required"
	    set value [my unmaybe $value "objPtr"]
	    $api Tcl_IncrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropNExistReference #####
	#
	# Type signature: objPtr:Tcl_Obj*! -> void
	#
	# Decrement the reference count of a Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropNExistReference" void<-Tcl_Obj*!]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $decr
	label decr "action.required"
	    set value [my unmaybe $value "objPtr"]
	    $api Tcl_DecrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropFailNExistReference #####
	#
	# Type signature: objPtr:Tcl_Obj*!? -> void
	#
	# Decrement the reference count of a Maybe Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropFailNExistReference" void<-Tcl_Obj*!?]
	params value:maybeObjPtr
	build {
	    my condBr [my maybe $value] $nothing $decr
	label decr "action.required"
	    my Call tcl.dropNExistReference [my unmaybe $value]
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropReference.failImpureInt #####
	#
	# Type signature: objPtr:<INT>? -> void
	#
	# Decrement the reference count within a Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropReference.failImpureInt" void<-<INT>?]
	params value
	build {
	    my condBr [my maybe $value] $nothing $incr
	label incr "action.required"
	    set value [my impure.string [my unmaybe $value "objPtr"]]
	    $api Tcl_DecrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropReference.failImpureDouble #####
	#
	# Type signature: objPtr:<DOUBLE>? -> void
	#
	# Decrement the reference count within a Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropReference.failImpureDouble" void<-<DOUBLE>?]
	params value
	build {
	    my condBr [my maybe $value] $nothing $incr
	label incr "action.required"
	    set value [my impure.string [my unmaybe $value "objPtr"]]
	    $api Tcl_DecrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.dropReference.failImpureZeroOneBoolean #####
	#
	# Type signature: objPtr:<ZEROONE BOOLEAN>? -> void
	#
	# Decrement the reference count within a Maybe containing a Tcl_Obj
	# reference, and delete it if the reference count drops to zero.

	set f [$m local "tcl.dropReference.failImpureZeroOneBoolean" void<-<ZEROONE>?]
	params value
	build {
	    my condBr [my maybe $value] $nothing $incr
	label incr "action.required"
	    set value [my impure.string [my unmaybe $value "objPtr"]]
	    $api Tcl_DecrRefCount $value
	    my ret
	label nothing "nothing.to.do"
	    my ret
	}

	##### tcl.unshare #####
	#
	# Type signature: objPtr:Tcl_Obj* -> Tcl_Obj*
................................................................................
	##### Closure Build:printref #####
	#
	# Type signature: val:STRING -> void
	#
	# Print a description of the given Tcl_Obj reference. Used for
	# debugging reference counts.

	set f [$m local writeref void<-int,STRING,char* noinline]
	params pr val prefix
	build {
	    set chan [$api Tcl_GetStdChannel [Const [expr 1<<3]]]
	    my condBr [my nonnull $prefix] $printPrefix $printRef0
	label printPrefix "print.prefix"
	    set str [$api Tcl_NewStringObj $prefix [Const -1]]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    my br $printRef0
	label printRef0 "check.print.reference"
	    my condBr [my nonnull $val] $printRef $gotNull
	label printRef "print.reference"
	    # Multi-stage print so we still get something useful when memory
	    # is corrupted.
	    set str [$api Tcl_ObjPrintf \
			 [my constString "%d:0x%X"] \
			 $pr [my castPtr2Int $val int]]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    set rc [my refCount $val]
	    set str [$api Tcl_ObjPrintf \
			 [my constString "(%.30s) => %d\n"] \
			 [$api Tcl_GetString $val] $rc]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    my ret
	label gotNull "got.null"
	    set str [$api Tcl_ObjPrintf [my constString "%d:NULL\n"] $pr]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    my ret
	}
	set f [$m local writeref? void<-int,STRING?,char*]
	params pr val prefix
	build {
	    my condBr [my maybe $val] $done $print
	label print:
	    my Call writeref $pr [my unmaybe $val] $prefix
	    my ret
	label done:
	    my ret
	}
	set f [$m local writearef void<-int,ARRAY,char*]
	params pr val prefix
	build {
	    nonnull $val
	    set chan [$api Tcl_GetStdChannel [Const [expr 1<<3]]]
	    my condBr [my nonnull $prefix] $printPrefix $printRef
	label printPrefix "print.prefix"
	    set str [$api Tcl_NewStringObj $prefix [Const -1]]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    my br $printRef
	label printRef "print.reference"
	    # Multi-stage print so we still get something useful when memory
	    # is corrupted.
	    set str [$api Tcl_ObjPrintf \
			 [my constString "%d:0x%X"] \
			 $pr [my castPtr2Int $val int]]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    set rc [my dereference $val 0 ARRAYIMPL.ref]
	    set str [$api Tcl_ObjPrintf \
			 [my constString "\[\] => %d\n"] \
			 $rc]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    my ret
	}
	my closure printref {val {prefix ""}} {
	    if {![info exists ::env(TQC_PRINT_REFERENCE_MANAGEMENT)]} {
		return
	    }
	    if {[TypeOf $val] eq [Type STRING]} {
		set writerFunc writeref
	    } elseif {[TypeOf $val] eq [Type STRING?]} {
		set writerFunc writeref?
	    } elseif {[TypeOf $val] eq [Type ARRAY]} {

		set writerFunc writearef
	    } elseif {[GetTypeKind [TypeOf $val]] eq "LLVMStructTypeKind"} {
		set idx -1
		foreach t [GetStructElementTypes [TypeOf $val]] {
		    incr idx
		    if {$t eq [Type STRING] || $t eq [Type STRING?]
			    || [GetTypeKind $t] eq "LLVMStructTypeKind"} {
			my printref [my extract $val $idx] $prefix
		    }

		}
		return
	    } else {
		my Warn "printref incomplete for \"%s\"" \
		    [PrintValueToString $val]
		return
	    }
	    if {$prefix ne ""} {
		set prefix [my constString $prefix]
	    } else {
		set prefix [my null char*]
	    }
	    variable prcount
	    set pr [Const [incr prcount]]
	    # set name [format %.30s... [PrintValueToString $val]]




	    my Call $writerFunc $pr $val $prefix
	    return
	}

	##### Closure Build:memcpy #####
	#
	# Type signature: target:[?]* * source:[?]* * length:int[?] -> void
	#
	# Copy memory of size 'length' from 'source' to 'target'.

	my closure memcpy {target source length} {
	    set vt [Type void*]
	    set memcpy [$m intrinsic memcpy $vt $vt [TypeOf $length]]
	    if {[TypeOf $target] ne $vt} {
		set target [my cast(ptr) $target void]
	    }
	    if {[TypeOf $source] ne $vt} {
		set source [my cast(ptr) $source void]
	    }
	    my Call memcpy $target $source $length \
		    [Const 0] [Const false bool]
	    return
	}

	##### Closure Build:bzero #####
	#
	# Type signature: memoryBlock:[?]* * length:int[?] -> void
	#
	# Zeroes memory of size 'length' starting at 'memoryBlock'. An
	# optional alignment may be given (as a simple Tcl integer); it
	# defaults to the platform alignment size, which is ideal for zeroing
	# normal structures on modern architectures.

	my closure bzero {target length {alignment -1}} {
	    if {$alignment < 0} {
		set alignment $::tcl_platform(wordSize)
	    }
	    set vt [Type void*]
	    set memset [$m intrinsic memset $vt [TypeOf $length]]
	    if {[TypeOf $target] ne $vt} {
		set target [my cast(ptr) $target void]
	    }
	    my Call memset $target [Const 0 int8] $length \
		[Const $alignment] [Const false bool]
	    return
	}

	##### Closure Build:memcmp #####
	#
	# Type signature: a:[?]* * b:[?]* * length:int[?] -> int
	#
	# Compare memory of size 'length' between 'a' and 'b'.

	set memcmp [$m function.extern memcmp \
		[Type func{int<-void*,void*,$size_t}] readonly]
	my closure memcmp {bytes1 bytes2 length {name "cmp"}} {
	    set vt [Type void*]
	    if {[TypeOf $bytes1] ne $vt} {
		set bytes1 [my cast(ptr) $bytes1 void]
	    }
	    if {[TypeOf $bytes2] ne $vt} {
		set bytes2 [my cast(ptr) $bytes2 void]
	    }
	    if {[TypeOf $length] ne [Type $size_t]} {
		set length [my castInt2Int $length $size_t]
	    }
	    my call $memcmp [list $bytes1 $bytes2 $length] $name
	}

	my StringInspectionFunctions $api
	my StringWritingFunctions $api
	my ListFunctions $api
	my DictionaryFunctions $api
	my StringComparisonFunctions $api

	return
    }
 
    # Builder:StringInspectionFunctions --
    #
................................................................................
	    my ret $res
	}
	unset -nocomplain valueObj

	##### Function tcl.impl.getWide #####
	##### MAPPED CALL TO METHOD: Build:GetWide #####
	#
	# Type signature: valueObj:STRING -> bool * int64
	#
	# Gets an int64 from a Tcl string. Wrapper around Tcl API to ensure
	# that scope lifetime gets better understood.

	set f [$m local "tcl.impl.getWide" struct{int1,int64}<-STRING]
	my closure GetWide {valueObj {name "result"}} {
	    my call ${tcl.impl.getWide} [list $valueObj] $name
	}
	params valueObj
	build {
	    nonnull $valueObj
	    set intVar [my alloc int64 "intPtr"]
	    set code [$api Tcl_GetWideIntFromObj {} $valueObj $intVar]
	    set res [my undef struct{bool,int64}]
	    set res [my insert $res [my eq $code [Const 0]] 0]
	    set res [my insert $res [my load $intVar "int"] 1 "result"]
	    my ret $res
	}
	unset -nocomplain valueObj

	##### Function tcl.impl.getString #####
................................................................................
	label fail:
	    my ret [Const false bool]
	}

	##### Function tcl.impl.getIndex #####
	##### Closure Build:GetIndex #####
	#
	# Type signature: interp:Interp* * objPtr:Tcl_Obj* * end:int
	#			-> int1 * int
	#
	# Converts an index string into an offset into something (i.e., a
	# string or list). Returns a tuple of whether the conversion succeeded
	# (a boolean) and the index.

	set f [$m local "tcl.impl.getIndex" \
		   struct{bool,int}<-Interp*,Tcl_Obj*,int readonly]
	unset -nocomplain objPtr end
	my closure GetIndex {interp objPtr end {indexVar dummy}} {
	    upvar 1 $indexVar index
	    if {$interp eq ""} {
		set interp [my null Interp*]
	    }
	    set res [my Call tcl.impl.getIndex $interp $objPtr $end]
	    set index [my extract $res 1 "getIndex.index"]
	    return [my extract $res 0 "getIndex.result"]
	}
	params interp objPtr end
	build {
................................................................................
    # that this is necessarily so.
    method StringWritingFunctions {api} {
	upvar 1 sizeof sizeof 0 0 1 1 -1 -1

	##### Function tcl.setFromAny #####
	##### Closure Build:setFromAny #####
	#
	# Type signature: typePtr:ObjType* * interp:Interp*
	#			* objPtr:STRING -> int
	#
	# Call the given type's setFromAnyProc on the given object.

	set f [$m local "tcl.setFromAny" int<-ObjType*,Interp*,STRING]
	params typePtr interp objPtr
	build {
	    noalias $typePtr $interp $objPtr
	    nonnull $typePtr $objPtr
	    set func [my dereference $typePtr 0 ObjType.setFromAnyProc]

	    set code [my Call $func $interp $objPtr]
	    SetValueName $code "code"
	    AddCallAttribute $code 1 nocapture
	    AddCallAttribute $code 2 nocapture
	    my ret $code
	}
	my closure setFromAny {TYPE INTERP VALUE {name "code"}} {
................................................................................
	    set unicodeResult [$api Tcl_NewStringObj $buf $len]
	    my br $done
	label done:
	    set result [my phi \
		    [list $emptyResult $byteResult $asciiResult $unicodeResult] \
		    [list $empty $baIdx $byteIndex $strIdx] "result"]
	    my addReference(STRING) $result
	    my ret [my ok $result]
	label failed:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.strrange #####
	#
	# Type signature: objPtr:STRING * fromInt:INT * toInt:INT -> STRING
	#
	# Quadcode implementation ('strrange')
................................................................................
	label realSubstring:
	    set value2 [$api Tcl_GetRange $str $from $to]
	    my br $finish
	label finish:
	    set result [my phi [list $value1 $value2] \
		    [list $empty $realSubstring] "result"]
	    my addReference(STRING) $result
	    my ret [my ok $result]
	label failed:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.strreplace #####
	#
	# Type signature: objPtr:STRING * fromInt:INT * toInt:INT
	#			* substringPtr:STRING -> STRING
	#
................................................................................
	label getTo:
	    my condBr [my GetIndex $interp $toIdx $end to] \
		$rangeCheck $failed
	label rangeCheck:
	    set from [my packInt32 $from]
	    set to [my packInt32 $to]
	    set replaced [my Call tcl.strreplace $str $from $to $substr]
	    my ret [my ok $replaced]
	label failed:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.strmap #####
	#
	# Type signature: sourceObj:STRING * targetObj:STIRNG *
	#			stringObj:STRING -> STRING
	#
................................................................................
	label releaseIntRep "release.internal.representation"
	    $api TclFreeIntRep $string
	    my br $done
	label done:
	    my addReference(STRING) $string
	    my ret $string
	}

	##### Function tcl.maptoint #####
	#
	# Type signature: value:STRING * mapping:STRING * notThere:int -> INT
	#
	# Quadcode implementation ('maptoint')
	#
	# Returns the INT looked up in 'mapping' that corresponds to 'value'.
	# If the value is absent, returns the 'notThere' value.

	set f [$m local "tcl.maptoint" INT<-STRING,HashTable*,int]
	params value mapping notThere
	build {
	    nonnull $value $mapping
	    set offset [$api TclFindHashEntry $mapping $value]
	    SetValueName $offset "offsetPtr"
	    my condBr [my nonnull $offset] $present $absent
	label present:
	    set offset [$api Tcl_GetHashValue $offset int]
	    SetValueName $offset "offset"
	    my ret [my packInt32 $offset]
	label absent:
	    my ret [my packInt32 $notThere]
	}

	##### Function tcl.concatenate #####
	#
	# Type signature: len:int * ary:STRING* -> STRING
	#
	# Quadcode implementation ('concat')
	#
	# Returns the application of Tcl_ConcatObj() to the given values, so
	# much so that it is just a very thin wrapper around that function.

	set f [$m local "tcl.concatenate" STRING<-int,STRING*]
	params len ary
	build {
	    nonnull $ary
	    set result [$api Tcl_ConcatObj $len $ary]
	    my addReference(STRING) $result
	    my ret $result
	}
    }
 
    # Builder:ListFunctions --
    #
    #	Generate the functions that implement the list-handling operators.
    #	Only called from StringFunctions method.
    #
    # Parameters:
    #	api -	The handle of the Tcl API object (currently an instance of the
    #		Thunk class).
    #
    # Results:
    #	None.

    method ListFunctions {api} {
	upvar 1 0 0 1 1 -1 -1

	##### Function tcl.impl.listDupe #####
	##### Closure Build:ListDupe #####
	#
	# Type signature: interp:Interp* * obj:STRING -> STRING
	#
	# Replacement for non-exposed TclListObjCopy().

	set f [$m local "tcl.impl.listDupe" STRING<-Interp*,STRING]
	unset -nocomplain interp objPtr name
	my closure ListDupe {interp objPtr {name ""}} {
	    if {$interp eq ""} {
		set interp [my null Interp*]
	    }
	    my call ${tcl.impl.listDupe} [list $interp $objPtr] $name
	}
	params interp obj
	build {
	    noalias $interp $obj
	    nonnull $obj
................................................................................
		$forceType $ok
	label forceType:
	    my condBr [my eq [my setFromAny $listType $interp $obj] $0] \
		$ok $fail
	label ok:
	    set new [$api Tcl_NewObj]
	    $api TclInvalidateStringRep $new

	    set func [my dereference $listType 0 ObjType.dupIntRepProc]

	    set call [my Call $func $obj $new]
	    AddCallAttribute $call 1 nocapture
	    AddCallAttribute $call 2 nocapture
	    my ret $new
	label fail:
	    my ret [my null STRING]
	}
................................................................................
	    noalias $list $ecvar
	    nonnull $list $ecvar
	    set interp [$api tclInterp]
	    set var [my alloc int "length"]
	    set code [$api Tcl_ListObjLength $interp $list $var]
	    my condBr [my eq $code $0] $ok $fail
	label ok:
	    my ret [my ok [my packInt32 [my load $var]]]
	label fail:
	    my store $1 $ecvar
	    my ret [my fail INT]
	}

	##### Function tcl.list.verify #####
	#
	# Type signature: value:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('verifyList')
	#
	# Wrapper around a list operation (Tcl_ListObjLength) that verifies
	# that the value it is dealing with is a list; converting it to a FAIL
	# if it is not.

	set f [$m local "tcl.list.verify" STRING?<-STRING,int*]
	params value ecvar
	build {
	    noalias $value $ecvar
	    nonnull $value $ecvar
	    set interp [$api tclInterp]
	    set var [my alloc int "length"]
	    set code [$api Tcl_ListObjLength $interp $value $var]
	    my condBr [my eq $code $0] $ok $fail
	label ok:
	    $api Tcl_IncrRefCount $value
	    my ret [my ok $value]
	label fail:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.append #####
	#
	# Type signature: list:STRING * value:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listAppend')
................................................................................
	    $api TclInvalidateStringRep $list
	    my addReference(STRING) $list
	    my condBr [my shared $value] $exit $extraRef
	label extraRef "add.extra.reference.to.value"
	    my addReference(STRING) $value
	    my br $exit
	label exit:
	    my ret [my ok $list]
	label error:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.concat #####
	#
	# Type signature: list:STRING * value:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listConcat')
................................................................................
	    my br $concat
	label concat:
	    set working [my phi [list $list $copy] [list $checkDupe $dupe] "list"]
	    set objc [my load $objc "objc"]
	    set objv [my load $objv "objv"]
	    $api Tcl_ListObjReplace {} $working $len $0 $objc $objv
	    my addReference(STRING) $working
	    my ret [my ok $working]
	label error:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.index #####
	#
	# Type signature: list:STRING * idxc:int * idxv:STRING* * ecvar:int*
	#			-> STRING?
	#
................................................................................
	    my condBr [my lt $i $idxc] $loopIndexValidityCheck $loopEmpty
	label loopEmpty:
	    my store [set list [$api Tcl_NewObj]] $listPtr
	    my addReference(STRING) $list
	    my br $loopNext
	label loopIndexValidityCheck:
	    my condBr [my GetIndex $interp \
		    [my load [my getelementptr $idxv [list $i]]] ${-1}] \
		$loopIndexOutOfRange $loopIndexBad
	label loopIndexBad:
	    my dropReference $sublistCopy
	    my br $error
	label loopNext:
	    my dropReference $sublistCopy
	    my store [my add [my load $iPtr "i"] $1] $iPtr
	    my br $loopTest
	label done:
	    set list [my load $listPtr "list"]
	    my ret [my ok $list]
	label error:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.index1 #####
	#
	# Type signature: list:STRING * index:INT * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listIndex')
................................................................................
	label ok:
	    my condBr [my and [my ge $idx $0] [my lt $idx [my load $objc]]] \
		$realIndex $outOfBounds
	label realIndex "real.index"
	    set objv [my load $objv "objv"]
	    set obj [my load [my getelementptr $objv [list $idx]] "objPtr"]
	    my addReference(STRING) $obj
	    my ret [my ok $obj]
	label outOfBounds "out.of.bounds"
	    set obj [$api Tcl_NewObj]
	    my addReference(STRING) $obj
	    my ret [my ok $obj]
	label fail:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.indexList #####
	#
	# Type signature: list:STRING * index:STRING * ecvar:int* -> STRING?
	#
	# Core of quadcode implementation ('listIndex')
................................................................................
	    set objc [my alloc int "objc"]
	    set objv [my alloc STRING* "objv"]
	    set code [$api Tcl_ListObjGetElements $interp $list $objc $objv]
	    my condBr [my eq $code $0] $checkType $notList
	label notList:
	    # We're not a list and we know it right now
	    my store $1 $ecvar
	    my ret [my fail STRING]
	label checkType:
	    my condBr [my neq [my dereference $index 0 Tcl_Obj.typePtr] \
			[$api tclListType]] \
		$checkIndex $slowPath
	label checkIndex:
	    set len [my load $objc]
	    my condBr [my GetIndex {} $index $len idx] \
................................................................................
	label immediateIndex:
	    my condBr [my and [my ge $idx $0] [my lt $idx $len]] \
		$realIndex $outOfBounds
	label realIndex "real.index"
	    set objv [my load $objv "objv"]
	    set obj [my load [my getelementptr $objv [list $idx]] "objPtr"]
	    my addReference(STRING) $obj
	    my ret [my ok $obj]
	label outOfBounds "out.of.bounds"
	    set obj [$api Tcl_NewObj]
	    my addReference(STRING) $obj
	    my ret [my ok $obj]
	label slowPath:
	    set dupe [my ListDupe $interp $index "copy"]
	    my condBr [my nonnull $dupe] $okIndex $notList
	label okIndex:
	    set listRep [my load [my cast(ptr) \
		    [my gep $dupe 0 Tcl_Obj.internalRep 0] \
		    TclList*] "listRep"]
................................................................................
		$sublistInplaceFree $sublistInplaceDone
	label sublistInplaceFree "sublist.inPlace.loop.body"
	    ReplaceAllUsesWith $loopIndex [my add $index $1 "index"]
	    set obj [my load [my getelementptr $objv [list $index]] "objPtr"]
	    my dropReference $obj
	    my br $sublistInplaceFreeTest
	label sublistInplaceDone "sublist.inPlace.done"
	    my storeInStruct $listPtr TclList.elemCount $onePast
	    my storeInStruct $listPtr TclList.canonicalFlag $1
	    $api TclInvalidateStringRep $list
	    my br $ok
	label sublistNew "sublist.new"
	    set r1 [$api Tcl_NewListObj [my add [my sub $to $from] $1] \
		    [my getelementptr $objv [list $from]]]
	    my br $ok
	label empty:
	    set r2 [$api Tcl_NewObj]
	    my br $ok
	label ok:
	    set sources [list $sublistInplaceDone $sublistNew $empty]
	    set result [my phi [list $list $r1 $r2] $sources "result"]
	    my addReference(STRING) $result
	    my ret [my ok $result]
	label error:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.range1 #####
	#
	# Type signature: list:STRING * from:INT * to:INT -> STRING?
	#
	# Core of quadcode implementation ('listRangeImm')
................................................................................
		$sublistInplaceFree $sublistInplaceDone
	label sublistInplaceFree "sublist.inPlace.free"
	    ReplaceAllUsesWith $loopIndex [my add $index $1 "index"]
	    set obj [my load [my getelementptr $objv [list $index]] "objPtr"]
	    my dropReference $obj
	    my br $sublistInplaceFreeTest
	label sublistInplaceDone "sublist.inPlace.done"
	    my storeInStruct $listPtr TclList.elemCount $onePast
	    my storeInStruct $listPtr TclList.canonicalFlag $1
	    $api TclInvalidateStringRep $list
	    my br $ok
	label sublistNew "sublist.new"
	    set r1 [$api Tcl_NewListObj [my add [my sub $to $from] $1] \
		    [my getelementptr $objv [list $from]]]
	    my br $ok
	label empty:
	    set r2 [$api Tcl_NewObj]
	    my br $ok
	label ok:
	    set sources [list $sublistInplaceDone $sublistNew $empty]
	    set result [my phi [list $list $r1 $r2] $sources "result"]
	    my addReference(STRING) $result
	    my ret [my ok $result]
	label error:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.set #####
	#
	# Type signature: list:STRING * idxc:int * idxv:STRING* * elem:STRING
	#			* ecvar:int* -> STRING?
	#
................................................................................
	build {
	    noalias $idxv $ecvar
	    nonnull $list $idxv $elem $ecvar
	    set interp [$api tclInterp]
	    my condBr [my eq $idxc $0] $doNothing $sharedCheck
	label doNothing:
	    my addReference(STRING) $list
	    my ret [my ok $list]
	label sharedCheck:
	    my condBr [my shared $list] $duplicate $prepareToLoop
	label duplicate:
	    set dupe [$api Tcl_DuplicateObj $list]
	    my br $prepareToLoop
	label prepareToLoop:
	    set sources [list $sharedCheck $duplicate]
................................................................................
	    my condBr [my neq $retValue $list] \
		$loopFailDropOverall $loopFailExit
	label loopFailDropOverall:
	    my dropReference $retValue
	    my br $loopFailExit
	label loopFailExit:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	label loopEnd:
	    set sublist [my load $subList]
	    set obj [my load $chain]
	    my condBr [my nonnull $obj] $loopEndDrop $terminalSet
	label loopEndDrop:
	    set ptr2 \
		[my cast(ptr) [my gep $obj 0 Tcl_Obj.internalRep 1] STRING]
................................................................................
	    $api TclInvalidateStringRep $sublist
	    my addReference(STRING) $retValue
	    my condBr [my shared $elem] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $elem
	    my br $exit2
	label exit2 "exit"
	    my ret [my ok $retValue]
	}

	##### Function tcl.list.set1 #####
	#
	# Type signature: list:STRING * index:INT * elem:STRING * ecvar:int*
	#			-> STRING?
	#
................................................................................
	    $api TclInvalidateStringRep $list
	    my addReference(STRING) $list
	    my condBr [my shared $elem] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $elem
	    my br $exit2
	label exit2 "exit"
	    my ret [my ok $list]
	label outRange "failure.outOfRange"
	    $api Tcl_SetObjResult $interp \
		[$api obj.constant "list index out of range"]
	    $api Tcl_SetObjErrorCode $interp \
		[$api obj.constant {TCL OPERATION LSET BADINDEX}]
	    my br $out
	label out "failure.exit"
	    my Call obj.cleanup $duped
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.list.setList #####
	#
	# Type signature: list:STRING * idxArg:STRING * elem:STRING
	#			* ecvar:int* -> STRING?
	#
................................................................................
	    my condBr [my eq [my memcmp $bytes1 $bytes2 $len1] $0] \
		$done $loopNext
	label loopNext:
	    ReplaceAllUsesWith $iLoop [set i [my add $i $1 "i"]]
	    my condBr [my lt $i $objc] $loop $done
	label fail:
	    my store $1 $ecVar
	    my ret [my fail ZEROONE]
	label done:
	    set flag [my phi [list [Const false bool] [Const false bool] [Const true bool]] \
		    [list $realCheck $loopNext $loopCompare] "flag"]
	    my ret [my ok $flag]
	}

	##### Function tcl.list.unshare #####
	#
	# Type signature: list:STRING -> STRING
	#
	# Core of quadcode implementation ('unshareList')
................................................................................
	    ReplaceAllUsesWith $maxLoop [my max $iterTmp $max "max"]
	    ReplaceAllUsesWith $iLoop [my add $i $1 "i"]
	    my br $loopStart
	label ok:
	    set pair [my undef FOREACH]
	    set pair [my insert $pair $0 FOREACH.val]
	    set pair [my insert $pair $max FOREACH.max]
	    my ret [my ok $pair]
	label fail:
	    my store $1 $ecVar
	    my ret [my fail FOREACH]
	}

	##### Function tcl.list.foreach.getStep #####
	#
	# Type signature: pair:FOREACH -> INT
	#
	# Core of quadcode implementation ('foreachIter')
................................................................................

	set f [$m local "tcl.list.foreach.nextStep" FOREACH<-FOREACH readnone]
	params pair
	build {
	    set val [my extract $pair FOREACH.val]
	    my ret [my insert $pair [my add $val $1] FOREACH.val]
	}
    }
 
    # Builder:DictionaryFunctions --
    #
    #	Generate the functions that implement the dict-handling operators.
    #	Only called from StringFunctions method.
    #
    # Parameters:
    #	api -	The handle of the Tcl API object (currently an instance of the
    #		Thunk class).
    #
    # Results:
    #	None.

    method DictionaryFunctions {api} {
	upvar 1 0 0 1 1

	##### Function tcl.dict.exists1 #####
	#
	# Type signature: dict:STRING * key:STRING -> ZEROONE
	#
	# Tests if a key is in a dictionary.

................................................................................
	    noalias $ecvar
	    nonnull $dict $ecvar
	    set interp [$api tclInterp]
	    set size [my alloc int "size"]
	    set code [$api Tcl_DictObjSize $interp $dict $size]
	    my condBr [my eq $code $0] $ok $fail
	label ok:
	    my ret [my ok [my packInt32 [my load $size]]]
	label fail:
	    my store $1 $ecvar
	    my ret [my fail INT]
	}

	##### Function tcl.dict.get1 #####
	#
	# Type signature: dict:STRING * key:STRING * ecvar:int32* -> STRING?
	#
	# Gets a value by key from a dictionary.  Can fail if the "dict" is
................................................................................
	    set result [$api Tcl_DictObjGet $interp $dict $key $resvar]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    set value [my load $resvar "value"]
	    my condBr [my nonnull $value] $return $fail
	label return:
	    my addReference(STRING) $value
	    my ret [my ok $value]
	label fail:
	    set keyval [$api Tcl_GetString $key]
	    $api Tcl_SetObjResult $interp \
		[$api Tcl_ObjPrintf [my constString \
			"key \"%s\" not known in dictionary"] \
		    $keyval]
	    $api Tcl_SetErrorCode $interp \
		[my constString TCL] [my constString LOOKUP] \
		[my constString DICT] $keyval {}
	    my br $notOK
	label notOK:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.get #####
	#
	# Type signature: dict:STRING * pathlen:int * pathobjs:STRING*
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    my condBr [my eq $result $0] $OK $fail
	label OK:
	    set value [my load $resvar "value"]
	    my condBr [my nonnull $value] $return $fail
	label return:
	    set value [my phi [list $dict $value] [list $verify $OK] "value"]
	    my addReference(STRING) $value
	    my ret [my ok $value]
	label fail:
	    set keyval [$api Tcl_GetString $key]
	    $api Tcl_SetObjResult $interp \
		[$api Tcl_ObjPrintf [my constString \
			"key \"%s\" not known in dictionary"] \
		    $keyval]
	    $api Tcl_SetErrorCode $interp \
		[my constString TCL] [my constString LOOKUP] \
		[my constString DICT] $keyval {}
	    my br $notOK
	label notOK:
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.get1.empty #####
	#
	# Type signature: dict:STRING * key:STRING * ecvar:int32* -> STRING!?
	#
	# Gets a value by key from a dictionary. Can only fail if the "dict"
	# is not a valid dictionary; an absent key in the terminal dictionary
	# is reported as an NEXIST result.

	set f [$m local "tcl.dict.get1.empty" STRING!?<-STRING,STRING,int*]
	params dict key ecvar
	build {
	    noalias $ecvar
	    nonnull $dict $key $ecvar
	    set interp [$api tclInterp]
	    set resvar [my alloc STRING "valueVar"]
	    set result [$api Tcl_DictObjGet $interp $dict $key $resvar]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    set value [my load $resvar "value"]
	    my condBr [my nonnull $value] $return $empty
	label return:
	    my addReference(STRING) $value
	    my ret [my ok [my just $value]]
	label empty:
	    my ret [my ok [my nothing STRING]]
	label notOK:
	    my store $1 $ecvar
	    my ret [my fail STRING!]
	}

	##### Function tcl.dict.set1 #####
	#
	# Type signature: dict:STRING * key:STRING * value:STRING
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	label OK:
	    my addReference(STRING) $dict
	    my condBr [my shared $value] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $value
	    my br $exit2
	label exit2 "exit"
	    my ret [my ok $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.set #####
	#
	# Type signature: dict:STRING * pathlen:int * pathobjs:STRING*
	#			* value:STRING * ecvar:int32* -> STRING?
	#
................................................................................
	label OK:
	    my addReference(STRING) $dict
	    my condBr [my shared $value] $exit2 $exit3
	label exit3 "exit"
	    my addReference(STRING) $value
	    my br $exit2
	label exit2 "exit"
	    my ret [my ok $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.unset1 #####
	#
	# Type signature: dict:STRING * key:STRING * ecvar:int32* -> STRING?
	#
	# Removes a key from a dictionary.  Can fail if the "dict" is not a
................................................................................
	    nonnull $dict $key $ecvar
	    set interp [$api tclInterp]
	    set dd [my Dedup dict]
	    set result [$api Tcl_DictObjRemove $interp $dict $key]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    my addReference(STRING) $dict
	    my ret [my ok $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.unset #####
	#
	# Type signature: dict:STRING * pathlen:int * pathobjs:STRING*
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    noalias $dict $pathobjs $ecvar
	    nonnull $dict $pathobjs $ecvar
	    set interp [$api tclInterp]
	    set dd [my Dedup dict]
	    set result [$api Tcl_DictObjRemoveKeyList $interp $dict $pathlen $pathobjs]
	    my condBr [my eq $result $0] $OK $notOK
	label OK:
	    my ret [my ok $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.set1.empty #####
	#
	# Type signature: dict:STRING * key:STRING * value:STRING!
	#			* ecvar:int32* -> STRING?
	#
	# Sets a key in a dictionary to map to a value, or removes the mapping
	# if the value is NEXIST. Can fail if the "dict" is not a valid
	# dictionary.

	set f [$m local "tcl.dict.set1.empty" \
		   STRING?<-STRING,STRING,STRING!,int*]
	params dict key value ecvar
	build {
	    noalias $ecvar
	    nonnull $dict $key $ecvar
	    my condBr [my exists $value] $reallySet $reallyUnset
	label reallySet "real.set"
	    set value [my unmaybe $value]
	    my ret [my Call tcl.dict.set1 $dict $key $value $ecvar]
	label reallyUnset "real.unset"
	    my ret [my Call tcl.dict.unset1 $dict $key $ecvar]
	}

	##### Function tcl.dict.addIterReference #####
	#
	# Type signature: iter:DICTITER -> void
	#
	# Increments the reference count inside a dictionary iteration state.
................................................................................
	build {
	    nonnull $iter
	    set ref [my gep $iter 0 DICTFOR.ref]
	    set rc [my load $ref]
	    my store [my add $rc $1] $ref
	    my ret
	}

	##### Function tcl.dict.addIterFailReference #####
	#
	# Type signature: value:DICTITER? -> void
	#
	# Increments the reference count inside a dictionary iteration
	# state, allowing for failure

	set f [$m local "tcl.dict.addIterFailReference" void<-DICTITER?]
	params value
	build {
	    my condBr [my maybe $value] $nothing $release
	label nothing:
	    my ret
	label release:
	    my Call tcl.dict.addIterReference [my unmaybe $value]
	    my ret
	}

	##### Function tcl.dict.iterStart #####
	#
	# Type signature: dict:STRING * ecvar:int* -> DICTITER?
	#
	# Starts iterating over a dictionary. The current state of the
	# iteration (assuming we don't get an error) is stored inside the
................................................................................
	    SetValueName $value "valuePtr"
	    set done [my alloc int "done"]
	    set search [my gep $iter 0 DICTFOR.search]
	    set code [$api Tcl_DictObjFirst $interp $dict \
			$search $key $value $done]
	    my condBr [my eq $code $0] $ok $failed
	label ok:
	    my storeInStruct $iter DICTFOR.dict $dict
	    my storeInStruct $iter DICTFOR.ref $0
	    my storeInStruct $iter DICTFOR.done [my neq [my load $done] $0]
	    my addReference(STRING) $dict


	    my Call tcl.dict.addIterReference $iter
	    my ret [my ok $iter]
	label failed:
	    $api ckfree $iter
	    my store $1 $ecvar
	    my ret [my fail DICTITER]
	}

	##### Function tcl.dict.iterNext #####
	#
	# Type signature: iter:DICTITER -> DICTITER
	#
	# Continues iterating over a dictionary. The current state of the
................................................................................
	    set key [my gep $iter 0 DICTFOR.key]
	    SetValueName $key "keyPtr"
	    set value [my gep $iter 0 DICTFOR.value]
	    SetValueName $value "valuePtr"
	    set done [my alloc int "done"]
	    set search [my gep $iter 0 DICTFOR.search]
	    $api Tcl_DictObjNext $search $key $value $done
	    my storeInStruct $iter DICTFOR.done [my neq [my load $done] $0]
	    my br $finished
	label finished:
	    my Call tcl.dict.addIterReference $iter
	    my ret $iter
	}

	##### Function tcl.dict.dropIterReference #####
................................................................................
	    set dictVal2 [$api Tcl_DuplicateObj $dictVal]
	    $api Tcl_AppendObjToObj $dictVal2 $value
	    set c [$api Tcl_DictObjPut {} $dict $key $dictVal2]
	    AddCallAttribute $c 3 nocapture
	    my br $done
	label done:
	    my addReference(STRING) $dict
	    my ret [my ok $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.incr #####
	#
	# Type signature: dict:STRING * key:STRING * value:INT
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    my br $done
	label done:
	    set resultValue [my phi [list $strVal $addVal] \
		    [list $set $doAdd] "value"]
	    # No failure mode at this point: we know we've got a dictionary.
	    set c [$api Tcl_DictObjPut {} $dict $key $resultValue]
	    my addReference(STRING) $dict
	    my ret [my ok $dict]
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	##### Function tcl.dict.lappend #####
	#
	# Type signature: dict:STRING * key:STRING * value:STRING
	#			* ecvar:int32* -> STRING?
	#
................................................................................
	    my condBr [my eq $result $0] $dupeUpdateOK $dupeNotOK
	label dupeUpdateOK:
	    set c [$api Tcl_DictObjPut {} $dict $key $dictVal]
	    AddCallAttribute $c 3 nocapture
	    my br $done
	label done:
	    my addReference(STRING) $dict
	    my ret [my ok $dict]
	label dupeNotOK:
	    my dropReference $dictVal
	    my br $notOK
	label notOK:
	    my Call obj.cleanup $dd
	    my store $1 $ecvar
	    my ret [my fail STRING]










































	}
    }
 
    # Builder:StringComparisonFunctions --
    #
    #	Generate the functions that implement the string comparators. Only
    #	called from StringFunctions method.
................................................................................
		    [my getInt32 $flags]]
	    my condBr [my nonnull $RE] $exec $err
	label exec "re.exec"
	    set match [$api Tcl_RegExpExecObj $interp $RE $stringObj $0 $0 $0]
	    my condBr [my ge $match $0] $done $err
	label done "re.done"
	    my store $0 $errVar
	    my ret [my ok [my gt $match $0]]
	label err "re.error"
	    my store $1 $errVar
	    my ret [my fail ZEROONE]
	}

    }
 
    # Builder:@apiFunctions --
    #
    #	Generate the quadcode operator implementations that require access to
    #	the Tcl API to work.
    #
................................................................................
    #	api -	The handle of the Tcl API object (currently an instance of the
    #		Thunk class).
    #
    # Results:
    #	None.

    method @apiFunctions {module api} {
	##### Function tcl.print.string #####
	##### Closure Build:printf #####
	##### Closure Build:fprintf #####
	#
	#	Print a formatted string.
	#
	# Parameters:
	#	channel (fprintf only) -
	#		Either "stdout" or "stderr" to select which channel to
	#		print to.
	#	str -	The Tcl string holding the format string.
	#	args -	The arguments to use in the format. These must be all
	#		LLVM values of the correct type.
	# Results:
	#	The reference count, as a LLVM value.

	set f [$module local tcl.print.string void<-int,Tcl_Obj*]
	my closure printf {str args} {
	    my Call tcl.print.string [Const [expr 1<<2]] \
		    [$api Tcl_ObjPrintf [my constString $str] {*}$args]
	}
	my closure fprintf {channel str args} {
	    set id [dict get {stdout 2 stderr 3} $channel]
	    my Call tcl.print.string [Const [expr {1<<$id}]] \
		    [$api Tcl_ObjPrintf [my constString $str] {*}$args]
	}
	params chanID str
	build {
	    set chan [$api Tcl_GetStdChannel $chanID]
	    $api Tcl_WriteObj $chan $str
	    $api Tcl_DecrRefCount $str
	    my ret
	}

	my StringifyFunctions $api
	my ReferenceFunctions $api
	my StringFunctions $api

	# Builder:MathException --
	#
	#	Generate one of the standard math exceptions that are produced
................................................................................

	set f [$module local "tcl.initExceptionSimple" void<-STRING,STRING]
	params message errorcode
	build {
	    nonnull $message $errorcode
	    set interp [$api tclInterp]
	    $api Tcl_SetObjResult $interp $message
	    set field [my gep $interp 0 Interp.returnOpts]
	    set ro [my load $field]
	    set newOpts [$api Tcl_NewObj]
	    set key [$api obj.constant "-errorcode"]
	    $api Tcl_DictObjPut {} $newOpts $key $errorcode
	    my store $newOpts $field
	    my addReference(STRING) $newOpts
	    my condBr [my nonnull $ro] $dropold $testForError
	label dropold "swap.dropOld"
	    my dropReference $ro
	    my br $testForError
	label testForError "test.for.error"
	    set field [my gep $interp 0 Interp.errorInfo]
	    set ei [my load $field]
	    my condBr [my nonnull $ei] $clearEI $setEC
	label clearEI "error.clearErrorInfo"
	    my dropReference $ei
	    my store [my null STRING] $field
	    my br $setEC
	label setEC "error.setErrorCode"
	    $api Tcl_SetObjErrorCode $interp $errorcode
	    set field [my gep $interp 0 Interp.flags]
	    my store [my or [my load $field] [Const 0x800]] $field
	    my ret
	}

	##### Function tcl.processReturn #####
	#
	# Type signature: result:STRING * code:int * level:int
................................................................................
	set f [$module local "tcl.processReturn" int<-STRING,int,int,STRING]
	params result code level returnOpts
	build {
	    nonnull $result
	    set interp [$api tclInterp]
	    $api Tcl_SetObjResult $interp $result
	    set valuePtr [my alloc STRING "valuePtr"]
	    set field [my gep $interp 0 Interp.returnOpts]
	    set ro [my load $field]
	    my condBr [my neq $ro $returnOpts] $swap $testForError
	label swap:
	    my condBr [my nonnull $ro] $swapdropold $swapinnew
	label swapdropold "swap.dropOld"
	    my dropReference $ro
	    my condBr [my nonnull $returnOpts] $swapinnew $totallyNew
................................................................................
	label swapinnew "swap.inNew"
	    my store $returnOpts $field
	    my addReference(STRING) $returnOpts
	    my br $testForError
	label testForError "test.for.error"
	    my condBr [my eq $code $1] $error $testForReturn
	label error:
	    set field [my gep $interp 0 Interp.errorInfo]
	    set ei [my load $field]
	    my condBr [my nonnull $ei] $clearEI $getEI
	label clearEI "error.clearErrorInfo"
	    my dropReference $ei
	    my store [my null STRING] $field
	    my br $getEI
	label getEI "error.getErrorInfo"
................................................................................
	label installEI "error.installErrorInfo"
	    set infoLen [my alloc int "infoLen"]
	    $api Tcl_GetStringFromObj $value $infoLen
	    my condBr [my neq [my load $infoLen] $0] $installEI2 $getES
	label installEI2 "error.setErrorInfo"
	    my store $value $field
	    my addReference(STRING) $value
	    set field [my gep $interp 0 Interp.flags]
	    my store [my or [my load $field] [Const 4]] $field
	    my br $getES
	label getES "error.getErrorStack"
	    my condBr [my nonnull $returnOpts] $testES $getEC
	label testES "error.testHaveErrorStack"
	    $api Tcl_DictObjGet {} $returnOpts \
		[$api obj.constant "-errorstack"] $valuePtr
	    set value [my load $valuePtr "errorStack"]
	    my condBr [my nonnull $value] $installES $getEC
	label installES "error.installErrorStack"
	    set field [my gep $interp 0 Interp.errorStack]
	    my condBr [my shared [my load $field]] $dedupES $getESElems
	label dedupES "error.deduplicateErrorStack"
	    set oldobj [my load $field]
	    set newobj [$api Tcl_DuplicateObj $oldobj]
	    my dropReference $oldobj
	    my addReference(STRING) $newobj
	    my store $newobj $field
................................................................................
	    set objvPtr [my alloc STRING*]
	    my condBr [my neq $0 \
		[$api Tcl_ListObjGetElements $interp $value $objcPtr $objvPtr]]\
		$notList $setES
	label notList "error.getErrorStackElements.notList"
	    my ret $1
	label setES "error.setErrorStack"
	    my store $0 [my gep $interp 0 Interp.resetErrorStack]
	    set lenPtr [my alloc int]
	    set es [my load $field]
	    $api Tcl_ListObjLength $interp $es $lenPtr
	    $api Tcl_ListObjReplace $interp \
		$es $0 [my load $lenPtr "len"] \
		[my load $objcPtr "objc"] [my load $objvPtr "objv"]
	    my br $getEC
................................................................................
		[$api obj.constant "-errorcode"] $valuePtr
	    set value [my load $valuePtr "errorCode"]
	    my condBr [my nonnull $value] $installEC $installNone
	label installEC "error.installErrorCode"
	    $api Tcl_SetObjErrorCode $interp $value
	    my br $getEL
	label installNone "error.installNONE"
	    $api Tcl_SetErrorCode $interp [my constString NONE] {}
	    my br $getEL
	label getEL "error.getErrorLine"
	    my condBr [my nonnull $returnOpts] $testEL $testForReturn
	label testEL "error.testHaveErrorInfo"
	    $api Tcl_DictObjGet {} $returnOpts \
		[$api obj.constant "-errorline"] $valuePtr
	    set value [my load $valuePtr "errorLine"]
	    my condBr [my nonnull $value] $installEL $testForReturn
	label installEL "error.installErrorLine"
	    $api Tcl_GetIntFromObj {} $value \
		[my gep $interp 0 Interp.errorLine]
	    my br $testForReturn
	label testForReturn "test.for.return"
	    my condBr [my neq $level $0] $processReturn $retestForError
	label processReturn "return.process"
	    my storeInStruct $interp Interp.returnLevel $level
	    my storeInStruct $interp Interp.returnCode $code
	    my ret [Const 2];	# TCL_RETURN
	label retestForError "test.for.error"
	    my condBr [my eq $code $1] $addFlag $done
	label addFlag "error.addFlag"
	    set field [my gep $interp 0 Interp.flags]
	    my store [my or [my load $field] [Const 0x800]] $field
	    my br $done
	label done:
	    my ret $code
	}

	##### Function tcl.handleExceptionResult #####
	#
	# Type signature: code:int * result:STRING -> bool
	#
	# Part of the machinery of _conditionally_ firing an exception.
	# Increments the reference count of the result value IFF the result is
	# a TCL_OK (other cases don't have a result at this point as they've
	# initialised an exception).

	set f [$m local "tcl.handleExceptionResult" bool<-int,STRING]
	params code result
	build {
	    set ok [my eq $code $0 "ok"]
	    my condBr $ok $addRef $done
	label addRef:
	    my addReference(STRING) $result
	    my br $done
	label done:
	    my ret $ok
	}

	##### Function tcl.procedure.return #####
	#
	# Type signature: code:INT * procName:STRING * ecvar:int32* -> FAIL
	#
	# Handles the transforms on a result when a procedure returns. See
	# InterpProcNR2 in tclProc.c for what is going on; this is the part
	# commencing at the 'process' label.

	set f [$m local "tcl.procedure.return" FAIL<-INT,STRING,int32*]
	params code procName ecvar
	build {
	    nonnull $procName $ecvar
	    set interp [$api tclInterp]
	    set code [my getInt32 $code]
	    my condBr [my eq $code [Const 2]] $handleReturn $test2
	label test2:
	    my condBr [my eq $code [Const 3]] $handleBreak $test3
	label test3:
	    my condBr [my eq $code [Const 4]] $handleContinue $test4
	label test4:
	    my condBr [my eq $code [Const 1]] $handleError $done
	label handleError "handle.error"
	    set limitVar [my alloc int]
	    set name [$api Tcl_GetStringFromObj $procName $limitVar]
	    SetValueName $name "name"
	    set limit [Const 60]
	    set nameLen [my load $limitVar "name.len"]
	    set overflow [my gt $nameLen $limit]
	    $api Tcl_AppendObjToErrorInfo $interp [$api Tcl_ObjPrintf \
		    [my constString "\n    (procedure \"%.*s%s\" line %d)"] \
		    [my select $overflow $limit $nameLen] $name \
		    [my select $overflow [my constString "..."] \
			    [my constString ""]] \
		    [my dereference $interp 0 Interp.errorLine]]
	    my br $done
	label handleReturn "handle.return"
	    set newcode [$api TclUpdateReturnInfo $interp]
	    my store $newcode $ecvar
	    my ret $newcode
	label handleBreak "handle.leaked.break"
	    $api Tcl_SetObjResult $interp [$api Tcl_ObjPrintf \
		    [my constString "invoked \"%s\" outside of a loop"] \
		    [my constString "break"]]
	    $api Tcl_SetObjErrorCode $interp \
		[$api obj.constant {TCL RESULT UNEXPECTED}]
	    my store [Const 1] $ecvar
	    my ret [Const 1]
	label handleContinue "handle.leaked.continue"
	    $api Tcl_SetObjResult $interp [$api Tcl_ObjPrintf \
		    [my constString "invoked \"%s\" outside of a loop"] \
		    [my constString "continue"]]
	    $api Tcl_SetObjErrorCode $interp \
		[$api obj.constant {TCL RESULT UNEXPECTED}]
	    my store [Const 1] $ecvar
	    my ret [Const 1]
	label done:
	    my store $code $ecvar
	    my ret $code
	}

	##### Function tcl.logCommandInfo #####
	#
	# Type signature: code:int * length:int * command:char*
	#			* ellipsis:char* -> void
	#
	# Builds the current entry in the errorInfo trace if the code is
	# TCL_ERROR. Note that most of the arguments to this function are
	# expected to be values that our caller will compute at compile time.

	set f [$m local "tcl.logCommandInfo" void<-int,int,char*,char*]
	params code length command ellipsis
	build {
	    nonnull $command $ellipsis
	    set ERR_ALREADY_LOGGED [Const 4]

	    set interp [$api tclInterp]
	    set flagVar [my gep $interp 0 Interp.flags]
	    set flags [my load $flagVar "flags"]
	    my condBr [my eq $code [Const 1]] $checkForLog $done
	label checkForLog "check.for.log.error"
	    my condBr [my eq [my and $flags $ERR_ALREADY_LOGGED] [Const 0]] \
		$logError $done
	label logError "log.error"
	    set initText [my select [my nonnull \
		    [my dereference $interp 0 Interp.errorInfo]] \
		    [my constString "invoked from within"] \
		    [my constString "while executing"]]
	    $api Tcl_AppendObjToErrorInfo $interp [
		$api Tcl_ObjPrintf [my constString "\n    %s\n\"%.*s%s\""] \
		    $initText $length $command $ellipsis]
	    # TODO: update the errorStack as well...
	    # $api Tcl_LogCommandInfo $interp {} {} [Const 0]
	    my br $done
	label done:
	    my store [my and $flags [my not $ERR_ALREADY_LOGGED]] $flagVar
	    my ret
	}

	##### Function tcl.setErrorLine #####
	#
	# Type signature: test:bool * code:int * line:int * length:int
	#			* command:char* * ellipsis:char* -> void
	#
	# Sets the current errorLine if the test is true and builds the
	# current entry in the errorInfo trace if necessary. Note that most of
	# the arguments to this function are expected to be values that our
	# caller will compute at compile time.

	set f [$m local "tcl.setErrorLine" void<-bool,int,int,int,char*,char*]
	params test code line length command ellipsis
	build {
	    nonnull $command $ellipsis
	    my condBr $test $setLine $done
	label setLine "set.error.line"
	    set interp [$api tclInterp]
	    my store $line [my gep $interp 0 Interp.errorLine]
	    my Call tcl.logCommandInfo $code $length $command $ellipsis
	    my br $done
	label done:
	    my ret
	}

	##### Function tcl.booleanTest #####
	#
	# Type signature: objPtr:Tcl_Obj* -> ZEROONE
	#
	# Part of quadcode implementation ('isBoolean')
	#
	# Returns whether the string 'objPtr' is a boolean value.

	set f [$m local "tcl.booleanTest" ZEROONE<-Tcl_Obj*]
	params objPtr
	build {
	    nonnull $objPtr
	    set NULL [my null Interp*]
	    set code [my setFromAny [$api tclBooleanType] $NULL $objPtr]
	    my ret [my eq $code $0]
	}

	##### Function tcl.invoke.command #####
	#
	# Type signature: objc:int * objv:STRING* * ecvar:int* -> STRING?
	#
	# Calls the Tcl interpreter to invoke a Tcl command, and packs the
	# result into a STRING FAIL.

	set f [$module local "tcl.invoke.command" \
		   STRING?<-int,STRING*,CALLFRAME,int*]
	params objc objv frame ecvar
	build {
	    noalias $objv $frame $ecvar
	    nonnull $objv $ecvar
	    set interp [$api tclInterp]
	    my condBr [my nonnull $frame] $frameInvoke $stdInvoke
	label stdInvoke "invoke.standard"
	    set code1 [$api Tcl_EvalObjv $interp $objc $objv $0]
	    my condBr [my eq $code1 $0] $ok $fail
	label frameInvoke "invoke.with.callframe"
	    set vfp [my gep $interp 0 Interp.varFramePtr]
	    set vf [my load $vfp]
	    my store $frame $vfp
	    set code2 [$api Tcl_EvalObjv $interp $objc $objv $0]
	    my store $vf $vfp
	    my condBr [my eq $code2 $0] $ok $fail
	label ok:
	    set result [$api Tcl_GetObjResult $interp]
	    my addReference(STRING) $result
	    my ret [my ok $result]
	label fail:
	    set code [my phi [list $code1 $code2] [list $stdInvoke $frameInvoke] "code"]
	    my store $code $ecvar
	    my ret [my fail STRING $code]
	}

	##### Function tcl.invoke.expanded #####
	#
	# Type signature: objc:int * objv:STRING* * flags:bool* * ecvar:int*
	#			-> STRING?
	#
	# Calls the Tcl interpreter to invoke a Tcl command, first expanding
	# the arguments indicate by the flags array (which will have objc
	# elements in it), and packs the result into a STRING FAIL.

	set f [$module local "tcl.invoke.expanded" \
		   STRING?<-int,STRING*,bool*,int*]
	params objc objv flags ecvar
	build {
	    noalias $objv $flags $ecvar
	    nonnull $objv $flags $ecvar
	    set tclobjSize [my cast(int) [my sizeof STRING]]
	    set interp [$api tclInterp]
	    set iPtr [my alloc int "i"]
	    set jPtr [my alloc int "j"]
	    set lenPtr [my alloc int "len"]
	    set objcPtr [my alloc int "objcPtr"]
	    set objvPtr [my alloc STRING* "objvPtr"]
	    my store $0 $iPtr
	    my store $0 $lenPtr
	    my br $findLenTest
	label findLenTest "test.findLength"
	    set i [my load $iPtr "i"]
	    my condBr [my lt $i $objc] $findLenBody $setupExpansion
	label findLenBody "body.findLength"
	    set flag [my load [my getelementptr $flags $i] "flag"]
	    set len [my load $lenPtr "len"]
	    my condBr $flag $findLenExpand $findLenSimple
	label findLenExpand "body.findLength.expand"
	    set obj [my load [my getelementptr $objv $i] "objPtr"]
	    $api Tcl_ListObjLength {} $obj $objcPtr
	    set lenstep1 [my load $objcPtr "lenStep"]
	    my br $findLenNext
	label findLenSimple "body.findLength.simple"
	    set lenstep2 $1
	    my br $findLenNext
	label findLenNext "next.findLength"
	    set lenstep [my phi [list $lenstep1 $lenstep2] \
			     [list $findLenExpand $findLenSimple] "lenStep"]
	    my store [my add $len $lenstep] $lenPtr
	    my store [my add $i $1] $iPtr
	    my br $findLenTest
	label setupExpansion "setup.expansion"
	    set len [my load $lenPtr "len"]
	    # Do not allocate on stack; might be large
	    set ary [$api ckalloc [my mult $len $tclobjSize] STRING "array"]
	    my store $0 $iPtr
	    my store $0 $jPtr
	    my br $expansionTest
	label expansionTest "test.expansion"
	    set i [my load $iPtr "i"]
	    my condBr [my lt $i $objc] $expansionBody $invoke
	label expansionBody "body.expansion"
	    set j [my load $jPtr "j"]
	    set flag [my load [my getelementptr $flags $i] "flag"]
	    set obj [my load [my getelementptr $objv $i] "objPtr"]
	    set target [my getelementptr $ary $j]
	    my condBr $flag $expansionExpand $expansionSimple
	label expansionExpand "body.expansion.expand"
	    $api Tcl_ListObjGetElements {} $obj $objcPtr $objvPtr
	    set srclen [my load $objcPtr "objc"]
	    set source [my load $objvPtr "objv"]
	    my memcpy $target $source [my mult $srclen $tclobjSize]
	    my store [my add $j $srclen] $jPtr
	    my br $expansionNext
	label expansionSimple "body.expansion.simple"
	    my store $obj $target
	    my store [my add $j $1] $jPtr
	    my br $expansionNext
	label expansionNext "next.expansion"
	    my store [my add $i $1] $iPtr
	    my br $expansionTest
	label invoke:
	    set code [$api Tcl_EvalObjv $interp $len $ary $0]
	    $api ckfree $ary
	    my condBr [my eq $code $0] $ok $fail
	label ok:
	    set result [$api Tcl_GetObjResult $interp]
	    my addReference(STRING) $result
	    my ret [my ok $result]
	label fail:
	    my store $code $ecvar
	    my ret [my fail STRING $code]
	}

	##### Function tcl.existsOrError #####
	#
	# Type signature: exists:int1 * message:STRING * ecvar:int* -> int1
	#
	# Conditionally generates an error about a non-existing variable.
................................................................................
	    noalias $ecvar
	    nonnull $value $ecvar
	    set interp [$api tclInterp]
	    set bvar [my alloc int]
	    set code [$api Tcl_GetBooleanFromObj $interp $value $bvar]
	    my condBr [my eq $code [Const 0]] $ok $fail
	label fail:
	    my store [Const 1] $ecvar
	    my ret [my fail ZEROONE]
	label ok:
	    my ret [my ok [my neq [my load $bvar "bool"] [Const 1]]]
	}

	my VariableHelperFunctions $api
	my @variableFunctions $api
	my @numericConverterFunctions $api

	##### Function: tcl.resolveCmd #####
	#
	# Type signature: cmdName:STRING -> STRING
	#
	# Quadcode implementation('resolveCmd')
	#
	# Returns either the resolved name of the command or an empty
	# string if the command cannot be resolved.

	set f [$m local "tcl.resolveCmd" STRING<-STRING]
	params cmdName
	build {
	    nonnull $cmdName
	    set interp [$api tclInterp]
	    set result [$api Tcl_NewObj]
	    set cmdPtr [$api Tcl_GetCommandFromObj $interp $cmdName]
	    my condBr [my nonnull $cmdPtr] $resolved $notResolved
	  label resolved:
	    $api Tcl_GetCommandFullName $interp $cmdPtr $result
	    my br $notResolved
	  label notResolved:
	    my addReference(STRING) $result
	    my ret $result
	}

	##### Function: tcl.originCmd #####
	#
	# Type signature: cmdName:STRING ecvar:int32* -> STRING
	#
	# Quadcode implementation('resolveCmd')
	#
	# Returns either the resolved name of the command or an empty
	# string if the command cannot be resolved.

	set f [$m local "tcl.originCmd" STRING?<-STRING,int*]
	params cmdName ecvar
	build {
	    nonnull $cmdName $ecvar
	    noalias $ecvar
	    set interp [$api tclInterp]
	    set result [$api Tcl_NewObj]
	    set cmdPtr [$api Tcl_GetCommandFromObj $interp $cmdName]
	    my condBr [my nonnull $cmdPtr] $resolved $notResolved
	  label resolved:
	    set origCmdPtr [$api TclGetOriginalCommand $cmdPtr]
	    my condBr [my nonnull $origCmdPtr] $aliased $notAliased
	  label aliased:
	    my br $done
	  label notAliased:
	    my br $done
	  label done:
	    set finalCmdPtr [my phi [list $origCmdPtr $cmdPtr] \
				 [list $aliased $notAliased]]
	    $api Tcl_GetCommandFullName $interp $finalCmdPtr $result
	    my addReference(STRING) $result
	    my ret [my ok $result]
	  label notResolved:
	    my dropReference(STRING) $result
	    $api Tcl_SetObjResult $interp \
		[$api Tcl_ObjPrintf \
		     [my constString "invalid command name \"%s\""] \
		     [$api Tcl_GetString $cmdName]]
	    $api Tcl_SetErrorCode $interp \
		[my constString TCL] [my constString LOOKUP] \
		[my constString COMMAND] [$api Tcl_GetString $cmdName] {}
	    my store $1 $ecvar
	    my ret [my fail STRING]
	}

	my CallFrameFunctions $api
    }

    export @apiFunctions
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/struct.tcl.

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
...
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
...
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
...
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
...
410
411
412
413
414
415
416
417

418

419
420

421
422
423
424
425
426
427
...
529
530
531
532
533
534
535




































536
537
538
539
540
541
542
...
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
....
1034
1035
1036
1037
1038
1039
1040




1041
1042
1043
1044
1045
1046
1047
....
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
....
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
....
1241
1242
1243
1244
1245
1246
1247

1248
1249
1250
1251
1252



1253
1254
1255
1256
1257
1258
1259
....
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
....
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
....
1647
1648
1649
1650
1651
1652
1653

1654


1655
1656
1657
1658
1659
1660
1661
....
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
....
1730
1731
1732
1733
1734
1735
1736

1737
1738
1739
1740
1741
1742
1743
....
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
....
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
....
1916
1917
1918
1919
1920
1921
1922


1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
....
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
....
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
....
2065
2066
2067
2068
2069
2070
2071



























2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089



2090

2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111








2112
2113
2114
2115
2116
2117
2118
....
2133
2134
2135
2136
2137
2138
2139

2140
2141
2142










2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
....
2268
2269
2270
2271
2272
2273
2274

2275
#		The execution engine associated with the module. Only
#		available after one of the engine-construction methods (e.g.,
#		'mcjit', 'interpreter') has been called.

oo::class create Module {
    superclass llvmEntity
    variable module counter funcs builder myname globals externs engine
    variable dbty mainNS thunkNS dbbuild

    constructor {name {filename "/dev/null"}} {
	next

	set myname $name
	set module [ModuleCreateWithName $name]
	SetTarget $module [GetHostTriple]

	# Module:debug --
	#
	#	Delegated access to the debugging information issuing
	#	interface of this module.
	#
	# Parameters:
	#	See the Debugging class.
	#
	# Results:
	#	See the Debugging class.

	set dbbuild [Debugging new [self] $filename]
	oo::objdefine [self] forward debug $dbbuild


	set funcs {}
	set globals {}
	set externs {}
	set support [my debug namespace tcl.support]
	my debug scope $support
	my debug scope [my debug namespace types] {
	    my InitTclTypes
	    my InitDebugTypes
	}
	[my builder] @supportFunctions [self]
	my debug scope [my debug main]
	set mainNS [my debug namespace main]
	set thunkNS [my debug namespace thunks]
	my debug scope [my debug namespace tcl.library]



	my verify
    }

    destructor {
	if 0 {
	    # BUG: Destroying the Debugging instance makes LLVM fail an
	    # assertion. Why?!















	    $dbbuild destroy





	}
    }

    # Module(self):initialiseLLVM --
    #
    #	Make llvmtcl ready to generate code. This only needs to be done once;
    #	subsequent calls will have no effect.
................................................................................
    #
    # Results:
    #	A TclOO object that encapsulates the function.

    method function.create {name type} {
	set ft [Type $type]
	set int $dbty([Type void*])
	set dbtype [my debug functionType [my debugType [GetReturnType $ft]] \
			{*}[lmap t [GetParamTypes $ft] {my debugType $t}]]
	set objname f[incr counter]([string map {::: || :: |} $name])
	set f [Function create $objname [self] $name $ft]
	switch -glob -- $name {
	    ::*		 {set scope $mainNS}
	    cmd.thunk::* {set scope $thunkNS}
	    default	 {set scope [my debug scope]}
	}
	my debug scope $scope {
	    set fn [my debug function [$f ref] $name $dbtype]
	}
	set [info object namespace $f]::dbref $fn
	dict set funcs $name $f
	return $f
    }

    # Module:local --
    #
    #	Create an instance of the Function class that represents a function
................................................................................
    #	args -	Extra attributes to apply to the function.
    #
    # Results:
    #	A TclOO object that encapsulates the function.

    method local {name signature args} {
	set oldfile [my debug file]
	my debug file [file normalize [dict get [info frame -1] file]]
	set f [my function.create $name [Type func{$signature}]]
	if {"noinline" ni $args} {
	    lappend args alwaysinline
	}
	$f private
	$f attribute {*}$args
	upvar 1 $name ref
................................................................................
    #
    # Results:
    #	A string in the format of LLVM IR.

    method dump {} {
	DumpModule $module
    }
























    # Module:verify --
    #
    #	Check the module to see if the code is actually valid.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	Empty string, or throws a Tcl error describing the problem.

    method verify {} {

	lassign [VerifyModule $module LLVMReturnStatusAction] rt msg
	if {$rt} {
	    return -code error [string trim $msg]
	}
    }

    # Module:optimize --
................................................................................
    #	None.

    method optimize {{level 3}} {
	set level [expr {max(0, min(3, int($level)))}]

	set bld [PassManagerBuilderCreate]
	set pm [CreatePassManager]
	set td [CreateTargetData ""]

	try {

	    SetDataLayout $module [CopyStringRepOfTargetData $td]
	    AddTargetData $td $pm

	    PassManagerBuilderSetOptLevel $bld $level
	    PassManagerBuilderSetDisableUnrollLoops $bld [expr {!$level}]
	    if {$level > 1} {
		PassManagerBuilderUseInlinerWithThreshold $bld \
		    [expr {$level > 2 ? 275 : 225 }]
	    }
	    PassManagerBuilderPopulateModulePassManager $bld $pm
................................................................................
	}
	lassign [CreateJITCompilerForModule $module $optimisationLevel] rt ee msg
	if {$rt} {
	    return -code error $msg
	}
	set engine $ee
    }





































    # Module:engine (property) --
    #
    #	Get the execution engine for the module.

    method engine {} {
	if {![info exists engine]} {
................................................................................
    # Results:
    #	None.

    method dispose {} {
	DisposeModule $module
	my destroy
    }





































    # Module:InitTclTypes --
    #
    #	Construct instances of the types used in the Tcl interface. These are
    #	stored as LLVM type references in variables of an instance of this
    #	class.

    #
    # Parameters:
    #	None.
    #
    # Results:
    #	None.

    method InitTclTypes {} {
	# Define the types we're using

	set fptype [Type func{int<-int}*]

	# Types where we don't care about the contents
	Type "named{ResolverScheme,int}"
	Type "named{Trace,int}"
	Type "named{ExecEnv,int}"
	Type "named{LimitHandler,int}"
	Type "named{TimerToken,int}"
	Type "named{OOFoundation,int}"
	Type "named{AsyncHandler,int}"
	Type "named{ThreadId,int}"
	Type "named{AllocCache,int}"
	Type "named{NamespacePathEntry,int}"
	Type "named{CompiledLocal,int}"
	# Type of contents of Tcl_RegExp doesn't matter; private to RE engine
	Type "named{Tcl_RegExp,int}"
	Type "named{mp_int,int,int,int,void*}"

	# WARNING: int type may need to be larger on some platforms!
	Type NUMERIC; # Make sure we get this early, just in case
	Type "named{Tcl_ObjType,
		name:char*,
		freeIntRepProc:$fptype,
		dupIntRepProc:$fptype,
		updateStringProc:$fptype,
		setFromAnyProc:$fptype}"
	Type "named{Tcl_Obj,
		refCount:int,
		bytes:char*,
		length:int,
		typePtr:Tcl_ObjType*,
		internalRep:struct{void*,void*}}"

	# Stub tables
	Type "named{TclIntStubs,
		int,
		void*,
		array{$fptype,252}}"
	Type "named{TclStubs,
		int,
		struct{void*,TclIntStubs*,void*}*,
		array{$fptype,631}}"

	Type "named{Tcl_Time,
		sec:long,
		usec:long}"
	Type "named{Tcl_HashKeyType,
		version:int,
		flags:int,
		hashKeyProc:$fptype,
		allocEntryProc:$fptype,
		freeEntryProc:$fptype}"
	Type "named{Tcl_HashTable,
		buckets:void*,
		staticBuckets:array{void*,4},
		numBuckets:int,
		numEntries:int,
		rebuildSize:int,
		downShift:int,
		mask:int,
		keyType:int,
		findProc:$fptype,
		createProc:$fptype,
		typePtr:Tcl_HashKeyType*}"
	Type "named{Tcl_HashEntry,
		nextPtr:Tcl_HashEntry*,
		tablePtr:Tcl_HashTable*,
		hash:void*,
		clientData:void*,
		key:void*}"
	Type "named{Tcl_HashSearch,
		tablePtr:Tcl_HashTable*,
		nextIndex:int,
		nextEntryPtr:Tcl_HashEntry*}"
	Type "named{LiteralEntry,
		nextPtr:LiteralEntry*,
		objPtr:Tcl_Obj*,
		refCount:int,
		nsPtr:void*}"
	Type "named{LiteralTable,
		buckets:LiteralEntry**,
		staticBuckets:array{LiteralEntry*,4},
		numBuckets:int,
		numEntries:int,
		rebuildSize:int,
		mask:int}"

	Type "named{TclVarHashTable,
		table:Tcl_HashTable,
		nsPtr:void*}"
	Type "named{Var,
		flags:int,
		value:Tcl_Obj*}"
	Type "named{VarInHash,
		var:Var,
		refCount:int,
		entry:Tcl_HashEntry}"
	Type "named{ArraySearch,
		name:Tcl_Obj*,
		id:int,
		varPtr:Var*,
		search:Tcl_HashSearch,
		nextEntry:Tcl_HashEntry*,
		nextPtr:ArraySearch*}"
	Type "named{VarTrace,
		traceProc:void*,
		clientData:void*,
		flags:int,
		nextPtr:VarTrace*}"
	Type "named{ActiveVarTrace,
		varPtr:Var*,
		nextPtr:ActiveVarTrace*,
		nextTracePtr:VarTrace*}"
	Type "named{Namespace,
		name:char*,
		fullName:char*,
		clientData:void*,
		deleteProc:$fptype,
		parentPtr:void*,
		childTable:Tcl_HashTable,
		nsId:long,
		interp:void*,
		flags:int,
		activationCount:int,
		refCount:int,
		cmdTable:Tcl_HashTable,
		varTable:TclVarHashTable,
		exportArrayPtr:char**,
		numExportPatterns:int,
		maxExportPatterns:int,
		cmdRefEpoch:int,
		resolverEpoch:int,
		cmdResProc:$fptype,
		varResProc:$fptype,
		compiledVarResProc:$fptype,
		exportLookupEpoch:int,
		ensembles:void*,
		unknownHandlerPtr:Tcl_Obj*,
		commandPathLength:int,
		commandPathArray:NamespacePathEntry*,
		commandPathSourceList:NamespacePathEntry*,
		earlyDeleteProc:$fptype}"
	Type "named{Command,
		hPtr:Tcl_HashEntry*,
		nsPtr:Namespace*,
		refCount:int,
		cmdEpoch:int,
		compileProc:$fptype,
		objProc:$fptype,
		objClientData:void*,
		proc:$fptype,
		clientData:void*,
		deleteProc:$fptype,
		deleteData:void*,
		flags:int,
		importRefPtr:void*,
		tracePtr:Trace*,
		nreProc:$fptype}"
	Type "named{Proc,
		iPtr:void*,
		refCount:int,
		cmdPtr:Command*,
		bodyPtr:Tcl_Obj*,
		numArgs:int,
		numCompiledLocals:int,
		firstLocalPtr:CompiledLocal*,
		lastLocalPtr:CompiledLocal*}"
	Type "named{CallFrame,
		nsPtr:Namespace*,
		isProcCallFrame:int,
		objc:int,
		objv:Tcl_Obj**,
		callerPtr:CallFrame*,
		callerVarPtr:CallFrame*,
		level:int,
		procPtr:Proc*,
		varTablePtr:TclVarHashTable*,
		numCompiledLocals:int,
		compiledLocals:Var*,
		clientData:void*,
		localCachePtr:named{LocalCache,int,int,Tcl_Obj*}*,
		tailcallPtr:Tcl_Obj*}"
	Type "named{CmdFrame,
		type:int,
		level:int,
		line:int*,
		nline:int,
		framePtr:CallFrame*,
		nextPtr:CmdFrame*,
		data:struct{void*,void*},
		cmdObj:Tcl_Obj*,
		cmd:char*,
		len:int,
		litarg:void*}"

	Type "named{NRE_callback,
		procPtr:func{int<-void**,void*,int}*,
		data:array{void*,4},
		nextPtr:NRE_callback*}"
	Type "named{ContLineLoc,
		num:int,
		loc:array{int,1}}"

	set TCL_RESULT_SIZE 201
	Type "named{Tcl_Interp,
		result:char*,
		freeProc:func{void<-char*}*,
		errorLine:int,
		stubTable:TclStubs*,
		handle:void**,
		globalNsPtr:Namespace*,
		hiddenCmdTablePtr:Tcl_HashTable*,
		interpInfo:void*,
		extra:Tcl_HashTable,
		numLevels:int,
		maxNestingDepth:int,
		framePtr:CallFrame*,
		varFramePtr:CallFrame*,
		activeVarTracePtr:ActiveVarTrace*,
		returnCode:int,
		rootFramePtr:CallFrame*,
		lookupNsPtr:Namespace*,
		appendResult:char*,
		appendAvl:int,
		appendUsed:int,
		packageTable:Tcl_HashTable,
		packageUnknown:char*,
		cmdCount:int,
		evalFlags:int,
		termOffset:int,
		literalTable:LiteralTable,
		compileEpoch:int,
		compiledProcPtr:Proc*,
		resolverPtr:ResolverScheme*,
		scriptFile:Tcl_Obj*,
		flags:int,
		randSeed:long,
		tracePtr:Trace*,
		assocData:Tcl_HashTable*,
		execEnvPtr:ExecEnv*,
		emptyObjPtr:Tcl_Obj*,
		resultSpace:array{char,$TCL_RESULT_SIZE},
		objResultPtr:Tcl_Obj*,
		threadId:ThreadId*,
		activeCmdTracePtr:Trace*,
		activeInterpTracePtr:Trace*,
		tracesForbiddingInline:int,
		returnOpts:Tcl_Obj*,
		errorInfo:Tcl_Obj*,
		eiVar:Tcl_Obj*,
		errorCode:Tcl_Obj*,
		ecVar:Tcl_Obj*,
		returnLevel:int,
		limit:named{LimitInfo,
			active:int,
			granularityTicker:int,
			exceeded:int,
			cmdCount:int,
			cmdHandlers:LimitHandler*,
			cmdGranularity:int,
			time:Tcl_Time,
			timeHandlers:LimitHandler*,
			timeGranularity:int,
			timeEvent:TimerToken*,
			callbacks:Tcl_HashTable},
		ensembleRewrite:named{EnsembleInfo,
			sourceObjs:Tcl_Obj**,
			numRemovedObjs:int,
			numInsertedObjs:int},
		chanMsg:Tcl_Obj*,
		cmdFramePtr:CmdFrame*,
		invokeCmdFramePtr:CmdFrame*,
		invokeWord:int,
		linePBodyPtr:Tcl_HashTable*,
		lineBCPtr:Tcl_HashTable*,
		lineLABCPtr:Tcl_HashTable*,
		lineLAPtr:Tcl_HashTable*,
		scriptCLLocPtr:ContLineLoc*,
		packagePrefer:int,
		varTraces:Tcl_HashTable,
		varSearches:Tcl_HashTable,
		allocCache:AllocCache*,
		pendingObjDataPtr:void*,
		asyncReadyPtr:int*,
		objectFoundation:OOFoundation*,
		deferredCallbacks:NRE_callback*,
		asyncCancel:AsyncHandler*,
		asyncCancelMsg:Tcl_Obj*,
		errorStack:Tcl_Obj*,
		upLiteral:Tcl_Obj*,
		callLiteral:Tcl_Obj*,
		innerLiteral:Tcl_Obj*,
		innerContext:Tcl_Obj*,
		resetErrorStack:int}"

	Type "named{TclList,
		refCount:int,
		maxElemCount:int,
		elemCount:int,
		canonicalFlag:int,
		elements:Tcl_Obj*}"

	Type "named{ChainEntry,
		entry:Tcl_HashEntry,
		prevPtr:ChainEntry*,
		nextPtr:ChainEntry*}"
	Type "named{Dict,
		table:Tcl_HashTable,
		entryChainHead:ChainEntry*,
		entryChainTail:ChainEntry*,
		epoch:int,
		refcount:int,
		chain:Tcl_Obj*}"
	Type "named{Tcl_DictSearch,
		next:ChainEntry*,
		epoch:int,
		dictionaryPtr:Dict*}"

	return
    }

    # Module:InitDebugTypes --
    #
    #	Construct debug delegates for the types used in the Tcl interface so
    #	that the Module:debugType method will work.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	None.

    method InitDebugTypes {} {
	proc DBTY {var <- type dbtype args} {
	    upvar 1 $var v dbty dbty
	    if {[catch {
		set t [uplevel 1 [list Type $type]]
		set con ${dbtype}Type
		set v [uplevel 1 [list my debug $con {*}$args]]
		if {![info exists dbty($t)]} {
		    set dbty($t) $v
		}
	    } msg]} {
		uplevel 1 [list my Warn "failed to build type $type: $msg"]
	    }
	}


	DBTY void <- void   void "void"
	DBTY ptr  <- void*  pointer "ClientData" $void
	DBTY chr  <- char   int "char" 8
	DBTY chrs <- char*  pointer "char*" $chr
	DBTY i16  <- int16  int "Tcl_UniChar" 16
	DBTY ustr <- int16* pointer "Tcl_UniString" $i16
	DBTY i32  <- int    int "int" 32
	DBTY i32* <- int*   pointer "int*" $i32
	DBTY i64  <- int64  int "int64" 64
	DBTY bool <- bool   int "bool" 1

	DBTY dbl  <- double float "double" 64
	DBTY i32? <- int?   struct "optional.i32" $bool $i32
	DBTY i64? <- int64? struct "optional.i64" $bool $i64

	DBTY lenunistr <- struct{int,int16*} struct "len.ustr" $i32 $ustr
	DBTY lenbytes  <- struct{int,int8*} struct "len.bytes" $i32 $chrs




	DBTY OTBase  <- Tcl_ObjType struct "Tcl_ObjType" \
	    $ptr $ptr $ptr $ptr $ptr
	DBTY ObjType <- Tcl_ObjType* pointer "Tcl_ObjType" $OTBase
	DBTY ObjBase <- Tcl_Obj struct "Tcl_Obj" \
	    $i32 $chrs $i32 $ObjType [my debug structType "" $ptr $ptr]


























































































































































































































































































































































































































































































































































































































































































































































































































	DBTY Obj     <- Tcl_Obj* pointer "Tcl_Obj*" $ObjBase
	DBTY ObjRef  <- Tcl_Obj** pointer "Tcl_Obj**" $Obj

	DBTY Interp <- Tcl_Interp* pointer "Tcl_Interp" \
	    [my debug structType "Interp"]
	set hash [my debug structType "Tcl_HashTable"]
	DBTY Hash <- Tcl_HashTable* pointer "Tcl_HashTable*" $hash



	set hEnt [my debug structType "Tcl_HashEntry" $ptr]
	DBTY HENT <- Tcl_HashEntry* pointer "Tcl_HashEntry" $hEnt
	DBTY VarHash <- TclVarHashTable* pointer "TclVarHashTable*" \
	    [my debug structType "TclVarHashTable"]
	set hSrc [my debug structType "Tcl_HashSearch" $ptr]
	DBTY HSRC <- Tcl_HashSearch* pointer "Tcl_HashSearch*" $hSrc



	DBTY VTRC <- VarTrace* pointer "VarTrace*" $ptr







































	DBTY VOID <- NOTHING  alias "NOTHING" $bool
	DBTY ZON  <- ZEROONE  alias "ZEROONE" $bool
	DBTY INT  <- INT      struct "INT" $i32 $i32 $i64
	DBTY DBL  <- DOUBLE   alias "DOUBLE" $dbl
	DBTY NUM  <- NUMERIC  struct "NUMERIC" $i32 $INT $DBL
	DBTY STR  <- STRING   alias "STRING" $Obj
	DBTY FOR  <- FOREACH  struct "FOREACH" $i32 $i32
	DBTY BWD  <- BOOLWORD struct "BOOLWORD" $bool $Obj

	set str [my debug structType "Tcl_DictSearch" $ptr $i32 $ptr]


	DBTY DFR <- DICTITER pointer "DICTFOR*" [my debug structType "DICTFOR" \
		$str $Obj $Obj $Obj $i32 $bool]



	foreach {ty rt1} {


	    ZON ZEROONE
	    INT INT
	    DBL DOUBLE

	    NUM NUMERIC
	    STR STRING
	    FOR FOREACH
	    DFR DICTITER
	    BWD BOOLWORD



	} {
	    upvar 0 $ty t




	    set rt [linsert $rt1 0 FAIL]
	    if {[catch {


		DBTY dummy <- $rt struct $rt $bool $t
	    }]} {
		my Warn "failed to make debug type for $rt"
	    }
	    set rt [linsert ${rt1} 0 IMPURE]
	    if {[catch {


		DBTY dummy <- $rt struct $rt $Obj $t
	    }]} {
		my Warn "failed to make debug type for $rt"
	    }
	}




	DBTY dummy <- struct{STRING,int1} struct "" $STR $bool










    }
}
 
# Class Function --
#
#	This class handles LLVM functions when they are under construction, in
#	particular the basic blocks in the function and the attributes on
................................................................................
	set func [AddFunction [$module ref] $name $type]
	set pcount [CountParamTypes $type]
	set vararg [IsFunctionVarArg $type]
	set params {}
	set vardb {}
	set counter -1
	set nm $name




    }

    # Function:ref (property) --
    #
    #	Get the LLVM handle to the function.

    method ref {} {
................................................................................
    # Results:
    #	The LLVM value reference for the parameter.

    method param {index {name ""}} {
	if {$index < 0 || $index >= $pcount} {
	    return -code error \
		"parameter $index out of range for function \"$nm\""
	} 
	set p [GetParam $func $index]
	if {$name ne ""} {
	    SetValueName $p $name
	}
	if {[info exists dbref]} {
	    incr index
	    if {![dict exists $params $index]} {
................................................................................
    #	none
    #
    # Side effects:
    #	Stores the record for future use and for annotation into the overall
    #	function when that is finalized.

    method localvar {name type} {
	if {[info exists dbref]} {
	    set dbv [$owner debug local $dbref $name \
		    [$owner debugType [Type $type]]]
	    if {![dict exists $vardb $name]} {
		dict set params v.$name $dbv
		dict set vardb $name $dbv
	    }
	}
	return
    }

    # Function:getvardb --
    #
    #	Get the variable debugging record for a particular named variable.
................................................................................
    # Parameters:
    #	None.
    #
    # Results:
    #	A boolean, true if verification FAILS.

    method verify {} {

	if {[info exist dbref]} {
	    DebugInfo Function.SetVariables $dbref {*}[dict values $params]
	    unset dbref
	}
	set v [VerifyFunction $func LLVMReturnStatusAction]



	if {$v} {
	    my Warn "$nm failed verification"
	    # The underlying API doesn't give us _why_ it failed. :-(
	}
	return $v
    }

................................................................................
    #	Test if this is a terminated block. Terminated blocks should have no
    #	further instructions appended to them.
    #
    # Parameters:
    #	none
    #
    # Results:
    #	A boolean true if the block is terminated. 

    method terminated {} {
	return $t
    }
}
 
# Class BuildSupport --
................................................................................
	}

	# build --
	#
	#	Create a context in which the code for the current function
	#	(WARNING: in the 'f' variable) is issued. This context serves
	#	two purposes:
	# 
	#	1. Managing the collection of basic blocks so that they are
	#	   declared at the start (by pre-parsing for the embedded
	#	   [label] command). Note that the initial basic block is
	#	   stored in the variable 'entry'.
	#
	#	2. Limiting the scope of variables created within the function
	#	   for the holding of intermediate values so that intermediate
................................................................................

	proc build {script} {
	    variable BuildSupportBuilder
	    upvar 1 f func entry entry ___params params
	    if {![info exist params]} {
		set params {}
	    }

	    set linenumber [dict get [info frame -1] line]


	    $func setAsCurrentDebuggingScope
	    upvar 1 [$func name] funcref ::useCount([$func name]) count
	    set count 0
	    trace add variable funcref read [list apply {{fn args} {
		incr ::useCount([$fn name])
	    }} $func]

................................................................................

	    # Save the builder context block and point it to the function's
	    # entry point.
	    set cur [$BuildSupportBuilder @cur]
	    $BuildSupportBuilder @end $entry

	    # Insert the line number tracking
	    set lines [split $script "\n"]
	    set script ""
	    foreach line $lines {
		if {[info complete $script]} {
		    append script [list \
			    $BuildSupportBuilder @location $linenumber] ";"
		}
		incr linenumber
		append script $line "\n"
	    }

	    # Construct the wrapping lambda term.
	    set initvars {upvar 1}
	    foreach v [uplevel 1 {info vars}] {
		lappend initvars $v $v
	    }
	    append initvars ";"
................................................................................
	    }

	    # Verify the function and reset the builder context.
	    $func verify
	    $BuildSupportBuilder @end $cur
	    uplevel 1 [list unset {*}$params]
	    unset params

	    return
	}
    }
}
 
# Class LLVMBuilder --
#
................................................................................
	if {[info exist currentblock]} {
	    $currentblock terminate!
	}
    }

    # Builder:@before --
    #
    #	Insert instructions before the given instruction. 
    #
    # Parameters:
    #	insertionPoint -
    #		The (result value of the) instruction to insert before.
    #	body -	A Tcl script to run to generate the instructions to insert.
    #
    # Results:
................................................................................

    # Builder:@loc (property) --
    #
    #	Get or set the current source code location. If there is no current
    #	location, the empty string will be returned. Set to the empty string
    #	to remove the current location.

    method @loc {{locationMetadata \u0000}} {
	if {$locationMetadata eq ""} {
	    unset -nocomplain location
	} elseif {$locationMetadata ne "\u0000"} {
	    set location $locationMetadata
	}
	if {[info exist location]} {
	    return $location
................................................................................
    # Builder:@location --
    #
    #	Set the current debugging location to be the given line and column of
    #	the current debugging scope (as set at the module level).
    #
    # Parameters:
    #	line -	The line number to set.


    #	column (optional) -
    #		The column number to set. Defaults to 0.
    # 
    # Results:
    #	The debugging metadata that was set as the current location.

    method @location {line {column 0}} {
	my @loc [$m debug location $line $column]
    }

    # Builder:Locate --
    #
    #	Apply the current location to the given instruction, if a location is
    #	currently set at all.
................................................................................
    #	The instruction that was passed in.
    #
    # Side effects:
    #	The instruction may have its location metadata set.

    method Locate {instruction} {
	if {[info exist location]} {
	    DebugInfo Instruction.SetLocation $instruction $location
	}
	return $instruction
    }

    export @end @cur @loc @location
}
 
................................................................................
	    {INT NUMERIC} {
		append body2 { [my packNumericInt $} [lindex $f 0] { cast]}
	    }
	    {DOUBLE NUMERIC} {
		append body2 { [my packNumericDouble $} [lindex $f 0] { cast]}
	    }
	    {{ZEROONE BOOLEAN} ZEROONE} {
		append body2 { [my extract $} [lindex $f 0] { BOOLWORD.bool cast]}
	    }
	    {{ZEROONE BOOLEAN} STRING} {
		set var [lindex $f 0]
		append body1 ";" [string trim [subst -nocommands {
		    lappend {string casts} [set $var [my extract $$var BOOLWORD.word]]
		    my addReference(STRING) $$var
		}]]
		append body2 { $} [lindex $f 0]
	    }
	    {INT STRING} {
		set var [lindex $f 0]
		append body1 ";" [string trim [subst -nocommands {
................................................................................
		    my addReference(STRING) $$var
		}]]
		append body2 { $} [lindex $f 0]
	    }
	    {EMPTY STRING} {
		append body2 { $} [lindex $f 0]
	    }



























	}

	foreach type {
	    BOOLEAN
	    ZEROONE {ZEROONE BOOLEAN}
	    INT {INT BOOLEAN}
	    DOUBLE
	    NUMERIC
	} {
	    set impureType [linsert $type 0 IMPURE]
	    
	    dict set TypeConversions [list $type $impureType] \
		[string trim \
		     [string map \
			  [list @type $type] \
			  {
			      set var [lindex $f 0]
			      append body2 { } \[ {my {packImpure(@type)}} \



				  \$ $var { cast} \]

			  }]]

	    set b1 {
		lappend {string casts} [set @v [my stringifyImpure $@v]]
		my addReference(STRING) $@v
	    }
	    dict set TypeConversions [list $impureType STRING] \
	    	[string trim \
	    	     [string map \
			  [list @b1 [list $b1]] \
			  {
			      set v [lindex $f 0]
			      append body1 \; \
				  [string map [list @v [list $v]] @b1]
			      append body2 { } \$ [lindex $f 0]
			  }]]
	}

	# Insert the do-nothing conversions; these are generated to ensure
	# that they always exist
	foreach pair [dict keys $TypeConversions] {








	    foreach type $pair {
		set key [list $type $type]
		if {![dict exists $TypeConversions $key]} {
		    dict set TypeConversions $key \
			{append body2 { $} [lindex $f 0]}
		}
	    }
................................................................................
    #	FOLLOWS STANDARD TclOO PROTOCOL
    #
    # Side effects:
    # 	May create a method. May perform a tailcall (beware if attempting to
    # 	wrap with a filter!)

    method unknown {methodName args} {

	if {[regexp {^addReference\(IMPURE[ _](.*)\)$} $methodName -> utype]} {
	    oo::objdefine [self] method $methodName {value} \
		[string map \










		     [list @utype $utype] {
			 my addReference(STRING) [my extract $value 0]
			 # How to determine whether the underlying type is
			 # itself a reference type? (Maybe never?)
			 #my {addReference(@utype)} [my extract $value 1]
		     }]
	    tailcall my $methodName {*}$args
	} elseif {[regexp {^dropReference\(IMPURE[ _](.*)\)$} $methodName \
		       -> utype]} {
	    oo::objdefine [self] method $methodName {value} \
		[string map \
		     [list @utype $utype] {
			 my dropReference(STRING) [my extract $value 0]
			 # How to determine whether the underlying type is
			 # itself a reference type? (Maybe never?)
			 #my {dropReference(@utype)} [my extract $value 1]
		     }]
	    tailcall my $methodName {*}$args
	} elseif {[my MakeTypecastWrapper $methodName]} {
	    set v [my $methodName {*}$args]
	    return $v
	}
	next $methodName {*}$args
    }
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:







|



>




|
<
<
<
<
<
<
<
<
<
<
|
|
>








<






>
>
>
|
|
|
<
<
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>







 







<
<

<

|




|

<







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>












>







 







|
>

>
|
|
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|
>








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>

|








>




<
|
>
>
>

<
<
<
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|

<
<
<
<
>
>

<
<
<
<
<
<
>
>
>
|
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


<

<

<
<
<
<
>
>
|
<
>
>


>
>
|
|
<
>
|
<
<
<
<
>
>
>


>
>
>
>

<
>
>
|
<
<
<
|
<
>
>
|
<
<
|
|
>
>
>
|
<
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>







 







|







 







|


<
|
|
<







 







>

<


|
>
>
>







 







|







 







|







 







>
|
>
>







 







|
<
<
<
<
<
<
<
<
<







 







>







 







|







 







|







 







>
>


|



|







 







|







 







|




|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|
|
<
<
|
<
|
|
>
>
>
|
>
|


|


|
<
<
|
<
|
<
|
|
|




|
>
>
>
>
>
>
>
>







 







>
|

|
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|




<
|
|
|
|
|
|







 







>

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
...
156
157
158
159
160
161
162


163

164
165
166
167
168
169
170
171

172
173
174
175
176
177
178
...
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
...
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
...
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
...
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
...
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
....
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
....
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
....
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755

1756
1757

1758
1759
1760
1761
1762
1763
1764
....
1842
1843
1844
1845
1846
1847
1848
1849
1850

1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
....
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
....
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
....
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
....
2293
2294
2295
2296
2297
2298
2299
2300









2301
2302
2303
2304
2305
2306
2307
....
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
....
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
....
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
....
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
....
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
....
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
....
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711


2712

2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726


2727

2728

2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
....
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796

2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
....
2911
2912
2913
2914
2915
2916
2917
2918
2919
#		The execution engine associated with the module. Only
#		available after one of the engine-construction methods (e.g.,
#		'mcjit', 'interpreter') has been called.

oo::class create Module {
    superclass llvmEntity
    variable module counter funcs builder myname globals externs engine
    variable dbty mainNS thunkNS initFunction dbbuild

    constructor {name {filename "/dev/null"}} {
	next
	variable ::LLVM::debugmeta
	set myname $name
	set module [ModuleCreateWithName $name]
	SetTarget $module [GetHostTriple]

	if {$debugmeta} {










	    set dbbuild [Debugging create DBBUILD [self] $filename]
	    oo::objdefine [self] forward debug $dbbuild
	}

	set funcs {}
	set globals {}
	set externs {}
	set support [my debug namespace tcl.support]
	my debug scope $support
	my debug scope [my debug namespace types] {
	    my InitTclTypes

	}
	[my builder] @supportFunctions [self]
	my debug scope [my debug main]
	set mainNS [my debug namespace main]
	set thunkNS [my debug namespace thunks]
	my debug scope [my debug namespace tcl.library]
	# Can't verify a module part way through if debugging metadata is
	# being generated; verification checks metadata completeness.
	if {!$debugmeta} {
	    my verify
	}
    }





    # Module:FinalizeDebuggingMetadata --
    #
    #	Destroy the access to the debugging API, finalizing the debugging
    #	metadata for this module.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	None.

    method FinalizeDebuggingMetadata {} {
	if {[info exist dbbuild]} {
	    try {
		my debug destroy
	    } on error msg {
		puts ERROR:$msg
	    }
	    oo::objdefine [self] deletemethod debug
	    unset -nocomplain dbbuild
	}
    }

    # Module(self):initialiseLLVM --
    #
    #	Make llvmtcl ready to generate code. This only needs to be done once;
    #	subsequent calls will have no effect.
................................................................................
    #
    # Results:
    #	A TclOO object that encapsulates the function.

    method function.create {name type} {
	set ft [Type $type]
	set int $dbty([Type void*])


	set objname f[incr counter]([string map {::: || :: |} $name])

	switch -glob -- $name {
	    "tcl ::*"	 {set scope $mainNS}
	    cmd.thunk::* {set scope $thunkNS}
	    default	 {set scope [my debug scope]}
	}
	my debug scope $scope {
	    set f [Function create $objname [self] $name $ft]
	}

	dict set funcs $name $f
	return $f
    }

    # Module:local --
    #
    #	Create an instance of the Function class that represents a function
................................................................................
    #	args -	Extra attributes to apply to the function.
    #
    # Results:
    #	A TclOO object that encapsulates the function.

    method local {name signature args} {
	set oldfile [my debug file]
	my debug file [dict get [info frame -1] file]
	set f [my function.create $name [Type func{$signature}]]
	if {"noinline" ni $args} {
	    lappend args alwaysinline
	}
	$f private
	$f attribute {*}$args
	upvar 1 $name ref
................................................................................
    #
    # Results:
    #	A string in the format of LLVM IR.

    method dump {} {
	DumpModule $module
    }

    # Module:bitcode --
    #
    #	Produce the machine-readable LLVM bitcode that describes the module.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	A byte-array in the format of LLVM bitcode.

    method bitcode {} {
	set f [file tempfile name]
	try {
	    WriteBitcodeToFile $module [file nativename [file normalize $name]]
	    chan configure $f -translation binary
	    chan seek $f 0
	    return [chan read $f]
	} finally {
	    catch {chan close $f}
	    catch {file delete $name}
	}
    }

    # Module:verify --
    #
    #	Check the module to see if the code is actually valid.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	Empty string, or throws a Tcl error describing the problem.

    method verify {} {
	my FinalizeDebuggingMetadata
	lassign [VerifyModule $module LLVMReturnStatusAction] rt msg
	if {$rt} {
	    return -code error [string trim $msg]
	}
    }

    # Module:optimize --
................................................................................
    #	None.

    method optimize {{level 3}} {
	set level [expr {max(0, min(3, int($level)))}]

	set bld [PassManagerBuilderCreate]
	set pm [CreatePassManager]
	catch {set td [CreateTargetData ""]}
	my FinalizeDebuggingMetadata
	try {
	    if {[info exist td]} {
		SetDataLayout $module [CopyStringRepOfTargetData $td]
		AddTargetData $td $pm
	    }
	    PassManagerBuilderSetOptLevel $bld $level
	    PassManagerBuilderSetDisableUnrollLoops $bld [expr {!$level}]
	    if {$level > 1} {
		PassManagerBuilderUseInlinerWithThreshold $bld \
		    [expr {$level > 2 ? 275 : 225 }]
	    }
	    PassManagerBuilderPopulateModulePassManager $bld $pm
................................................................................
	}
	lassign [CreateJITCompilerForModule $module $optimisationLevel] rt ee msg
	if {$rt} {
	    return -code error $msg
	}
	set engine $ee
    }

    # Module:gcfuncs --
    #
    #	Delete all functions that are not actively being used by the public
    #	functions of the module.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	None.

    method gcfuncs {} {
	GarbageCollectUnusedFunctionsInModule $module
    }

    # Module:writeobject --
    #
    #	Writes the module out as a system object.
    #
    # Parameters:
    #	filename -
    #		The file to write.
    #	type (optional) -
    #		What type of file to write. Defaults to 'object' to write a .o
    #		(or .obj) format file. Can be set to 'assembly' to generate .s
    #		(or .asm) format files instead.
    #
    # Results:
    #	None.

    method writeobject {filename {type object}} {
	WriteModuleMachineCodeToFile $module \
	    [file nativename [file normalize $filename]] \
	    $::llvmtcl::host_triple $type
    }

    # Module:engine (property) --
    #
    #	Get the execution engine for the module.

    method engine {} {
	if {![info exists engine]} {
................................................................................
    # Results:
    #	None.

    method dispose {} {
	DisposeModule $module
	my destroy
    }

    # Module:getInitFunction --
    #
    #	Get the init function object, provided the thunk builder for the
    #	module has been finalized.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	The handle to the function.

    method getInitFunction {} {
	if {![info exists initFunction]} {
	    return -code error "no complete init function is defined"
	}
	return $initFunction
    }

    # Module:debug --
    #
    #	Delegated access to the debugging information issuing interface of
    #	this module, or a default implementation that mostly does nothing
    #	(except where it is evaluating a script body).
    #
    # Parameters:
    #	See the Debugging class.
    #
    # Results:
    #	See the Debugging class.

    method debug {method args} {
	if {$method eq "scope" && [llength $args] >= 2} {
	    uplevel 1 [lindex $args 1]
	}
    }

    # Module:InitTclTypes --
    #
    #	Construct instances of the types used in the Tcl interface. These are
    #	stored as LLVM type references in variables of an instance of this
    #	class. Also constructs debug delegates for the types used in the Tcl
    #	interface so that the Module:debugType method will work.
    #
    # Parameters:
    #	None.
    #
    # Results:
    #	None.

    method InitTclTypes {} {




















	# WARNING: int type may need to be larger on some platforms!
	Type NUMERIC; # Make sure we get this early, just in case







































































































































































































































































































































	# Debug-world delegates for the basic types
	DBTY void <- void   void "void"
	DBTY ptr  <- ClientData  pointer "ClientData" $void
	DBTY chr  <- char   int "char" 8
	DBTY chrs <- char*  pointer "char*" $chr
	DBTY i16  <- int16  int "Tcl_UniChar" 16
	DBTY ustr <- int16* pointer "Tcl_UniString" $i16
	DBTY i32  <- int    int "int" 32
	DBTY i32* <- int*   pointer "int*" $i32
	DBTY i64  <- int64  int "int64" 64
	DBTY bool <- bool   int "bool" 1
	DBTY b*   <- bool*  pointer "bool*" $bool
	DBTY dbl  <- double float "double" 64
	DBTY i32? <- int?   struct "optional.i32" $bool $i32
	DBTY i64? <- int64? struct "optional.i64" $bool $i64


	# Debug-world delegate for *generic* function pointers
	set fptype [Type func{int<-int}*]
	DBTY Func <- [Type func{int<-int}] function $i32 $i32
	DBTY FuncPtr <- $fptype pointer "FunctionPtr" $Func




	simultaneousDeclare {
	    # Types where we don't care about the contents
	    struct AllocCache
	    struct AsyncHandler
	    struct Channel
	    struct CompileEnv
	    struct Condition
	    struct Encoding
	    struct Ensemble
	    struct Event
	    struct InterpState
	    struct LimitHandler
	    struct Mutex
	    struct RegExp
	    struct StatBuf
	    # TSD-related stuff cannot be safely accessed outside code that
	    # comprehends it.
	    struct ThreadDataKey
	    struct ThreadLocalData
	    struct ThreadId
	    struct TimerToken

	    # Bigint implementation
	    struct mp_int {
		used:int
		alloc:int
		sign:int
		dp:mp_digit*
	    }

	    # Tcl_Obj core
	    struct ObjType {
		name:char*
		freeIntRepProc:func{void<-Tcl_Obj*}*
		dupIntRepProc:func{void<-Tcl_Obj*,Tcl_Obj*}*
		updateStringProc:func{void<-Tcl_Obj*}*
		setFromAnyProc:func{int<-Interp*,Tcl_Obj*}*
	    }
	    struct InternalRepresentation {
		void*
		void*
	    }
	    struct Tcl_Obj {
		refCount:int
		bytes:char*
		length:int
		typePtr:ObjType*
		internalRep:InternalRepresentation
	    }

	    # Stub tables
	    set STUB_SIZE 631
	    set PLAT_STUB_SIZE 2
	    set INT_STUB_SIZE 252
	    set INT_PLAT_STUB_SIZE 31
	    set OO_STUB_SIZE 29
	    set OO_INT_STUB_SIZE 16
	    struct TclIntStubs {
		magic:int
		hooks:void*
		stubs:array{$fptype,$INT_STUB_SIZE}
	    }
	    struct TclStubHooks {
		tclPlatStubs:TclPlatStubs*
		tclIntStubs:TclIntStubs*
		tclIntPlatStubs:TclIntPlatStubs*
	    }
	    struct TclPlatStubs {
		magic:int
		hooks:void*
		stubs:array{$fptype,$PLAT_STUB_SIZE}
	    }
	    struct TclIntPlatStubs {
		magic:int
		hooks:void*
		stubs:array{$fptype,$INT_PLAT_STUB_SIZE}
	    }
	    struct TclStubs {
		magic:int
		hooks:TclStubHooks*
		stubs:array{$fptype,$STUB_SIZE}
	    }
	    struct TclOOStubs {
		magic:int
		hooks:TclOOStubHooks*
		stubs:array{$fptype,$OO_STUB_SIZE}
	    }
	    struct TclOOIntStubs {
		magic:int
		hooks:void*
		stubs:array{$fptype,$OO_INT_STUB_SIZE}
	    }
	    struct TclOOStubHooks {
		tclOOIntStubs:TclOOIntStubs*
	    }

	    struct Time {
		sec:long
		usec:long
	    }

	    # Hash tables
	    set NUM_STATIC_BUCKETS 4
	    struct HashKeyType {
		version:int
		flags:int
		hashKeyProc:func{int32<-HashTable*,void*}*
		compareKeysProc:func{int<-void*,HashEntry*}*
		allocEntryProc:func{HashEntry*<-HashTable*,void*}*
		freeEntryProc:func{void<-HashEntry*}*
	    }
	    struct HashTable {
		buckets:HashEntry**
		staticBuckets:array{HashEntry*,$NUM_STATIC_BUCKETS}
		numBuckets:int
		numEntries:int
		rebuildSize:int
		downShift:int
		mask:int
		keyType:int
		findProc:func{HashEntry*<-HashTable*,char*}*
		createProc:func{HashEntry*<-HashTable*,char*,int*}*
		typePtr:HashKeyType*
	    }
	    struct HashEntry {
		nextPtr:HashEntry*
		tablePtr:HashTable*
		hash:void*
		clientData:ClientData
		key:void*
	    }
	    struct HashSearch {
		tablePtr:HashTable*
		nextIndex:int
		nextEntryPtr:HashEntry*
	    }
	    struct LiteralEntry {
		nextPtr:LiteralEntry*
		objPtr:Tcl_Obj*
		refCount:int
		nsPtr:Namespace*
	    }
	    struct LiteralTable {
		buckets:LiteralEntry**
		staticBuckets:array{LiteralEntry*,$NUM_STATIC_BUCKETS}
		numBuckets:int
		numEntries:int
		rebuildSize:int
		mask:int
	    }

	    # Namespaces, variables and commands
	    struct VarHashTable {
		table:HashTable
		nsPtr:Namespace*
	    }
	    struct Var {
		flags:int
		value:Tcl_Obj*
	    }
	    struct VarInHash {
		var:Var
		refCount:int
		entry:HashEntry
	    }
	    struct ArraySearch {
		name:Tcl_Obj*
		id:int
		varPtr:Var*
		search:HashSearch
		nextEntry:HashEntry*
		nextPtr:ArraySearch*
	    }
	    struct Trace {
		level:int
		proc:func{int<-ClientData,Interp*,int,char*,Command*,int,Tcl_Obj**}*
		clientData:ClientData
		nextPtr:Trace*
		flags:int
		delProc:func{void<-ClientData}*
	    }
	    struct ActiveInterpTrace {
		nextPtr:ActiveInterpTrace*
		nextTracePtr:Trace*
		reverseScan:int
	    }
	    struct VarTrace {
		traceProc:func{char*<-ClientData,Interp*,char*,char*,int}*
		clientData:ClientData
		flags:int
		nextPtr:VarTrace*
	    }
	    struct ActiveVarTrace {
		varPtr:Var*
		nextPtr:ActiveVarTrace*
		nextTracePtr:VarTrace*
	    }
	    set ResolveCmdProc \
		func{int<-Interp*,char*,Namespace*,int,Command*}
	    set ResolveVarProc \
		func{int<-Interp*,char*,Namespace*,int,Var*}
	    set ResolveCompiledVarProc \
		func{int<-Interp*,char*,int,Namespace*,ResolvedVarInfo**}
	    struct ResolverScheme {
		name:char*
		cmdResProc:$ResolveCmdProc*
		varResProc:$ResolveVarProc*
		compiledVarResProc:$ResolveCompiledVarProc*
		nextPtr:ResolverScheme*
	    }
	    struct ResolvedVarInfo {
		fetchProc:func{Var*<-Interp*,ResolvedVarInfo*}*
		deleteProc:func{void<-ResolvedVarInfo*}*
	    }
	    struct ResolverInfo {
		cmdResProc:$ResolveCmdProc*
		varResProc:$ResolveVarProc*
		compiledVarResProc:$ResolveCompiledVarProc*
	    }
	    struct Namespace {
		name:char*
		fullName:char*
		clientData:ClientData
		deleteProc:func{void<-ClientData}*
		parentPtr:Namespace*
		childTable:HashTable
		nsId:long
		interp:Interp*
		flags:int
		activationCount:int
		refCount:int
		cmdTable:HashTable
		varTable:VarHashTable
		exportArrayPtr:char**
		numExportPatterns:int
		maxExportPatterns:int
		cmdRefEpoch:int
		resolverEpoch:int
		cmdResProc:$ResolveCmdProc*
		varResProc:$ResolveVarProc*
		compiledVarResProc:$ResolveCompiledVarProc*
		exportLookupEpoch:int
		ensembles:Ensemble*
		unknownHandlerPtr:Tcl_Obj*
		commandPathLength:int
		commandPathArray:NamespacePathEntry*
		commandPathSourceList:NamespacePathEntry*
		earlyDeleteProc:func{void<-ClientData}*
	    }
	    struct NamespacePathEntry {
		nsPtr:Namespace*
		creatorNsPtr:Namespace*
		prevPtr:NamespacePathEntry*
		nextPtr:NamespacePathEntry*
	    }
	    struct ImportRef {
		importedCmdPtr:Command*
		nextPtr:ImportRef*
	    }
	    struct Command {
		hPtr:HashEntry*
		nsPtr:Namespace*
		refCount:int
		cmdEpoch:int
		compileProc:func{int<-Interp*,Parse*,Command*,CompileEnv*}*
		objProc:func{int<-ClientData,Interp*,int,Tcl_Obj**}*
		objClientData:ClientData
		proc:func{int<-ClientData,Interp*,int,char**}*
		clientData:ClientData
		deleteProc:func{void<-ClientData}*
		deleteData:ClientData
		flags:int
		importRefPtr:ImportRef*
		tracePtr:Trace*
		nreProc:func{int<-ClientData,Interp*,int,Tcl_Obj**}*
	    }
	    struct Proc {
		iPtr:Interp*
		refCount:int
		cmdPtr:Command*
		bodyPtr:Tcl_Obj*
		numArgs:int
		numCompiledLocals:int
		firstLocalPtr:CompiledLocal*
		lastLocalPtr:CompiledLocal*
	    }
	    struct CompiledLocal {
		nextPtr:CompiledLocal*
		nameLength:int
		frameIndex:int
		flags:int
		defValuePtr:Tcl_Obj*
		resolveInfo:ResolvedVarInfo*
		name:array{char,1}
	    }
	    struct LocalCache {
		refCount:int
		numVars:int
		varName0:array{Tcl_Obj*,1}
	    }
	    struct CallFrame {
		nsPtr:Namespace*
		isProcCallFrame:int
		objc:int
		objv:Tcl_Obj**
		callerPtr:CallFrame*
		callerVarPtr:CallFrame*
		level:int
		procPtr:Proc*
		varTablePtr:VarHashTable*
		numCompiledLocals:int
		compiledLocals:Var*
		clientData:ClientData
		localCachePtr:LocalCache*
		tailcallPtr:Tcl_Obj*
	    }
	    # type of CmdFrame.data field
	    struct CmdFrameLocation {
		void*
		pc:char*
	    }
	    struct CmdFrame {
		type:int
		level:int
		line:int*
		nline:int
		framePtr:CallFrame*
		nextPtr:CmdFrame*
		data:CmdFrameLocation
		cmdObj:Tcl_Obj*
		cmd:char*
		len:int
		litarg:CFWordBC*
	    }
	    struct CFWordBC {
		framePtr:CmdFrame*
		pc:int
		word:int
		prevPtr:CFWordBC*
		nextPtr:CFWordBC*
		obj:Tcl_Obj*
	    }
	    struct ContLineLoc {
		num:int
		loc:array{int,1}
	    }
	    struct ExtraFrameInfoField {
		name:char*
		proc:func{Tcl_Obj*<-ClientData}*
		clientData:ClientData
	    }
	    struct ExtraFrameInfo {
		length:int
		fields:array{ExtraFrameInfoField,2}
	    }

	    # Interpreter
	    struct NRECallback {
		procPtr:func{int<-ClientData*,Interp*,int}*
		data:array{ClientData,4}
		nextPtr:NRECallback*
	    }
	    struct LimitInfo {
		active:int
		granularityTicker:int
		exceeded:int
		cmdCount:int
		cmdHandlers:LimitHandler*
		cmdGranularity:int
		time:Time
		timeHandlers:LimitHandler*
		timeGranularity:int
		timeEvent:TimerToken*
		callbacks:HashTable
	    }
	    struct EnsembleInfo {
		sourceObjs:Tcl_Obj**
		numRemovedObjs:int
		numInsertedObjs:int
	    }
	    set TCL_RESULT_SIZE 201
	    struct Interp {
		result:char*
		freeProc:func{void<-char*}*
		errorLine:int
		stubTable:TclStubs*
		handle:void**
		globalNsPtr:Namespace*
		hiddenCmdTablePtr:HashTable*
		interpInfo:ClientData
		extra:HashTable
		numLevels:int
		maxNestingDepth:int
		framePtr:CallFrame*
		varFramePtr:CallFrame*
		activeVarTracePtr:ActiveVarTrace*
		returnCode:int
		rootFramePtr:CallFrame*
		lookupNsPtr:Namespace*
		appendResult:char*
		appendAvl:int
		appendUsed:int
		packageTable:HashTable
		packageUnknown:char*
		cmdCount:int
		evalFlags:int
		termOffset:int
		literalTable:LiteralTable
		compileEpoch:int
		compiledProcPtr:Proc*
		resolverPtr:ResolverScheme*
		scriptFile:Tcl_Obj*
		flags:int
		randSeed:long
		tracePtr:Trace*
		assocData:HashTable*
		execEnvPtr:ExecEnv*
		emptyObjPtr:Tcl_Obj*
		resultSpace:array{char,$TCL_RESULT_SIZE}
		objResultPtr:Tcl_Obj*
		threadId:ThreadId*
		activeCmdTracePtr:Trace*
		activeInterpTracePtr:Trace*
		tracesForbiddingInline:int
		returnOpts:Tcl_Obj*
		errorInfo:Tcl_Obj*
		eiVar:Tcl_Obj*
		errorCode:Tcl_Obj*
		ecVar:Tcl_Obj*
		returnLevel:int
		limit:LimitInfo
		ensembleRewrite:EnsembleInfo
		chanMsg:Tcl_Obj*
		cmdFramePtr:CmdFrame*
		invokeCmdFramePtr:CmdFrame*
		invokeWord:int
		linePBodyPtr:HashTable*
		lineBCPtr:HashTable*
		lineLABCPtr:HashTable*
		lineLAPtr:HashTable*
		scriptCLLocPtr:ContLineLoc*
		packagePrefer:int
		varTraces:HashTable
		varSearches:HashTable
		allocCache:AllocCache*
		pendingObjDataPtr:void*
		asyncReadyPtr:int*
		objectFoundation:OOFoundation*
		deferredCallbacks:NRECallback*
		asyncCancel:AsyncHandler*
		asyncCancelMsg:Tcl_Obj*
		errorStack:Tcl_Obj*
		upLiteral:Tcl_Obj*
		callLiteral:Tcl_Obj*
		innerLiteral:Tcl_Obj*
		innerContext:Tcl_Obj*
		resetErrorStack:int
	    }

	    struct InstructionDesc {
		name:char*
		numBytes:int
		stackEffect:int
		numOperands:int
		opTypes:array{int,2}
	    }
	    struct ExecStack {
		prevPtr:ExecStack*
		nextPtr:ExecStack*
		markerPtr:Tcl_Obj**
		endPtr:Tcl_Obj**
		tosPtr:Tcl_Obj**
		stackWords:array{Tcl_Obj*,1}
	    }
	    struct CorContext {
		framePtr:CallFrame*
		varFramePtr:CallFrame*
		cmdFramePtr:CmdFrame*
		lineLABCPtr:HashTable*
	    }
	    struct CoroutineData {
		cmdPtr:Command*
		eePtr:ExecEnv*
		callerEEPtr:ExecEnv*
		caller:CorContext
		running:CorContext
		lineLABCPtr:HashTable*
		stackLevel:void*
		auxNumLevels:int
		nargs:int
	    }
	    struct ExecEnv {
		execStackPtr:ExecStack*
		constants:array{Tcl_Obj,2}
		interp:Interp*
		callbackPtr:NRECallback*
		corPtr:CoroutineData*
		rewind:int
	    }

	    struct OOFoundation {
		interp:Interp*
		objectCls:Class*
		classCls:Class*
		ooNs:Namespace*
		defineNs:Namespace*
		objdefNs:Namespace*
		helpersNs:Namespace*
		epoch:int
		tsdPtr:ThreadLocalData*
		unknownMethodNameObj:Tcl_Obj*
		constructorName:Tcl_Obj*
		destructorName:Tcl_Obj*
		clonedName:Tcl_Obj*
		defineName:Tcl_Obj*
	    }
	    struct Class {
		thisPtr:Object*
		refCount:int
		flags:int
		superclasses:StaticList_Class
		subclasses:DynamicList_Class
		instances:DynamicList_Object
		filters:StaticList_Value
		mixins:StaticList_Class
		mixinSubs:DynamicList_Class
		classMethods:HashTable
		constructorPtr:Method*
		destructorPtr:Method*
		metadataPtr:HashTable*
		constructorChainPtr:CallChain*
		destructorChainPtr:CallChain*
		classChainCache:HashTable*
		variables:StaticList_Value
	    }
	    struct Object {
		fPtr:OOFoundation*
		namespacePtr:Namespace*
		command:Command*
		myCommand:Command*
		selfCls:Class*
		methodsPtr:HashTable*
		mixins:StaticList_Class
		filters:StaticList_Value
		classPtr:Class*
		refCount:int
		flags:int
		creationEpoch:int
		epoch:int
		metadataPtr:HashTable*
		cachedNameObj:Tcl_Obj*
		chainCache:HashTable*
		mapMethodNameProc:func{int<-Interp*,Object*,Class*,Tcl_Obj*}*
	    }
	    set CALL_CHAIN_STATIC_SIZE 4
	    struct CallChain {
		objectCreationEpoch:int
		objectEpoch:int
		epoch:int
		flags:int
		refCount:int
		numChain:int
		chain:MInvoke*
		staticChain:array{MInvoke,$CALL_CHAIN_STATIC_SIZE}
	    }
	    struct MInvoke {
		mPtr:Method*
		isFilter:int
		filterDeclarer:Class*
	    }
	    struct CallContext {
		oPtr:Object*
		index:int
		skip:int
		callPtr:CallChain*
	    }
	    struct Method {
		typePtr:MethodType*
		refCount:int
		clientData:ClientData
		namePtr:Tcl_Obj*
		declaringObjectPtr:Object*
		declaringClassPtr:Class*
		flags:int
	    }
	    struct ProcedureMethod {
		version:int
		procPtr:Proc*
		flags:int
		refCount:int
		clientData:ClientData
		deleteClientdataProc:func{void<-ClientData}*
		cloneClientdataProc:func{ClientData<-ClientData}*
		errProc:func{void<-Interp*,Tcl_Obj*}*
		preCallProc:func{int<-ClientData,Interp*,CallContext*,CallFrame*,int*}*
		postCallProc:func{int<-ClientData,Interp*,CallContext*,Namespace*,int}*
		gfivProc:func{Tcl_Obj*<-ClientData}*
	    }
	    struct ForwardMethod {
		prefixObj:Tcl_Obj*
	    }
	    struct MethodType {
		version:int
		name:char*
		callProc:func{int<-ClientData,Interp*,CallContext*,int,Tcl_Obj**}*
		deleteProc:func{void<-ClientData}*
		cloneProc:func{int<-Interp*,ClientData,ClientData*}*
	    }
	    struct ObjectMetadataType {
		version:int
		name:char*
		deleteProc:func{void<-ClientData}*
		cloneProc:func{int<-Interp*,ClientData,ClientData*}*
	    }
	    # TclOO synthetic std structure types
	    struct StaticList_Class {
		num:int
		list:Class*
	    }
	    struct StaticList_Value {
		num:int
		list:Tcl_Obj*
	    }
	    struct DynamicList_Class {
		num:int
		size:int
		list:Class*
	    }
	    struct DynamicList_Object {
		num:int
		size:int
		list:Object*
	    }

	    # Miscellaneous other public types
	    set TCL_DSTRING_STATIC_SIZE 200
	    struct DString {
		string:char*
		length:int
		spaceAvl:int
		staticSpace:array{char,$TCL_DSTRING_STATIC_SIZE}
	    }
	    struct ChannelType {
		typeName:char*
		version:named{ChannelTypeVersion}*
		closeProc:func{int<-ClientData,Interp*}*
		inputProc:func{int<-ClientData,char*,int,int*}*
		outputProc:func{int<-ClientData,char*,int,int*}*
		seekProc:func{int<-ClientData,long,int,int*}*
		setOptionProc:func{int<-ClientData,Interp*,char*,char*}*
		getOptionProc:func{int<-ClientData,Interp*,char*,DString*}*
		watchProc:func{int<-ClientData,int}*
		getHandleProc:func{int<-ClientData,int,void*}*
		close2Proc:func{int<-ClientData,Interp*,int}*
		blockModeProc:func{int<-ClientData,int}*
		flushProc:func{int<-ClientData}*
		handlerProc:func{int<-ClientData,int}*
		wideSeekProc:func{int<-ClientData,int64,int,int*}*
		threadActionProc:func{int<-ClientData,int}*
		truncateProc:func{int<-ClientData,int64}*
	    }
	    struct CmdInfo {
		isNativeObjectProc:int
		objProc:func{int<-ClientData,Interp*,int,Tcl_Obj**}*
		objClientData:ClientData
		proc:func{int<-ClientData,Interp*,int,char**}*
		clientData:ClientData
		deleteProc:func{int<-ClientData}*
		deleteData:ClientData
		namespacePtr:Namespace*
	    }
	    struct Config {
		key:char*
		value:char*
	    }
	    struct Event {
		proc:func{int<-Event*,int}*
		nextPtr:Event*
	    }
	    struct Token {
		type:int
		start:char*
		size:int
		numComponents:int
	    }
	    set NUM_STATIC_TOKENS 20
	    struct Parse {
		commentStart:char*
		commentSize:int
		commandStart:char*
		commandSize:int
		numWords:int
		tokenPtr:Token*
		numTokens:int
		tokensAvailable:int
		errorType:int
		string:char*
		end:char*
		interp:Interp*
		term:char*
		incomplete:int
		staticTokens:array{Token,$NUM_STATIC_TOKENS}
	    }
	    struct RegExpIndices {
		start:long
		end:long
	    }
	    struct RegExpInfo {
		nsubs:int
		matches:RegExpIndices*
		extendStart:long
		reserved:long
	    }
	    struct FSVersion
	    struct Filesystem {
		typeName:char*
		structureLength:int
		version:FSVersion*
		pathInFilesystemProc:func{int<-Tcl_Obj*,ClientData*}*
		dupInternalRepProc:func{ClientData<-ClientData}*
		freeInternalRepProc:func{void<-ClientData}*
		internalToNormalizedProc:func{Tcl_Obj*<-ClientData}*
		createInternalRepProc:func{ClientData<-Tcl_Obj*}*
		normalizePathProc:func{int<-Interp*,Tcl_Obj*,int}*
		filesystemPathTypeProc:func{Tcl_Obj*<-Tcl_Obj*}*
		filesystemSeparatorProc:func{Tcl_Obj*<-Tcl_Obj*}*
		statProc:func{int<-Tcl_Obj*,StatBuf*}*
		accessProc:func{int<-Tcl_Obj*,int}*
		openFileChannelProc:func{Channel*<-Interp*,Tcl_Obj*,int,int}*
		matchInDirectoryProc:func{int<-Interp*,Tcl_Obj*,Tcl_Obj*,char*,GlobTypeData*}*
		utimeProc:func{int<-Tcl_Obj*,utimbuf*}*
		linkProc:func{Tcl_Obj*<-Tcl_Obj*,Tcl_Obj*,int}*
		listVolumesProc:func{Tcl_Obj*<-}*
		fileAttrStringsProc:func{char**<-Tcl_Obj*,Tcl_Obj**}*
		fileAttrsGetProc:func{int<-Interp*,int,Tcl_Obj*,Tcl_Obj**}*
		fileAttrsSetProc:func{int<-Interp*,int,Tcl_Obj*,Tcl_Obj*}*
		createDirectoryProc:func{int<-Tcl_Obj*}*
		removeDirectoryProc:func{int<-Tcl_Obj*,int,Tcl_Obj**}*
		deleteFileProc:func{int<-Tcl_Obj*}*
		copyFileProc:func{int<-Tcl_Obj*,Tcl_Obj*}*
		renameFileProc:func{int<-Tcl_Obj*,Tcl_Obj*}*
		copyDirectoryProc:func{int<-Tcl_Obj*,Tcl_Obj*,Tcl_Obj**}*
		lstatProc:func{int<-Tcl_Obj*,StatBuf*}*
		loadFileProc:func{int<-Interp*,Tcl_Obj*,LoadHandle*,void**}*
		getCwdProc:func{Tcl_Obj*<-Interp*}*
		chdirProc:func{int<-Tcl_Obj*}*
	    }
	    struct GlobTypeData {
		type:int
		perm:int
		macType:Tcl_Obj*
		macCreator:Tcl_Obj*
	    }
	    # FIXME: This is known to be correct for OSX only; CHECK
	    # elsewhere...
	    struct utimbuf {
		long
		long
	    }
	    struct LoadHandle {
		clientData:ClientData
		findSymbolProcPtr:func{void*<-Interp*,LoadHandle*,char*}*
		unloadFileProcPtr:func{void<-LoadHandle*}*
	    }

	    # List internal representation
	    struct TclList {
		refCount:int
		maxElemCount:int
		elemCount:int
		canonicalFlag:int
		elements:Tcl_Obj*
	    }

	    # Dict internal representation
	    struct ChainEntry {
		entry:HashEntry
		prevPtr:ChainEntry*
		nextPtr:ChainEntry*
	    }
	    struct Dict {
		table:HashTable
		entryChainHead:ChainEntry*
		entryChainTail:ChainEntry*
		epoch:int
		refcount:int
		chain:Tcl_Obj*
	    }
	    struct DictSearch {
		next:ChainEntry*
		epoch:int
		dictionaryPtr:Dict*
	    }
	}

	DBTY ObjType <- ObjType*  pointer "" $ObjType
	DBTY Obj     <- Tcl_Obj*  pointer "" $Tcl_Obj
	DBTY ObjRef  <- Tcl_Obj** pointer "" $Obj





	DBTY Interp <- Interp*	  pointer "" $Interp
	DBTY Hash <- HashTable*	  pointer "" $HashTable







	DBTY HENT <- HashEntry*	  pointer "" $HashEntry
	DBTY VarHash <- VarHashTable* pointer "" $VarHashTable
	DBTY HSRC <- HashSearch*  pointer "" $HashSearch
	DBTY VTRC <- VarTrace*	  pointer "" $ptr
	DBTY TVAR <- Var*	  pointer "" $Var
	DBTY FRM  <- CallFrame*	  pointer "" $CallFrame
	DBTY PROC <- Proc*	  pointer "" $Proc
	DBTY NS   <- Namespace*	  pointer "" $Namespace
	DBTY LC   <- LocalCache*  pointer "" $LocalCache

	struct INT {
	    kind:bool
	    i32:int32
	    i64:int64
	}
	struct NUMERIC {
	    kind:bool
	    int:INT
	    double:double
	}
	struct FOREACH {
	    val:int
	    max:int
	}
	struct DICTFOR {
	    search:DictSearch
	    dict:STRING
	    key:STRING
	    value:STRING
	    ref:int
	    done:int1
	}
	struct ARRAYIMPL {
	    ref:int
	    provenance:bool
	    ary:VarHashTable*
	}
	struct ARRAYSTRING {
	    kind:bool
	    array:ARRAY
	    scalar:STRING
	}

	DBTY VOID <- NOTHING  alias "NOTHING" $bool
	DBTY ZON  <- ZEROONE  alias "ZEROONE" $bool

	DBTY DBL  <- DOUBLE   alias "DOUBLE" $dbl

	DBTY STR  <- STRING   alias "STRING" $Obj




	DBTY ARY  <- ARRAY    pointer "ARRAY" $ARRAYIMPL
	DBTY ASTR <- "ARRAY STRING" struct "ARRAYSTRING" $bool $VarHash $Obj
	DBTY DFR  <- DICTITER pointer "DICTFOR*" $DICTFOR

	DBTY dummy <- "FOREACH FAIL"  struct "FOREACH?"  $bool $FOREACH
	DBTY dummy <- "DICTITER FAIL" struct "DICTITER?" $bool $DFR

	foreach {ty rt1} {
	    i32      int32
	    i64      int64
	    ZON      ZEROONE
	    INT      INT

	    DBL      DOUBLE
	    NUMERIC  NUMERIC




	    STR      STRING
	    ARY      ARRAY
	    ASTR     ARRAYSTRING
	} {
	    upvar 0 $ty t
	    set rt [linsert $rt1 0 IMPURE]
	    DBTY impure <- $rt struct <$rt1> $Obj $t
	    set rt [linsert $rt1 0 NEXIST]
	    DBTY impure <- $rt struct $rt1! $i32 $t
	    set rt [linsert $rt1 0 FAIL]

	    DBTY fail <- $rt struct $rt1? $bool $t
	    set rt [linsert $rt1 0 NEXIST IMPURE]
	    DBTY dummy <- $rt struct <$rt1>! $i32 $impure



	    set rt [linsert $rt1 0 FAIL IMPURE]

	    DBTY dummy <- $rt struct <$rt1>? $bool $impure
	    set rt [linsert $rt1 0 FAIL NEXIST]
	    DBTY dummy <- $rt struct $rt1!? $bool $impure


	}

	struct "" {
	    int
	    int16*
	}

	struct "" {
	    int
	    int8*
	}
	struct "" {
	    STRING
	    bool
	}

	return
    }
}
 
# Class Function --
#
#	This class handles LLVM functions when they are under construction, in
#	particular the basic blocks in the function and the attributes on
................................................................................
	set func [AddFunction [$module ref] $name $type]
	set pcount [CountParamTypes $type]
	set vararg [IsFunctionVarArg $type]
	set params {}
	set vardb {}
	set counter -1
	set nm $name
	set dbtype [$module debug functionType \
		[$module debugType [GetReturnType $type]] \
		{*}[lmap t [GetParamTypes $type] {$module debugType $t}]]
	set dbref [$module debug function $func $dbtype]
    }

    # Function:ref (property) --
    #
    #	Get the LLVM handle to the function.

    method ref {} {
................................................................................
    # Results:
    #	The LLVM value reference for the parameter.

    method param {index {name ""}} {
	if {$index < 0 || $index >= $pcount} {
	    return -code error \
		"parameter $index out of range for function \"$nm\""
	}
	set p [GetParam $func $index]
	if {$name ne ""} {
	    SetValueName $p $name
	}
	if {[info exists dbref]} {
	    incr index
	    if {![dict exists $params $index]} {
................................................................................
    #	none
    #
    # Side effects:
    #	Stores the record for future use and for annotation into the overall
    #	function when that is finalized.

    method localvar {name type} {
	if {[info exists dbref] && ![dict exists $vardb $name]} {
	    set dbv [$owner debug local $dbref $name \
		    [$owner debugType [Type $type]]]

	    dict set params v.$name $dbv
	    dict set vardb $name $dbv

	}
	return
    }

    # Function:getvardb --
    #
    #	Get the variable debugging record for a particular named variable.
................................................................................
    # Parameters:
    #	None.
    #
    # Results:
    #	A boolean, true if verification FAILS.

    method verify {} {
	variable ::LLVM::debugmeta
	if {[info exist dbref]} {

	    unset dbref
	}
	set v [expr {!$debugmeta && [VerifyFunction $func LLVMReturnStatusAction]}]
	# LLVM BUG: can't verify an individual function until we close the
	# debugging handle, which we can't do until we finish compiling the
	# module.
	if {$v} {
	    my Warn "$nm failed verification"
	    # The underlying API doesn't give us _why_ it failed. :-(
	}
	return $v
    }

................................................................................
    #	Test if this is a terminated block. Terminated blocks should have no
    #	further instructions appended to them.
    #
    # Parameters:
    #	none
    #
    # Results:
    #	A boolean true if the block is terminated.

    method terminated {} {
	return $t
    }
}
 
# Class BuildSupport --
................................................................................
	}

	# build --
	#
	#	Create a context in which the code for the current function
	#	(WARNING: in the 'f' variable) is issued. This context serves
	#	two purposes:
	#
	#	1. Managing the collection of basic blocks so that they are
	#	   declared at the start (by pre-parsing for the embedded
	#	   [label] command). Note that the initial basic block is
	#	   stored in the variable 'entry'.
	#
	#	2. Limiting the scope of variables created within the function
	#	   for the holding of intermediate values so that intermediate
................................................................................

	proc build {script} {
	    variable BuildSupportBuilder
	    upvar 1 f func entry entry ___params params
	    if {![info exist params]} {
		set params {}
	    }
	    set contextlocation [info frame -1]
	    set linenumber [dict get $contextlocation line]
	    set filename [dict get $contextlocation file]
	    [$func module] debug scope "" {
	    $func setAsCurrentDebuggingScope
	    upvar 1 [$func name] funcref ::useCount([$func name]) count
	    set count 0
	    trace add variable funcref read [list apply {{fn args} {
		incr ::useCount([$fn name])
	    }} $func]

................................................................................

	    # Save the builder context block and point it to the function's
	    # entry point.
	    set cur [$BuildSupportBuilder @cur]
	    $BuildSupportBuilder @end $entry

	    # Insert the line number tracking
	    set script [$BuildSupportBuilder AddLineDirectives $linenumber $filename $script]










	    # Construct the wrapping lambda term.
	    set initvars {upvar 1}
	    foreach v [uplevel 1 {info vars}] {
		lappend initvars $v $v
	    }
	    append initvars ";"
................................................................................
	    }

	    # Verify the function and reset the builder context.
	    $func verify
	    $BuildSupportBuilder @end $cur
	    uplevel 1 [list unset {*}$params]
	    unset params
	    }
	    return
	}
    }
}
 
# Class LLVMBuilder --
#
................................................................................
	if {[info exist currentblock]} {
	    $currentblock terminate!
	}
    }

    # Builder:@before --
    #
    #	Insert instructions before the given instruction.
    #
    # Parameters:
    #	insertionPoint -
    #		The (result value of the) instruction to insert before.
    #	body -	A Tcl script to run to generate the instructions to insert.
    #
    # Results:
................................................................................

    # Builder:@loc (property) --
    #
    #	Get or set the current source code location. If there is no current
    #	location, the empty string will be returned. Set to the empty string
    #	to remove the current location.

    method @loc {{locationMetadata "\u0000"}} {
	if {$locationMetadata eq ""} {
	    unset -nocomplain location
	} elseif {$locationMetadata ne "\u0000"} {
	    set location $locationMetadata
	}
	if {[info exist location]} {
	    return $location
................................................................................
    # Builder:@location --
    #
    #	Set the current debugging location to be the given line and column of
    #	the current debugging scope (as set at the module level).
    #
    # Parameters:
    #	line -	The line number to set.
    #	file (optional) -
    #		The file containing the file. Defaults to empty string.
    #	column (optional) -
    #		The column number to set. Defaults to 0.
    #
    # Results:
    #	The debugging metadata that was set as the current location.

    method @location {line {file ""} {column 0}} {
	my @loc [$m debug location $line $column]
    }

    # Builder:Locate --
    #
    #	Apply the current location to the given instruction, if a location is
    #	currently set at all.
................................................................................
    #	The instruction that was passed in.
    #
    # Side effects:
    #	The instruction may have its location metadata set.

    method Locate {instruction} {
	if {[info exist location]} {
	    $m debug setInstructionLocation $instruction $location
	}
	return $instruction
    }

    export @end @cur @loc @location
}
 
................................................................................
	    {INT NUMERIC} {
		append body2 { [my packNumericInt $} [lindex $f 0] { cast]}
	    }
	    {DOUBLE NUMERIC} {
		append body2 { [my packNumericDouble $} [lindex $f 0] { cast]}
	    }
	    {{ZEROONE BOOLEAN} ZEROONE} {
		append body2 { $} [lindex $f 0]
	    }
	    {{ZEROONE BOOLEAN} STRING} {
		set var [lindex $f 0]
		append body1 ";" [string trim [subst -nocommands {
		    lappend {string casts} [set $var [my {stringify($t)} $$var]]
		    my addReference(STRING) $$var
		}]]
		append body2 { $} [lindex $f 0]
	    }
	    {INT STRING} {
		set var [lindex $f 0]
		append body1 ";" [string trim [subst -nocommands {
................................................................................
		    my addReference(STRING) $$var
		}]]
		append body2 { $} [lindex $f 0]
	    }
	    {EMPTY STRING} {
		append body2 { $} [lindex $f 0]
	    }
	    {{IMPURE ZEROONE} {IMPURE INT}} {
		append body2 [format { [my upcastImpure.INT(ZEROONE) $%s]} [lindex $f 0]]
	    }
	    {{IMPURE ZEROONE} {IMPURE NUMERIC}} {
		append body2 [format { [my upcastImpure.NUMERIC(ZEROONE) $%s]} [lindex $f 0]]
	    }
	    {{IMPURE INT} {IMPURE NUMERIC}} {
		append body2 [format { [my upcastImpure.NUMERIC(INT) $%s]} [lindex $f 0]]
	    }
	    {{IMPURE DOUBLE} {IMPURE NUMERIC}} {
		append body2 [format { [my upcastImpure.NUMERIC(DOUBLE) $%s]} [lindex $f 0]]
	    }
	    {NOTHING STRING} {
		append body2 { [my undef STRING]}
	    }
	    {{EXPANDED STRING} STRING} {
		append body2 { $} [lindex $f 0]
	    }
	    {{EXPANDED INT} INT} {
		append body2 { $} [lindex $f 0]
	    }
	    {{EXPANDED DOUBLE} DOUBLE} {
		append body2 { $} [lindex $f 0]
	    }
	    {{EXPANDED NUMERIC} NUMERIC} {
		append body2 { $} [lindex $f 0]
	    }
	}

	foreach type {
	    BOOLEAN
	    ZEROONE {ZEROONE BOOLEAN}
	    INT {INT BOOLEAN}
	    DOUBLE
	    NUMERIC
	} {
	    set impureType [linsert $type 0 IMPURE]

	    dict set TypeConversions [list $type $impureType] [string trim \


		    [string map [list @type $type] {

			set var [lindex $f 0]
			append body2 { [my {packImpure(@type)} $} $var {]}
		    }]]

	    dict set TypeConversions [list $impureType $type] [string trim \
		    [string map [list @type $type] {
			append body2 { [my impure.value $} [lindex $f 0] {]}
		    }]]

	    set b1 {
		lappend {string casts} [set @v [my impure.string $@v]]
		my addReference(STRING) $@v
	    }
	    dict set TypeConversions [list $impureType STRING] [string trim \


		    [string map [list @b1 [list $b1]] {

			set v [lindex $f 0]

			append body1 \; [string map [list @v [list $v]] @b1]
			append body2 { } \$ [lindex $f 0]
		    }]]
	}

	# Insert the do-nothing conversions; these are generated to ensure
	# that they always exist
	set typepairs [dict keys $TypeConversions]
	set SpecialTypes {
	    ARRAY {ARRAY STRING} {NEXIST ARRAY} {NEXIST ARRAY STRING}
	    DICTFOR FOREACH
	}
	foreach type $SpecialTypes {
	    lappend typepairs [list $type $type]
	}
	foreach pair $typepairs {
	    foreach type $pair {
		set key [list $type $type]
		if {![dict exists $TypeConversions $key]} {
		    dict set TypeConversions $key \
			{append body2 { $} [lindex $f 0]}
		}
	    }
................................................................................
    #	FOLLOWS STANDARD TclOO PROTOCOL
    #
    # Side effects:
    # 	May create a method. May perform a tailcall (beware if attempting to
    # 	wrap with a filter!)

    method unknown {methodName args} {
	if {[regexp {^addReference\(FAIL IMPURE (.*)\)$} \
		 $methodName -> utype]} {
	    oo::objdefine [self] method $methodName {value} \
		[string map [list @utype $utype] {
		    my addReference(STRING) \
			[my impure.string [my unmaybe $value]]
		    # How to determine whether the underlying type is
		    # itself a reference type? (Maybe never?)
		    #my {addReference(@utype)} [my impure.value $value]
		}]
	    tailcall my $methodName {*}$args
	} elseif {[regexp {^addReference\(IMPURE[ _](.*)\)$} \
		       $methodName -> utype]} {
	    oo::objdefine [self] method $methodName {value} \
		[string map [list @utype $utype] {
		    my addReference(STRING) [my impure.string $value]
		    # How to determine whether the underlying type is
		    # itself a reference type? (Maybe never?)
		    #my {addReference(@utype)} [my impure.value $value]
		}]
	    tailcall my $methodName {*}$args
	} elseif {[regexp {^dropReference\(IMPURE[ _](.*)\)$} $methodName \
		       -> utype]} {
	    oo::objdefine [self] method $methodName {value} \

		[string map [list @utype $utype] {
		    my dropReference(STRING) [my impure.string $value]
		    # How to determine whether the underlying type is
		    # itself a reference type? (Maybe never?)
		    #my {dropReference(@utype)} [my impure.value $value]
		}]
	    tailcall my $methodName {*}$args
	} elseif {[my MakeTypecastWrapper $methodName]} {
	    set v [my $methodName {*}$args]
	    return $v
	}
	next $methodName {*}$args
    }
................................................................................
    }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil
# buffer-file-coding-system: utf-8-unix
# End:

Changes to codegen/tclapi.tcl.

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
..
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
...
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
...
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
...
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
...
444
445
446
447
448
449
450

451
452




453
454
455
456
457
458
459
...
462
463
464
465
466
467
468

469
470




471
472
473
474
475
476
477
...
480
481
482
483
484
485
486

487

488
489
490
491
492
493
494
...
506
507
508
509
510
511
512




























513
514
515
516
517
518
519
...
521
522
523
524
525
526
527

528

529
530
531
532
533
534
535
...
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
...
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
....
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
....
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
....
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
....
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
....
1165
1166
1167
1168
1169
1170
1171

1172
# tclapi.tcl --
#
#	Defines how Tcl's own API is mapped into LLVM. Adjunct to thunk.tcl.
#
# Copyright (c) 2015 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
oo::define ThunkBuilder {

































































































































    # ThunkBuilder:API --
    #
    #	Bind a public Tcl API function and construct a method of the current
    #	instance of the class for generating a call to that function. Two
    #	sorts of bindings are supported, one based on the stub table, and one
    #	based on direct calls to the Tcl API functions; the choice between
    #	them is based on the presence (or absence) of the global variable
    #	::USE_TCL_STUBS.

    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	index -	The index into the public stub table. Essential for stub
    #		binding.
    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc (optional) -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
................................................................................
    #		If supplied, the default LLVM name to apply to the result of
    #		the call.
    #
    # Results:
    #	None.

    method API {index name type {postfunc ""} {defName ""}} {
	set type [Type func{$type}]
	set count [CountParamTypes $type]
	set vararg [IsFunctionVarArg $type]
	if {![info exists ::USE_TCL_STUBS]} {
	    set func [$m function.extern $name $type]
	    AddFunctionAttr $func nounwind
	    my closure $name args {
		# Because these are *much* less nasty than crashes!
		if {$vararg && [llength $args] < $count} {
		    return -code error "insufficient arguments"
		} elseif {!$vararg && [llength $args] != $count} {
		    return -code error "wrong number of arguments"

		}
		foreach expected [GetParamTypes $type] got $args {
		    if {[incr i]>$count} break;	# Stop checking; varargs...
		    if {$got eq ""} {
			set got [$b null $expected]
			lset args [expr {$i-1}] $got
			continue



		    }
		    set got [TypeOf $got]
		    if {$got ne $expected} {
			return -code error "type mismatch at argument ${i}:\
			    expected [PrintTypeToString $expected] but\
			    got [PrintTypeToString $got]"
		    }
		}
		set call [$b call $func $args]
		SetTailCall $call 0
		if {$defName ne ""} {
		    SetValueName $call $defName
		}
		foreach f $postfunc {
		    my {*}$f $call
		}
		return $call
	    }
	} else {
	    upvar 1 stubtable stubtable
	    set ptype [Type $type*]
	    set fptr [$b dereference $stubtable 0 2 $index]
	    set var [$m variable $name $ptype [$b null $ptype]]
	    $b store [$b cast(ptr) $fptr $type] $var
	    my closure $name args {
		# Because these are *much* less nasty than crashes!
		if {$vararg && [llength $args] < $count} {
		    return -code error "insufficient arguments"
		} elseif {!$vararg && [llength $args] != $count} {
		    return -code error "wrong number of arguments"
		}
		foreach expected [GetParamTypes $type] got $args {
		    if {[incr i]>$count} break;	# Stop checking; varargs...
		    if {$got eq ""} {
			set got [$b null $expected]
			lset args [expr {$i-1}] $got
			continue
		    }
		    set got [TypeOf $got]
		    if {$got ne $expected} {
			return -code error "type mismatch at argument ${i}:\
			    expected [PrintTypeToString $expected] but\
			    got [PrintTypeToString $got]"
		    }
		}
		set call [$b call [$b load $var] $args]
		SetTailCall $call 0
		if {$defName ne ""} {
		    SetValueName $call $defName
		}
		foreach f $postfunc {
		    my {*}$f $call
		}
		return $call
	    }
	}
	oo::objdefine [self] export $name
    }

    # ThunkBuilder:IntAPI --
    #
    #	Bind an internal Tcl API function and construct a method of the
    #	current instance of the class for generating a call to that function.
    #	Two sorts of bindings are supported, one based on the stub table, and
    #	one based on direct calls to the Tcl API functions; the choice between
    #	them is based on the presence (or absence) of the global variable
    #	::USE_TCL_STUBS.

    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	index -	The index into the internal stub table. Essential for stub
    #		binding.
    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc (optional) -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
................................................................................
    #		If supplied, the default LLVM name to apply to the result of
    #		the call.
    #
    # Results:
    #	None.

    method IntAPI {index name type {postfunc ""} {defName ""}} {
	set type [Type func{$type}]
	set count [CountParamTypes $type]
	set vararg [IsFunctionVarArg $type]
	if {![info exists ::USE_TCL_STUBS]} {
	    set func [$m function.extern $name $type]
	    AddFunctionAttr $func nounwind
	    my closure $name args {
		# Because these are *much* less nasty than crashes!
		if {$vararg && [llength $args] < $count} {
		    return -code error "insufficient arguments"
		} elseif {!$vararg && [llength $args] != $count} {
		    return -code error "wrong number of arguments"
		}
		foreach expected [GetParamTypes $type] got $args {
		    if {[incr i]>$count} break; # Stop checking; varargs...
		    if {$got eq ""} {
			set got [$b null $expected]
			lset args [expr {$i-1}] $got
			continue
		    }
		    set got [TypeOf $got]
		    if {$got ne $expected} {
			return -code error "type mismatch at argument ${i}:\
			    expected [PrintTypeToString $expected] but\
			    got [PrintTypeToString $got]"
		    }
		}
		set call [$b call $func $args]
		SetTailCall $call 0
		if {$defName ne ""} {
		    SetValueName $call $defName
		}
		foreach f $postfunc {
		    my {*}$f $call
		}
		return $call
	    }
	} else {
	    upvar 1 intstubtable stubtable
	    set ptype [Type $type*]
	    set fptr [$b dereference $stubtable 0 2 $index]
	    set var [$m variable $name $ptype [$b null $ptype]]
	    $b store [$b cast $fptr $type] $var
	    my closure $name args {
		# Because these are *much* less nasty than crashes!
		if {$vararg && [llength $args] < $count} {
		    return -code error "insufficient arguments"
		} elseif {!$vararg && [llength $args] != $count} {
		    return -code error "wrong number of arguments"
		}
		foreach expected [GetParamTypes $type] got $args {
		    if {[incr i]>$count} break; # Stop checking; varargs...
		    if {$got eq ""} {
			set got [$b null $expected]
			lset args [expr {$i-1}] $got
			continue
		    }
		    set got [TypeOf $got]
		    if {$got ne $expected} {
			return -code error "type mismatch at argument ${i}:\
			    expected [PrintTypeToString $expected] but\
			    got [PrintTypeToString $got]"
		    }
		}
		set call [$b call [$b load $var] $args]
		SetTailCall $call 0
		if {$defName ne ""} {
		    SetValueName $call $defName
		}
		foreach f $postfunc {
		    my {*}$f $call
		}
		return $call
	    }
	}
	oo::objdefine [self] export $name














    }

    # ThunkBuilder:APIVar --
    #
    #	Bind a variable in the module to a particular value. A public method
    #	with the same name as the variable will be added to the instance; that
    #	method generates a read of the variable when called.
................................................................................
    #	interp -
    #		The LLVM value reference to the Tcl interpreter.
    #
    # Results:
    #	None.

    method InitTclAPI {interp} {



	set stubtable [$b dereference $interp 0 3]
	set intstubtable [$b dereference [$b dereference $stubtable 0 1] 0 1]




	set cur [$b @cur]

	# ThunkBuilder:AssertZeroRefCount --
	#
	#	Asserts that the result of the function to which it is applied
	#	is a Tcl_Obj reference with a reference count of zero.

	#
	# Parameters:
	#	objPtr -
	#		The LLVM value reference to the Tcl_Obj*.
	#
	# Results:
	#	None.

	set f [$m local AssertZeroRefCount void<-Tcl_Obj*]
	params objPtr
	build {
	    AddArgumentAttribute $objPtr nonnull
	    set refCount [$b getelementptr $objPtr [list $0 $0] "refCount"]


	    if {[catch {
		$b assume [$b eq [$b load $refCount] $0]
	    }]} {
		# Older LLVM; use this intrusive version instead
		$b store $0 $refCount
	    }


	    $b ret
	}
	my closure AssertZeroRefCount objPtr {
	    if {![info exist ::env(NOASSERTS)]} {
		$b Call [$f ref] $objPtr
	    }
	}

	# ThunkBuilder:AssertNonNullResult --























	#
	#	Asserts that the result of the function to which it is applied
	#	is a a pointer that does not point to NULL.
	#
	# Parameters:
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure AssertNonNullResult ptr {
	    upvar 1 call call
	    AddCallAttribute $call 0 nonnull
	}

































	# ThunkBuilder:NonNullArgs --
	#
	#	Asserts that some of the arguments of the function to which it
	#	is applied are pointers that do not point to NULL.
	#
	# Parameters:
	#	indices... -
	#		The argument indices that are non-null.

	#	ptr -	The LLVM value reference to the pointer. Ignored.
	#
	# Results:
	#	None.

	my closure NonNullArgs {args} {
	    upvar 1 call call
	    set ptr [lindex $args end]
	    foreach index [lrange $args 0 end-1] {
		AddCallAttribute $call $index nonnull
	    }
	}

	# ThunkBuilder:NoAliasArgs --
	#
	#	Asserts that the arguments of the function to which it is
	#	applied (when pointers) are not aliased to each other.
	#
	# Parameters:
	#	result -
	#		Ignored.


	#
	# Results:
	#	None.

	my closure NoAliasArgs result {
	    upvar 1 call call args args
	    foreach a $args {
		incr i
		if {[GetTypeKind [TypeOf $a]] eq "LLVMPointerTypeKind"} {
		    AddCallAttribute $call $i noalias
		}
	    }
	}

	# ThunkBuilder:NoAliasResult --
	#
	#	Asserts that the result of the function is a pointer that does
	#	not alias any other pointer that the LLVM engine knows about.
	#
................................................................................

	# ThunkBuilder:NoCapture --
	#
	#	Asserts that the arguments of the function to which it is
	#	applied (when pointers) are not captured and used later.
	#
	# Parameters:
	#	result -
	#		Ignored.
	#
	# Results:
	#	None.

	my closure NoCapture result {
	    upvar 1 call c args ar
	    foreach a $ar {
		incr i
		if {[GetTypeKind [TypeOf $a]] eq "LLVMPointerTypeKind"} {
		    AddCallAttribute $c $i nocapture
		}
	    }
	}

	# ThunkBuilder:NoCaptureArgs --
	#
	#	Asserts that some of the arguments of the function to which it
	#	is applied are pointers that are not captured and used later.
	#
	# Parameters:
	#	indices... -
	#		The argument indices that are not captured.

	#	ptr -	The LLVM value reference to the call. Ignored.
	#
	# Results:
	#	None.

	my closure NoCaptureArgs args {
	    upvar 1 call call
	    set ptr [lindex $args end]

	    foreach index [lrange $args 0 end-1] {
		AddCallAttribute $call $index nocapture
	    }
	}

	# ThunkBuilder:AssertAllocated --
	#
	#	Asserts that the result of the function to which it is
	#	applied is a newly-allocated pointer.
	#
................................................................................
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure AssertAllocated ptr {
	    if {![info exist ::env(NOASSERTS)]} {

		$b Call [$m intrinsic lifetime.start] \
			[Const -1 int64] [$b cast(ptr) $ptr void]




	    }
	}

	# ThunkBuilder:AssertDeallocated --
	#
	#	Asserts that the result of the function to which it is
	#	applied is a deallocated pointer, not to be further used.
................................................................................
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure AssertDeallocated ptr {
	    if {![info exist ::env(NOASSERTS)]} {

		$b Call [$m intrinsic lifetime.end] \
			[Const -1 int64] [$b cast(ptr) $ptr void]




	    }
	}

	# ThunkBuilder:ReadOnly --
	#
	#	Asserts that the function to which it is applied only reads
	#	memory, and makes no alterations.
................................................................................
	#	ptr -	Ignored.
	#
	# Results:
	#	None.

	my closure ReadOnly ptr {
	    upvar 1 func func

	    AddFunctionAttr $func readonly

	}

	# ThunkBuilder:ReadOnlyArgs --
	#
	#	Asserts that the pointer arguments to which it is applied are
	#	only read from, not written through.
	#
................................................................................
	my closure ReadOnlyArgs args {
	    upvar 1 call call
	    set ptr [lindex $args end]
	    foreach index [lrange $args 0 end-1] {
		AddCallAttribute $call $index readonly
	    }
	}





























	# ThunkBuilder:ReadNone --
	#
	#	Asserts that the function to which it is applied does not read
	#	or write memory at all; its result depends purely on its
	#	arguments. Enables aggressive optimisations.
	#
................................................................................
	#	ptr -	Ignored.
	#
	# Results:
	#	None.

	my closure ReadNone ptr {
	    upvar 1 func func

	    AddFunctionAttr $func readnone

	}

	# ThunkBuilder:NoReturn --
	#
	#	Asserts that the function to which it is applied does not
	#	return, that it is a total failure path. Enables aggressive
	#	optimisations.
................................................................................
	#	ptr -	Ignored.
	#
	# Results:
	#	None.

	my closure NoReturn ptr {
	    upvar 1 func func

	    AddFunctionAttr $func noreturn
	}


	$cur build-in $b

	# Define the Tcl API functions we're using
	set size_t int
	set Tcl_NRPostPtr [Type func{int<-void**,Tcl_Interp*,int}*]














































	my API 0 Tcl_PkgProvideEx int<-Tcl_Interp*,char*,char*,void* {
	    {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3 4}} "code"




	my API 2 Tcl_Panic void<-char*,... NoReturn
	my API 3 Tcl_Alloc void*<-$size_t {
	    NoAliasResult AssertNonNullResult} "ptr"
	my API 4 Tcl_Free void<-void*
	my API 5 Tcl_Realloc void*<-void*,$size_t {
	    NoAliasResult AssertNonNullResult} "ptr"

	my API 6 Tcl_DbCkalloc void*<-$size_t,char*,int {
	    NoAliasResult AssertNonNullResult {ReadOnlyArgs 2}} "ptr"
	my API 7 Tcl_DbCkfree void<-void*,char*,int {
	    {ReadOnlyArgs 2}}
	my API 8 Tcl_DbCkrealloc void*<-void*,$size_t,char*,int {
	    NoAliasResult AssertNonNullResult {ReadOnlyArgs 3}} "ptr"















	my API 17 Tcl_ConcatObj Tcl_Obj*<-int,Tcl_Obj** {
	    NoAliasResult NoCapture AssertNonNullResult AssertZeroRefCount
	    {ReadOnlyArgs 2}} "objPtr"































	my API 29 Tcl_DuplicateObj Tcl_Obj*<-Tcl_Obj* {
	    NoAliasResult NoCapture AssertNonNullResult AssertZeroRefCount
	    {NonNullArgs 1} {ReadOnlyArgs 1}} "objPtr"
	my API 30 TclFreeObj void<-Tcl_Obj* {{NonNullArgs 1}}

	my API 32 Tcl_GetBooleanFromObj int<-Tcl_Interp*,Tcl_Obj*,int* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3}} "code"
	my API 33 Tcl_GetByteArrayFromObj char*<-Tcl_Obj*,$size_t* {
	    NoAliasArgs AssertNonNullResult NoCapture {NonNullArgs 1}} "bytes"

	my closure Tcl_GetByteArray {obj} {
	    my Tcl_GetByteArrayFromObj $obj [$b null int*]
	}
	oo::objdefine [self] export Tcl_GetByteArray

	my API 35 Tcl_GetDoubleFromObj int<-Tcl_Interp*,Tcl_Obj*,double* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3}} "code"





	my API 38 Tcl_GetIntFromObj int<-Tcl_Interp*,Tcl_Obj*,int* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3}} "code"

	my API 40 Tcl_GetObjType Tcl_ObjType*<-char* {
	    NoCapture ReadOnly {NonNullArgs 1} {ReadOnlyArgs 1}} "objTypePtr"
	my API 41 Tcl_GetStringFromObj char*<-Tcl_Obj*,$size_t* {
	    NoAliasArgs AssertNonNullResult NoCapture {NonNullArgs 1}} "str"

	my API 42 Tcl_InvalidateStringRep void<-Tcl_Obj* {
	    NoCapture {NonNullArgs 1}}


	my API 44 Tcl_ListObjAppendElement \
	    int<-Tcl_Interp*,Tcl_Obj*,Tcl_Obj* {
	    NoAliasArgs {NonNullArgs 2 3} {NoCaptureArgs 1 2}} "code"
	my API 45 Tcl_ListObjGetElements \
	    int<-Tcl_Interp*,Tcl_Obj*,int*,Tcl_Obj*** {
		NoAliasArgs NoCapture {NonNullArgs 2 3 4}} "code"

	my API 46 Tcl_ListObjIndex int<-Tcl_Interp*,Tcl_Obj*,int,Tcl_Obj** {
	    NoAliasArgs NoCapture {NonNullArgs 2 4}} "code"
	my API 47 Tcl_ListObjLength int<-Tcl_Interp*,Tcl_Obj*,int* {
	    NoAliasArgs NoCapture {NonNullArgs 2}} "code"
	my API 48 Tcl_ListObjReplace \
	    int<-Tcl_Interp*,Tcl_Obj*,int,int,int,Tcl_Obj** {
		NoAliasArgs NoCapture {NonNullArgs 2 6} {ReadOnlyArgs 6}
	    } "code"
	my API 49 Tcl_NewBooleanObj Tcl_Obj*<-int {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"
	my API 50 Tcl_NewByteArrayObj Tcl_Obj*<-char*,$size_t {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount
	    NoCapture ReadOnly {NonNullArgs 1} {ReadOnlyArgs 1}} "objPtr"
	my API 51 Tcl_NewDoubleObj Tcl_Obj*<-double {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"
	my API 52 Tcl_NewIntObj Tcl_Obj*<-int {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"
	my API 53 Tcl_NewListObj Tcl_Obj*<-int,Tcl_Obj** {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount NoCapture
	    {ReadOnlyArgs 2}} "objPtr"


	my API 55 Tcl_NewObj Tcl_Obj*<- {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"
	my API 56 Tcl_NewStringObj Tcl_Obj*<-char*,$size_t {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount NoCapture
	    {ReadOnlyArgs 1}} "objPtr"














	my API 64 Tcl_SetObjLength void<-Tcl_Obj*,int NoCapture































































	my API 96 Tcl_CreateObjCommand \
	    void*<-Tcl_Interp*,char*,$Tcl_ObjCmdPtr,void*,$Tcl_CmdDeletePtr {

		{NonNullArgs 1 2 3} {NoCaptureArgs 2} {ReadOnlyArgs 2 3 5}
	    } "cmdPtr"


























	my API 108 Tcl_DeleteHashEntry void<-Tcl_HashEntry* {
	    {NonNullArgs 1}}
	my API 109 Tcl_DeleteHashTable void<-Tcl_HashTable* {
	    {NonNullArgs 1}}
























































	my API 132 Tcl_EventuallyFree void<-void*,func{void<-void*}*














	my API 145 Tcl_FirstHashEntry \
	    Tcl_HashEntry*<-Tcl_HashTable*,Tcl_HashSearch* {
		{NonNullArgs 1 2} {NoCaptureArgs 2} {ReadOnlyArgs 1}} "hPtr"









































	my API 161 Tcl_GetErrno int<- {} "errno"






	my API 166 Tcl_GetObjResult Tcl_Obj*<-Tcl_Interp* {
	    NoCapture AssertNonNullResult} "objPtr"



















	my API 181 Tcl_InitHashTable void<-Tcl_HashTable*,int {
	    NoCapture {NonNullArgs 1}}









	my API 187 Tcl_LinkVar int<-Tcl_Interp*,char*,void*,int {
	    {NonNullArgs 1 2 3} {ReadOnlyArgs 2}} "code"
	my API 145 Tcl_NextHashEntry Tcl_HashEntry*<-Tcl_HashSearch* {












	    {NonNullArgs 1} {NoCaptureArgs 1}} "hPtr"
	my API 195 Tcl_ObjGetVar2 \
	    Tcl_Obj*<-Tcl_Interp*,Tcl_Obj*,Tcl_Obj*,int {
		{NonNullArgs 1 2}} "objPtr"
	my API 196 Tcl_ObjSetVar2 \
	    Tcl_Obj*<-Tcl_Interp*,Tcl_Obj*,Tcl_Obj*,Tcl_Obj*,int {
		{NonNullArgs 1 2 4}} "objPtr"














































	my API 227 Tcl_SetErrno void<-int
	my API 228 Tcl_SetErrorCode void<-Tcl_Interp*,... {
	    NoCapture {NonNullArgs 1}}






	my API 234 Tcl_SetObjErrorCode void<-Tcl_Interp*,Tcl_Obj* {
	    NoAliasArgs {NonNullArgs 1 2}}
	my API 235 Tcl_SetObjResult void<-Tcl_Interp*,Tcl_Obj* {
	    NoAliasArgs {NonNullArgs 1 2}}















































	my API 264 Tcl_WrongNumArgs void<-Tcl_Interp*,int,Tcl_Obj**,char* {
	    NoCapture NoAliasArgs {NonNullArgs 1} {ReadOnlyArgs 3 4}}


































	my API 286 Tcl_AppendObjToObj void<-Tcl_Obj*,Tcl_Obj* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}}







	my API 292 Tcl_EvalObjv int<-Tcl_Interp*,int,Tcl_Obj**,int {
	    NoCapture NoAliasArgs {NonNullArgs 1 3} {ReadOnlyArgs 3}} "code"


















































	my API 324 Tcl_UniCharToUtf int<-int,char* {


	    NoCapture {NonNullArgs 2}} "len"












	my API 331 Tcl_UtfPrev char*<-char*,char* {
	    NoCapture ReadOnly AssertNonNullResult {NonNullArgs 1 2}
	    {ReadOnlyArgs 1 2}} "chPtr"





	my API 334 Tcl_UtfToLower int<-char* {
	    NoCapture {NonNullArgs 1}} "len"
	my API 335 Tcl_UtfToTitle int<-char* {
	    NoCapture  {NonNullArgs 1}} "len"
	my API 336 Tcl_UtfToUniChar int<-char*,$Tcl_UniChar* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2} {ReadOnlyArgs 1}} "len"

	my API 337 Tcl_UtfToUpper int<-char* {
	    NoCapture {NonNullArgs 1}} "len"





	my API 340 Tcl_GetString char*<-Tcl_Obj* {
	    NoCapture AssertNonNullResult {NonNullArgs 1}} "str"




	my API 345 Tcl_UniCharIsAlnum int<-int16 \
	    ReadNone "test"
	my API 346 Tcl_UniCharIsAlpha int<-int16 \
	    ReadNone "test"
	my API 347 Tcl_UniCharIsDigit int<-int16 \
	    ReadNone "test"
	my API 348 Tcl_UniCharIsLower int<-int16 \
	    ReadNone "test"
	my API 349 Tcl_UniCharIsSpace int<-int16 \
	    ReadNone "test"
	my API 350 Tcl_UniCharIsUpper int<-int16 \
	    ReadNone "test"
	my API 351 Tcl_UniCharIsWordChar int<-int16 \
	    ReadNone "test"


	my API 353 Tcl_UniCharNcmp int<-$Tcl_UniChar*,$Tcl_UniChar*,int {
	    NoCapture ReadOnly {NonNullArgs 1 2} {ReadOnlyArgs 1 2}} "cmp"




	my API 356 Tcl_GetRegExpFromObj \
	    Tcl_RegExp*<-Tcl_Interp*,Tcl_Obj*,int {
		NoCapture NoAliasArgs {NonNullArgs 2}} "rePtr"




























	my API 371 Tcl_StringCaseMatch int<-char*,char*,int {
	    NoCapture ReadOnly {NonNullArgs 1 2} {ReadOnlyArgs 1 2}}
	my API 372 Tcl_UniCharIsControl int<-int16 \
	    ReadNone "test"
	my API 373 Tcl_UniCharIsGraph int<-int16 \
	    ReadNone "test"
	my API 374 Tcl_UniCharIsPrint int<-int16 \
	    ReadNone "test"
	my API 375 Tcl_UniCharIsPunct int<-int16 \
	    ReadNone "test"
	my API 376 Tcl_RegExpExecObj \
	    int<-Tcl_Interp*,Tcl_RegExp*,Tcl_Obj*,int,int,int {
		NoCapture NoAliasArgs {NonNullArgs 2 3}} "code"



	my API 378 Tcl_NewUnicodeObj Tcl_Obj*<-$Tcl_UniChar*,int {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount NoCapture
	    {NonNullArgs 1} {ReadOnlyArgs 1}} "objPtr"


	my API 380 Tcl_GetCharLength int<-Tcl_Obj* {
	    NoCapture {NonNullArgs 1}} "length"
	my API 381 Tcl_GetUniChar $Tcl_UniChar<-Tcl_Obj*,int {
	    NoCapture ReadOnly {NonNullArgs 1}}
	my API 382 Tcl_GetUnicode $Tcl_UniChar*<-Tcl_Obj* {
	    NoCapture AssertNonNullResult {NonNullArgs 1}} "ustr"
	my API 383 Tcl_GetRange Tcl_Obj*<-Tcl_Obj*,int,int {
	    NoAliasResult AssertNonNullResult NoCapture AssertZeroRefCount
	    {NonNullArgs 1}} "objPtr"
	my API 384 Tcl_AppendUnicodeToObj void<-Tcl_Obj*,$Tcl_UniChar*,int {
	    NoCapture NoAliasArgs {NonNullArgs 1 2} {ReadOnlyArgs 2}}




















































	my API 421 Tcl_FindHashEntry Tcl_HashEntry*<-Tcl_HashTable*,void* {
	    NoCapture NoAliasArgs {NonNullArgs 1} {ReadOnlyArgs 2}} "hPtr"
	my API 422 Tcl_CreateHashEntry \
	    Tcl_HashEntry*<-Tcl_HashTable*,void*,int* {
		AssertNonNullResult NoAliasArgs {NonNullArgs 1 3}
		{NoCaptureArgs 1 3}} "hPtr"
	my API 424 Tcl_InitObjHashTable void<-Tcl_HashTable* {























	    NoCapture {NonNullArgs 1}}


	my API 434 Tcl_GetUnicodeFromObj $Tcl_UniChar*<-Tcl_Obj*,int* {
	    AssertNonNullResult NoAliasArgs NoCapture {NonNullArgs 1}} "ustr"






















































































































	my API 487 Tcl_GetWideIntFromObj int<-Tcl_Interp*,Tcl_Obj*,int64* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3}} "code"
	my API 488 Tcl_NewWideIntObj Tcl_Obj*<-int64 {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"
	my API 494 Tcl_DictObjPut \









	    int<-Tcl_Interp*,Tcl_Obj*,Tcl_Obj*,Tcl_Obj* {
		{NonNullArgs 2 3 4} {NoCaptureArgs 1 2}} "code"
	my API 495 Tcl_DictObjGet \
	    int<-Tcl_Interp*,Tcl_Obj*,Tcl_Obj*,Tcl_Obj** {
		NoCapture {NonNullArgs 2 3 4} {ReadOnlyArgs 3}} "code"

	my API 496 Tcl_DictObjRemove int<-Tcl_Interp*,Tcl_Obj*,Tcl_Obj* {
	    NoCapture {NonNullArgs 2 3} {ReadOnlyArgs 3}} "code"
	my API 497 Tcl_DictObjSize int<-Tcl_Interp*,Tcl_Obj*,int* {
	    NoCapture {NonNullArgs 2 3}} "code"
	my API 498 Tcl_DictObjFirst \
	    int<-Tcl_Interp*,Tcl_Obj*,Tcl_DictSearch*,Tcl_Obj**,Tcl_Obj**,int* {
		{NonNullArgs 2 3 4 5 6} {NoCaptureArgs 1 3 4 5 6}} "code"
	my API 499 Tcl_DictObjNext \

	    void<-Tcl_DictSearch*,Tcl_Obj**,Tcl_Obj**,int* {
		NoCapture {NonNullArgs 1 2 3 4}}
	my API 500 Tcl_DictObjDone void<-Tcl_DictSearch* {
	    NoCapture {NonNullArgs 1}}
	my API 501 Tcl_DictObjPutKeyList \
	    int<-Tcl_Interp*,Tcl_Obj*,int,Tcl_Obj**,Tcl_Obj* {
		{NonNullArgs 2 4 5} {NoCaptureArgs 1 2 4} {ReadOnlyArgs 4}
	    } "code"
	my API 502 Tcl_DictObjRemoveKeyList \
	    int<-Tcl_Interp*,Tcl_Obj*,int,Tcl_Obj** {
		NoCapture {NonNullArgs 2 4} {ReadOnlyArgs 4}} "code"
	my API 503 Tcl_NewDictObj Tcl_Obj*<- {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"
	my API 504 Tcl_DbNewDictObj Tcl_Obj*<-char*,int {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount} "objPtr"



























































	my API 538 Tcl_SetReturnOptions int<-Tcl_Interp*,Tcl_Obj* {
	    NoAliasArgs {NonNullArgs 1 2} {NoCaptureArgs 1}} "code"
	my API 539 Tcl_GetReturnOptions Tcl_Obj*<-Tcl_Interp*,int {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount NoCapture
	    {NonNullArgs 1}} "objPtr"















	my API 555 Tcl_NewBignumObj Tcl_Obj*<-mp_int* {



	    NoAliasResult AssertNonNullResult AssertZeroRefCount NoCapture


	} "objPtr"
	my API 558 Tcl_GetBignumFromObj int<-Tcl_Interp*,Tcl_Obj*,mp_int* {





































	    NoCapture NoAliasArgs {NonNullArgs 2}} "code"

	my API 578 Tcl_ObjPrintf Tcl_Obj*<-char*,... {
	    NoAliasResult AssertNonNullResult AssertZeroRefCount NoCapture





	    {NonNullArgs 1}} "objPtr"



	my API 583 Tcl_NRCreateCommand \
	    Command*<-Tcl_Interp*,char*,$Tcl_ObjCmdPtr,$Tcl_ObjCmdPtr,void*,$Tcl_CmdDeletePtr {
		{NonNullArgs 1 2} {NoCaptureArgs 2}} "cmdPtr"


	my API 584 Tcl_NREvalObj int<-Tcl_Interp*,Tcl_Obj*,int \
	    NoAliasArgs "code"
	my API 585 Tcl_NREvalObjv int<-Tcl_Interp*,int,Tcl_Obj**,int \
	    NoAliasArgs "code"
	my API 586 Tcl_NRCmdSwap \
	    int<-Tcl_Interp*,Command*,int,Tcl_Obj**,int NoAliasArgs "code"

	my API 587 Tcl_NRAddCallback \
	    void<-Tcl_Interp*,$Tcl_NRPostPtr,void*,void*,void*,void*









































































	# Internal API





































	my IntAPI 34 TclGetIntForIndex int<-Tcl_Interp*,Tcl_Obj*,int,int* {
	    NoCapture NoAliasArgs {NonNullArgs 2 4}} "code"






























































































































	my IntAPI 166 TclListObjSetElement \
	    int<-Tcl_Interp*,Tcl_Obj*,int,Tcl_Obj* {
		NoAliasArgs {NonNullArgs 2 4} {NoCaptureArgs 1 2}} "code"

	my IntAPI 169 TclpUtfNcmp2 int<-char*,char*,int {
	    NoCapture ReadOnly {NonNullArgs 1 2} {ReadOnlyArgs 1 2}} "cmp"








	my IntAPI 173 TclUniCharMatch \
	    int<-$Tcl_UniChar*,int,$Tcl_UniChar*,int,int {
		NoCapture ReadOnly {NonNullArgs 1 3} {ReadOnlyArgs 1 3}}

	my IntAPI 175 TclCallVarTraces \
	    int<-Tcl_Interp*,Var*,Var*,char*,char*,int,int {
		NoCapture {NonNullArgs 1 2 4}} "code"
	my IntAPI 176 TclCleanupVar void<-Var*,Var* {
	    NoCapture NoAliasArgs {NonNullArgs 1}}
	my IntAPI 177 TclVarErrMsg void<-Tcl_Interp*,char*,char*,char*,char* {
	    NoCapture {NonNullArgs 1 2 4 5} {ReadOnlyArgs 2 3 4 5}}























	my IntAPI 225 TclTraceDictPath \
	    Tcl_Obj*<-Tcl_Interp*,Tcl_Obj*,int,Tcl_Obj**,int {
		NoCapture NoAliasArgs {NonNullArgs 2 4} {ReadOnlyArgs 4}
	    } "objPtr"







	my IntAPI 230 TclObjLookupVar \
	    Var*<-Tcl_Interp*,Tcl_Obj*,char*,int,char*,int,int,Var** {
		{NoCaptureArgs 1 3 5 8} NoAliasArgs {NonNullArgs 1 2 5 8} 
		{ReadOnlyArgs 3 5}} "varPtr"
	my IntAPI 231 TclGetNamespaceFromObj \
	    int<-Tcl_Interp*,Tcl_Obj*,Namespace** {
		NoCapture NoAliasArgs {NonNullArgs 1 2 3}} "code"










































































































































































	# Special "constants"

	my APIVar tclIntType \
	    [set it [my Tcl_GetObjType [$b constString "int" "type.int"]]]
	my APIVar tclDoubleType \
	    [my Tcl_GetObjType [$b constString "double" "type.double"]]
	my APIVar tclBooleanType \
	    [my Tcl_GetObjType [$b constString "boolean" "type.boolean"]]
	my APIVar tclByteArrayType \
	    [my Tcl_GetObjType [$b constString "bytearray" "type.bytes"]]
	my APIVar tclStringType \
	    [my Tcl_GetObjType [$b constString "string" "type.string"]]
	set wt [my Tcl_GetObjType [$b constString "wideInt" "type.wide"]]
	my APIVar tclWideIntType [$b select [$b nonnull $wt] $wt $it]
	my APIVar tclListType \
	    [my Tcl_GetObjType [$b constString "list" "type.list"]]
	my APIVar tclInterp $interp "interp"
	my APIVar tclEmptyString [set emptyString [my Tcl_NewObj]]
	my APIVar tclEmptyStringRep \
	    [$b dereference $emptyString 0 Tcl_Obj.bytes]


	set cur [$b @cur]
	my @macros
	my @thunkHelpers
	$cur build-in $b


	my Tcl_IncrRefCount $emptyString

    }

    # ThunkBuilder:MathFunc --
    #
    #	Create an LLVM function that represents a Tcl math function. Assumes
    #	that it is only ever called from the 'InitMathFuncs' method.
    #
................................................................................
    #	body -	The script that defines how to implement the function.
    #
    # Results:
    #	None.

    method MathFunc {name type body} {
	upvar 1 funs funs func func






	set sig [split [regsub {.*<-} $type ""] ","]
	set fullname [list tcl ::tcl::mathfunc::$name $sig]
	if {$fullname in $funs} {
	    my Warn "double definition of math function '$name'"
	    return
	}
	set func [$m function.create $fullname [Type func{$type}]]
	$func private
	$func attribute alwaysinline readnone


	[$func block] build-in $b
	uplevel 1 $body




	$func verify
	lappend funs $fullname
	return
    }

    # ThunkBuilder:InitMathFuncs --
    #
................................................................................
	    $b ret [$b cast(INT) [$b Call $intr [$func param 0 "x"]]]
	}
	return [lsort $funs]
    }

    variable thunk.result.ZEROONE thunk.result.INT\ BOOLEAN thunk.result.INT
    variable thunk.result.DOUBLE thunk.result.NUMERIC thunk.result.STRING
    variable thunk.result.VOID thunk.arg.default

    # ThunkBuilder:@thunkHelpers --
    #
    #	Create the functions that map from tclquadcode values to standard Tcl
    #	result values. The names include the logical name of the type being
    #	mapped, and the type of each function's second argument must be the
    #	actual type that will be handled at that point. The interpreter result
................................................................................
    #
    # Results:
    #	None.

    method @thunkHelpers {} {
	##### Function thunk.result.ZEROONE #####
	#
	# Type signature: interp:Tcl_Interp* * result:ZEROONE -> void
	#
	# Transfers a result value to the Tcl interpreter.

	set f [$m local "thunk.result.ZEROONE" void<-Tcl_Interp*,int1]
	params interp result
	build {
	    nonnull $interp
	    my Tcl_SetObjResult $interp [my Tcl_NewBooleanObj \
		    [$b select $result [Const 1] [Const 0]]]
	    $b ret
	}

	##### Function thunk.result.INT BOOLEAN #####
	#
	# Type signature: interp:Tcl_Interp* * result:INT -> void
	#
	# Transfers a result value to the Tcl interpreter.

	set f [$m local "thunk.result.INT BOOLEAN" void<-Tcl_Interp*,INT]
	params interp result
	build {
	    nonnull $interp
	    my Tcl_SetObjResult $interp [my Tcl_NewBooleanObj \
		    [$b getInt32 $result]]
	    $b ret
	}

	##### Function thunk.result.INT #####
	#
	# Type signature: interp:Tcl_Interp* * result:INT -> void
	#
	# Transfers a result value to the Tcl interpreter.

	# FIXME interim fix
	set f [$m local "thunk.result.INT" void<-Tcl_Interp*,INT]
	params interp result
	build {
	    nonnull $interp
	    $b condBr [$b isInt32 $result] $r32 $r64
	label r32 "result.32bit"
	    set v32 [my Tcl_NewIntObj [$b int.32 $result]]
	    $b br $next
................................................................................
	    set v [$b phi [list $v32 $v64] [list $r32 $r64] "obj.result"]
	    my Tcl_SetObjResult $interp $v
	    $b ret
	}

	##### Function thunk.result.DOUBLE #####
	#
	# Type signature: interp:Tcl_Interp* * result:DOUBLE -> void
	#
	# Transfers a result value to the Tcl interpreter.

	set f [$m local "thunk.result.DOUBLE" void<-Tcl_Interp*,DOUBLE]
	params interp result
	build {
	    nonnull $interp
	    my Tcl_SetObjResult $interp [my Tcl_NewDoubleObj $result]
	    $b ret
	}

	##### Function thunk.result.NUMERIC #####
	#
	# Type signature: interp:Tcl_Interp* * result:NUMERIC -> void
	#
	# Transfers a result value to the Tcl interpreter.

	set f [$m local "thunk.result.NUMERIC" void<-Tcl_Interp*,NUMERIC]
	params interp result
	build {
	    nonnull $interp
	    $b condBr [$b isNumericInt $result] $rInt $rDbl
	label rDbl:
	    set thisVal [$b numeric.double $result]
	    $b call ${thunk.result.DOUBLE} [list $interp $thisVal]
................................................................................
	    set thisVal [$b numeric.int $result]
	    $b call ${thunk.result.INT} [list $interp $thisVal]
	    $b ret
	}

	##### Function thunk.result.STRING #####
	#
	# Type signature: interp:Tcl_Interp* * result:STRING -> void
	#
	# Transfers a result value to the Tcl interpreter.

	set f [$m local "thunk.result.STRING" void<-Tcl_Interp*,STRING]
	params interp result
	build {
	    nonnull $interp $result
	    my Tcl_SetObjResult $interp $result
	    my Tcl_DecrRefCount $result
	    $b ret
	}

















	##### Function thunk.arg.default #####
	#
	# Type signature: index:int * argc:int * argv:STRING*
	#				* default:STRING -> STRING
	#
	# Computes whether to use a real argument or use a default value.
................................................................................
   }
}
 
# Local Variables:
# mode: tcl
# fill-column: 78
# auto-fill-function: nil

# End:




|







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|
<
>






|
<







 







|
|
<
<
<
<
<
<
<
|
<
<
>
|
<
<
<
<
<
<
>
>
>
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






|
<
>






|
<







 







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
|
|
>
>
|
>





|
>











|
|
>
>






>
>








|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|
>






|
|
|
<
<








|
|
>
>




|
|
|
|
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
>
|




|
|
<
>
|
<
<







 







>
|

>
>
>
>







 







>
|

>
>
>
>







 







>
|
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
|
>







 







>
|
|
|
>


|
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>


|
|

<
>

|

|

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|


>
|
|

|
>

|


>
|
|
>
>
>
>
>
|
|
>
|


|
>


>
>
|
<
|

|
|
>
|
|
|
|

|



|

|


|

|

|

>
>

|

|

>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

<
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
|
|
<
>
>
>
>
>
>
>
>
>
>
>
>
|
|
<
|

|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
>
>
>
>
>
>
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>
>
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
|
>
>
>
>
>
>
>
>
>
>
>
>

|

>
>
>
>
>




|
|
>


>
>
>
>
>

|
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
|

>
>
>
>
|
<
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|
|
|
|
|
|
|
|

|

>
>
>
|
|

>
>


|

|
|

|

|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

|
<
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|

|
<
>
>
>
>
>
>
>
>
>
|
|
<
|
|
>
|

|
|

|
|
<
>
|
|
|


|
|
|

|


|

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
|
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>

|
>
>
>
>
>
|
>
>
>

<
<
>
>
|
|
|
|
|
<
>

<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
|
>

<
>
>
>
>
>
>
>
>
|
<
|
>

|



|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
|
|
>
>
>
>
>
>
>

|
|
|

|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>






>
|
>







 







>
>
>
>
>
>
|
<







>
>
|
<
>
>
>
>







 







|







 







|



|










|



|










|




|







 







|



|









|



|







 







|



|







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>

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
...
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
...
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
...
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
...
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
...
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
...
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
...
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
...
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
...
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
...
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
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887


1888
1889
1890
1891
1892
1893
1894

1895
1896

1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969

1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135

2136
2137
2138

2139
2140
2141
2142
2143
2144
2145
2146
2147

2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
....
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421

2422
2423
2424
2425
2426
2427
2428
2429
2430
2431

2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
....
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
....
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
....
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
....
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
....
2740
2741
2742
2743
2744
2745
2746
2747
2748
# tclapi.tcl --
#
#	Defines how Tcl's own API is mapped into LLVM. Adjunct to thunk.tcl.
#
# Copyright (c) 2015-2017 by Donal K. Fellows
#
# See the file "license.terms" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------------
 
oo::define ThunkBuilder {
    # ThunkBuilder:@apiDeclare --
    #
    #	Bind an API function and construct a method of the current instance of
    #	the class for generating a call to that function. Two sorts of
    #	bindings are supported, one based on the stub table, and one based on
    #	direct calls to the API functions; the choice between them is based on
    #	the presence (or absence) of the variable ::LLVM::useStubs.
    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	stubsname -
    #		The name of the variable in the caller holding the stubs
    #		table. Only needs to actually point to a variable if stubs are
    #		being used.
    #	index -	The index into the stub table. Essential for stub binding.
    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
    #		allocated memory, etc.
    #	defName -
    #		The default LLVM name to apply to the result of the call, or
    #		the empty string to not apply a name.
    #
    # Results:
    #	None.

    method @apiDeclare {stubsname index name type postfunc defName} {
	variable ::LLVM::useStubs
	set type [Type func{$type}]
	set count [CountParamTypes $type]
	set vararg [IsFunctionVarArg $type]
	if {!$useStubs} {
	    set func [$m function.extern $name $type]
	    AddFunctionAttr $func nounwind
	    my closure $name args {
		my @apiVerify $type $count $vararg args
		set call [$b call $func $args]
		SetTailCall $call 0
		if {$defName ne ""} {
		    SetValueName $call $defName
		}
		foreach f $postfunc {
		    my {*}$f $call
		}
		return $call
	    }
	} else {
	    upvar 1 $stubsname stubtable
	    set ptype [Type $type*]
	    my buildInSection API {
		# Assume that the real stub table is always at index 2 in the
		# relevant structure. Should be true given the current table
		# generation code.
		set fptr [$b dereference $stubtable 0 2 $index]
		set var [$m variable $name $ptype [$b null $ptype]]
		$b store [$b cast(ptr) $fptr $type] $var
	    }
	    my closure $name args {
		my @apiVerify $type $count $vararg args
		set func [$b loadInvariant $var]
		set call [$b call $func $args]
		SetTailCall $call 0
		if {$defName ne ""} {
		    SetValueName $call $defName
		}
		foreach f $postfunc {
		    my {*}$f $call
		}
		return $call
	    }
	}
	oo::objdefine [self] export $name
    }

    # ThunkBuilder:@apiVerify --
    #
    #	Helper used to check that the arguments being passed to an API
    #	function are sane. Makes the caller throw an error if the arguments
    #	don't make sense.
    #
    # Parameters:
    #	name -	The name of the function. Essential for direct binding.
    #	type -	The LLVM type signature of the function.
    #	count -	The number of defined arguments expected.
    #	vararg -
    #		Boolean indicating if this is a varargs function.
    #	arglist -
    #		Name of variable in caller holding list of LLVM value
    #		references for the actual arguments to the function. These can
    #		also be the empty string, which will cause them to be replaced
    #		with the appropriate NULL for that position's pointer type.
    #
    # Results:
    #	None.

    method @apiVerify {type count vararg arglist} {
	upvar 1 $arglist arguments
	# Because these are *much* less nasty than crashes!
	if {$vararg && [llength $arguments] < $count} {
	    return -code error -level 2 "insufficient arguments"
	} elseif {!$vararg && [llength $arguments] != $count} {
	    return -code error -level 2 "wrong number of arguments"
	}
	set i 0
	foreach expected [GetParamTypes $type] got $arguments {
	    if {$got eq ""} {
		if {$expected eq ""} {
		    set expected [Type void*]
		}
		set got [$b null $expected]
		lset arguments $i $got
	    }
	    if {[incr i]>$count} continue;	# Stop checking; varargs...
	    set got [TypeOf $got]
	    if {$got ne $expected} {
		return -code error -level 2 [format \
			"type mismatch at argument %d: expected %s but got %s" \
			$i [PrintTypeToString $expected] [PrintTypeToString $got]]
	    }
	}
    }

    # ThunkBuilder:API --
    #
    #	Bind a public Tcl API function and construct a method of the current
    #	instance of the class for generating a call to that function. Two
    #	sorts of bindings are supported, one based on the stub table, and one
    #	based on direct calls to the Tcl API functions; the choice between
    #	them is based on the presence (or absence) of the variable

    #	::LLVM::useStubs.
    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	index -	The index into the stub table. Essential for stub binding.

    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc (optional) -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
................................................................................
    #		If supplied, the default LLVM name to apply to the result of
    #		the call.
    #
    # Results:
    #	None.

    method API {index name type {postfunc ""} {defName ""}} {
	variable APIindices
	if {[info exists APIindices($index)]} {







	    return -code error \


		"double index use: $index is $APIindices($index) and $name"
	}






	set APIindices($index) $name
	tailcall my @apiDeclare \
	    stubtable $index $name $type $postfunc $defName
    }


























































    # ThunkBuilder:IntAPI --
    #
    #	Bind an internal Tcl API function and construct a method of the
    #	current instance of the class for generating a call to that function.
    #	Two sorts of bindings are supported, one based on the stub table, and
    #	one based on direct calls to the Tcl API functions; the choice between
    #	them is based on the presence (or absence) of the variable

    #	::LLVM::useStubs.
    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	index -	The index into the stub table. Essential for stub binding.

    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc (optional) -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
................................................................................
    #		If supplied, the default LLVM name to apply to the result of
    #		the call.
    #
    # Results:
    #	None.

    method IntAPI {index name type {postfunc ""} {defName ""}} {
	variable IntAPIindices
	if {[info exists IntAPIindices($index)]} {
	    return -code error \
		"double index use: $index is $IntAPIindices($index) and $name"
	}
	set IntAPIindices($index) $name
	tailcall my @apiDeclare \
	    intstubtable $index $name $type $postfunc $defName
    }

    # ThunkBuilder:OOAPI --
    #
    #	Bind a public TclOO API function and construct a method of the current
    #	instance of the class for generating a call to that function. Two
    #	sorts of bindings are supported, one based on the stub table, and one
    #	based on direct calls to the TclOO API functions; the choice between
    #	them is based on the presence (or absence) of the variable
    #	::LLVM::useStubs.
    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	index -	The index into the stub table. Essential for stub binding.
    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc (optional) -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
    #		allocated memory, etc.
    #	defName (optional) -
    #		If supplied, the default LLVM name to apply to the result of
    #		the call.
    #
    # Results:
    #	None.

    method OOAPI {index name type {postfunc ""} {defName ""}} {
	variable OOAPIindices
	if {[info exists OOAPIindices($index)]} {
	    return -code error \
		"double index use: $index is $OOAPIindices($index) and $name"
	}
	set OOAPIindices($index) $name
	tailcall my @apiDeclare \
	    oostubtable $index $name $type $postfunc $defName
    }

    # ThunkBuilder:OOIntAPI --
    #
    #	Bind a TclOO internal API function and construct a method of the
    #	current instance of the class for generating a call to that function.
    #	Two sorts of bindings are supported, one based on the stub table, and
    #	one based on direct calls to the TclOO API functions; the choice
    #	between them is based on the presence (or absence) of the variable
    #	::LLVM::useStubs.
    #
    #	A public method with the same name as the function will be added to
    #	the instance; that method generates a call of the function when
    #	called; the function also adds sanity checking of the arguments.
    #
    # Parameters:
    #	index -	The index into the stub table. Essential for stub binding.
    #	name -	The name of the function. Essential for direct binding.
    #	type -	The human-readable type signature of the function.
    #	postfunc (optional) -
    #		List of post-processing functions (names of methods of the
    #		instance of this class) to apply to the call. These are used
    #		to establish properties like whether the function retains
    #		references to the arguments, whether it is returning newly
    #		allocated memory, etc.
    #	defName (optional) -
    #		If supplied, the default LLVM name to apply to the result of
    #		the call.
    #
    # Results:
    #	None.

    method OOIntAPI {index name type {postfunc ""} {defName ""}} {
	variable OOIntAPIindices
	if {[info exists OOIntAPIindices($index)]} {
	    return -code error \
		"double index use: $index is $OOIntAPIindices($index) and $name"
	}
	set OOIntAPIindices($index) $name
	tailcall my @apiDeclare \
	    oointstubtable $index $name $type $postfunc $defName
    }

    # ThunkBuilder:APIVar --
    #
    #	Bind a variable in the module to a particular value. A public method
    #	with the same name as the variable will be added to the instance; that
    #	method generates a read of the variable when called.
................................................................................
    #	interp -
    #		The LLVM value reference to the Tcl interpreter.
    #
    # Results:
    #	None.

    method InitTclAPI {interp} {
	variable ::LLVM::useStubs
	my buildInSection API {
	    if {$useStubs} {
		set stubtable [$b dereference $interp 0 Interp.stubTable]
		set intstubtable [$b dereference \
			[$b dereference $stubtable 0 TclStubs.hooks] \
			0 TclStubHooks.tclIntStubs]
	    }
	}
	set cur [$b @cur]

	# ThunkBuilder:AssertZeroRefCount --
	#
	#	Asserts that the result of the function to which it is applied
	#	is either a Tcl_Obj reference with a reference count of zero
	#	or NULL. (Non-null-ness must be separately asserted.)
	#
	# Parameters:
	#	objPtr -
	#		The LLVM value reference to the Tcl_Obj*.
	#
	# Results:
	#	None.

	set f [$m local AssertZeroRefCount void<-Tcl_Obj*]
	params objPtr
	build {
	    $b condBr [$b nonnull $objPtr] \
		$doassert $done
	label doassert "assert.zero.reference.count"
	    set refCount [$b gep $objPtr 0 Tcl_Obj.refCount]
	    if {[catch {
		$b assume [$b eq [$b load $refCount] $0]
	    }]} {
		# Older LLVM; use this intrusive version instead
		$b store $0 $refCount
	    }
	    $b ret
	label done "null.doesnt.have.reference.counts"
	    $b ret
	}
	my closure AssertZeroRefCount objPtr {
	    if {![info exist ::env(NOASSERTS)]} {
		$b Call [$f ref] $objPtr
	    }
	}

	# ThunkBuilder:Cold --
	#
	#	Asserts that calls to the function to which it is applied are
	#	cold, i.e., on code path that it is unimportant to optimise.
	#
	#	Current implementation does NOT allow this code to apply the
	#	attribute when using a stub table. This is an LLVM limitation.
	#
	# Parameters:
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure Cold ptr {
	    upvar 1 func func
	    if {[info exists func]} {
		catch {
		    AddFunctionAttr $func cold
		}
	    }
	}

	# ThunkBuilder:NonNullResult --
	#
	#	Asserts that the result of the function to which it is applied
	#	is a a pointer that does not point to NULL.
	#
	# Parameters:
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure NonNullResult ptr {
	    upvar 1 call call
	    AddCallAttribute $call 0 nonnull
	}

	# ThunkBuilder:ApplyAttributeToPointerArguments --
	#
	#	Adds an attribute to some of arguments to the function call.
	#	Used to share implementations of some of the assertions.
	#
	# Parameters:
	#	attr -	The name of the attribute to apply.
	#	call -	The LLVM value reference to the function call.
	#	arglist -
	#		The list of all arguments to the function call
	#	indices -
	#		The argument indices that are non-null. If empty,
	#		applies to all type-correct parameters.
	#
	# Results:
	#	None.

	my closure ApplyAttributeToPointerArguments {attr call arglist indices} {
	    if {[llength $indices] == 0} {
		foreach a $arglist {
		    incr i
		    if {[GetTypeKind [TypeOf $a]] eq "LLVMPointerTypeKind"} {
			AddCallAttribute $call $i $attr
		    }
		}
	    } else {
		foreach index $indices {
		    AddCallAttribute $call $index $attr
		}
	    }
	}

	# ThunkBuilder:NonNullArgs --
	#
	#	Asserts that some of the arguments of the function to which it
	#	is applied are pointers that do not point to NULL.
	#
	# Parameters:
	#	indices... -
	#		The argument indices that are non-null. If omitted,
	#		applies to all type-correct parameters.
	#	ptr -	The LLVM value reference to the pointer. Ignored.
	#
	# Results:
	#	None.

	my closure NonNullArgs {args} {
	    upvar 1 call call args alist
	    tailcall my ApplyAttributeToPointerArguments nonnull \
		$call $alist [lrange $args 0 end-1]


	}

	# ThunkBuilder:NoAliasArgs --
	#
	#	Asserts that the arguments of the function to which it is
	#	applied (when pointers) are not aliased to each other.
	#
	# Parameters:
	#	indices... -
	#		The argument indices that are not aliased. If omitted,
	#		applies to all type-correct parameters.
	#	ptr -	The LLVM value reference to the pointer. Ignored.
	#
	# Results:
	#	None.

	my closure NoAliasArgs args {
	    upvar 1 call call args alist
	    tailcall my ApplyAttributeToPointerArguments noalias \
		$call $alist [lrange $args 0 end-1]




	}

	# ThunkBuilder:NoAliasResult --
	#
	#	Asserts that the result of the function is a pointer that does
	#	not alias any other pointer that the LLVM engine knows about.
	#
................................................................................

	# ThunkBuilder:NoCapture --
	#
	#	Asserts that the arguments of the function to which it is
	#	applied (when pointers) are not captured and used later.
	#
	# Parameters:






















	#	indices... -
	#		The argument indices that are not captured. If
	#		omitted, applies to all type-correct parameters.
	#	ptr -	The LLVM value reference to the pointer. Ignored.
	#
	# Results:
	#	None.

	my closure NoCapture args {
	    upvar 1 call call args alist

	    tailcall my ApplyAttributeToPointerArguments nocapture \
		$call $alist [lrange $args 0 end-1]


	}

	# ThunkBuilder:AssertAllocated --
	#
	#	Asserts that the result of the function to which it is
	#	applied is a newly-allocated pointer.
	#
................................................................................
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure AssertAllocated ptr {
	    if {![info exist ::env(NOASSERTS)]} {
		if {[catch {
		    $b Call [$m intrinsic lifetime.start] \
			[Const -1 int64] [$b cast(ptr) $ptr void]
		}]} {
		    $b Call [$m intrinsic lifetime.start [TypeOf $ptr]] \
			[Const -1 int64] $ptr
		}
	    }
	}

	# ThunkBuilder:AssertDeallocated --
	#
	#	Asserts that the result of the function to which it is
	#	applied is a deallocated pointer, not to be further used.
................................................................................
	#	ptr -	The LLVM value reference to the pointer.
	#
	# Results:
	#	None.

	my closure AssertDeallocated ptr {
	    if {![info exist ::env(NOASSERTS)]} {
		if {[catch {
		    $b Call [$m intrinsic lifetime.end] \
			[Const -1 int64] [$b cast(ptr) $ptr void]
		}]} {
		    $b Call [$m intrinsic lifetime.end [TypeOf $ptr]] \
			[Const -1 int64] $ptr
		}
	    }
	}

	# ThunkBuilder:ReadOnly --
	#
	#	Asserts that the function to which it is applied only reads
	#	memory, and makes no alterations.
................................................................................
	#	ptr -	Ignored.
	#
	# Results:
	#	None.

	my closure ReadOnly ptr {
	    upvar 1 func func
	    catch {
		AddFunctionAttr $func readonly
	    }
	}

	# ThunkBuilder:ReadOnlyArgs --
	#
	#	Asserts that the pointer arguments to which it is applied are
	#	only read from, not written through.
	#
................................................................................
	my closure ReadOnlyArgs args {
	    upvar 1 call call
	    set ptr [lindex $args end]
	    foreach index [lrange $args 0 end-1] {
		AddCallAttribute $call $index readonly
	    }
	}

	# ThunkBuilder:WriteOnlyArgs --
	#
	#	Asserts that the pointer arguments to which it is applied are
	#	only written through, not read from (i.e., that it is an "out"
	#	parameter").
	#
	# Parameters:
	#	indices... -
	#		The argument indices that are not read from.
	#	ptr -	The LLVM value reference to the call. Ignored.
	#
	# Results:
	#	None.
	#
	# Results:
	#	None.

	my closure WriteOnlyArgs args {
	    upvar 1 call call
	    set ptr [lindex $args end]
	    foreach index [lrange $args 0 end-1] {
		catch {
		    # Not supported on all versions of LLVM
		    AddCallAttribute $call $index writeonly
		}
	    }
	}

	# ThunkBuilder:ReadNone --
	#
	#	Asserts that the function to which it is applied does not read
	#	or write memory at all; its result depends purely on its
	#	arguments. Enables aggressive optimisations.
	#
................................................................................
	#	ptr -	Ignored.
	#
	# Results:
	#	None.

	my closure ReadNone ptr {
	    upvar 1 func func
	    catch {
		AddFunctionAttr $func readnone
	    }
	}

	# ThunkBuilder:NoReturn --
	#
	#	Asserts that the function to which it is applied does not
	#	return, that it is a total failure path. Enables aggressive
	#	optimisations.
................................................................................
	#	ptr -	Ignored.
	#
	# Results:
	#	None.

	my closure NoReturn ptr {
	    upvar 1 func func
	    catch {
		AddFunctionAttr $func noreturn
	    }
	}

	$cur build-in $b

	### Define the Tcl API types we're using that aren't in our


	### description of internal types over in struct.tcl. This is mostly
	### done by putting the opaque structure types first, followed by the
	### function types, but this rule is not universal.

	set size_t int32; # fixme: int[expr {8*$::tcl_platform(wordSize)}]
	set Unicode $Tcl_UniChar
	set Handle [Type void**]

	set AsyncProc func{void<-ClientData,Interp*,int}
	set ChannelProc func{void<-ClientData,int}
	set CloseProc func{void<-ClientData}
	set CmdDeleteProc func{void<-ClientData}
	set CmdObjTraceProc \
	    func{void<-ClientData,Interp*,int,char*,Command*,int,Tcl_Obj**}
	set CmdObjTraceDeleteProc func{void<-ClientData}
	set CmdProc func{int<-ClientData,Interp*,int,char**}
	set CmdTraceProc \
	    func{void<-ClientData,Interp*,int,char*,$CmdProc*,ClientData,int,char**}
	set CommandTraceProc func{void<-ClientData,Interp*,char*,char*,int}
	set EventCheckProc func{void<-ClientData,int}
	set EventDeleteProc func{int<-Event*,ClientData}
	set EventSetupProc func{void<-ClientData,int}
	set ExitProc func{void<-ClientData}
	set FileProc func{void<-ClientData,int}
	set FreeProc func{void<-ClientData}
	set FSUnloadFileProc func{void<-LoadHandle*}
	set IdleProc func{void<-ClientData}
	set InterpDeleteProc func{void<-ClientData,Interp*}
	set NamespaceDeleteProc func{void<-ClientData}
	set NRPostProc func{int<-ClientData*,Interp*,int}
	set ObjCmdProc func{int<-ClientData,Interp*,int,Tcl_Obj**}
	set PackageInitProc func{int<-Interp*}
	set PanicProc func{void<-char*,...}
	set ProcErrorProc func{void<-Interp*,Tcl_Obj*}
	set ResolveCmdProc func{int<-Interp*,char*,Namespace*,int,Command*}
	set ResolveCompiledVarProc \
	    func{int<-Interp*,char*,int,Namespace*,ResolvedVarInfo*}
	set ResolveVarProc func{int<-Interp*,char*,Namespace*,int,Var*}
	# TODO: Definition of Tcl_ThreadCreateProc should be different on
	# Windows, but we never actually use it so it isn't important now.
	set ThreadCreateProc func{void<-ClientData}
	set TimerProc func{void<-ClientData}
	set VarTraceProc func{char*<-ClientData,Interp*,char*,char*,int}

	### -------------------- The Tcl public API -------------------- ###

	my API 0 Tcl_PkgProvideEx int<-Interp*,char*,char*,ClientData {
	    Cold {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3 4} {NoCapture 1 2 3}
	    NoAliasArgs} "code"
	my API 1 Tcl_PkgRequireEx char*<-Interp*,char*,char*,int,void* {
	    Cold {NonNullArgs 1 2} {ReadOnlyArgs 2 3} {NoCapture 1 2 3}
	    NoAliasArgs {WriteOnlyArgs 5}} "version"
	my API 2 Tcl_Panic void<-char*,... NoReturn
	my API 3 Tcl_Alloc void*<-$size_t {
	    NoAliasResult NonNullResult} "ptr"
	my API 4 Tcl_Free void<-void* {{NonNullArgs 1}}
	my API 5 Tcl_Realloc void*<-void*,$size_t {

	    NoAliasResult NonNullResult {NonNullArgs 1}} "ptr"
	my API 6 Tcl_DbCkalloc void*<-$size_t,char*,int {
	    NoAliasResult NonNullResult {ReadOnlyArgs 2} {NonNullArgs 2}} "ptr"
	my API 7 Tcl_DbCkfree void<-void*,char*,int {
	    {ReadOnlyArgs 2} NoAliasArgs {NonNullArgs 1 2}}
	my API 8 Tcl_DbCkrealloc void*<-void*,$size_t,char*,int {
	    NoAliasResult NonNullResult {ReadOnlyArgs 3} NoAliasArgs
	    {NonNullArgs 1 3}} "ptr"
	my API 9 Tcl_CreateFileHandler void<-int,int,$FileProc*,ClientData {
	    {ReadOnlyArgs 3} NoAliasArgs}
	my API 10 Tcl_DeleteFileHandler void<-int
	my API 11 Tcl_SetTimer void<-Time* {
	    {ReadOnlyArgs 1} {NonNullArgs 1} NoCapture}
	my API 12 Tcl_Sleep void<-int
	my API 13 Tcl_WaitForEvent int<-Time* {
	    {ReadOnlyArgs 1} NoCapture} "haveEvent"
	my API 14 Tcl_AppendAllObjTypes int<-Interp*,Tcl_Obj* {
	    {NonNullArgs 1 2}} "code"
	my API 15 Tcl_AppendStringsToObj void<-Tcl_Obj*,... {
	    {NoCapture 1} {NonNullArgs 1}}
	my API 16 Tcl_AppendToObj void<-Tcl_Obj*,char*,int {
	    NoCapture {NonNullArgs 1 2} {ReadOnlyArgs 2}}
	my API 17 Tcl_ConcatObj Tcl_Obj*<-int,Tcl_Obj** {
	    NoAliasResult NoCapture NonNullResult AssertZeroRefCount
	    {ReadOnlyArgs 2}} "objPtr"
	my API 18 Tcl_ConvertToType int<-Interp*,Tcl_Obj*,ObjType* {
	    {NonNullArgs 2 3} {ReadOnlyArgs 3} {NoCapture 1}
	    NoAliasArgs} "code"
	my API 19 Tcl_DbDecrRefCount void<-Tcl_Obj*,char*,int {
	    {ReadOnlyArgs 2} {NonNullArgs 1 2} NoCapture NoAliasArgs}
	my API 20 Tcl_DbIncrRefCount void<-Tcl_Obj*,char*,int {
	    {ReadOnlyArgs 2} {NonNullArgs 1 2} NoCapture NoAliasArgs}
	my API 21 Tcl_DbIsShared int<-Tcl_Obj*,char*,int {
	    {ReadOnlyArgs 2} {NonNullArgs 1 2} NoCapture
	    NoAliasArgs} "shared"
	my API 22 Tcl_DbNewBooleanObj Tcl_Obj*<-int,char*,int {
	    {ReadOnlyArgs 2} {NonNullArgs 2} NoCapture NoAliasResult
	    NonNullResult AssertZeroRefCount} "objPtr"
	my API 23 Tcl_DbNewByteArrayObj Tcl_Obj*<-char*,int,char*,int {
	    {ReadOnlyArgs 1 3} {NonNullArgs 1 3} NoCapture NoAliasArgs
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 24 Tcl_DbNewDoubleObj Tcl_Obj*<-double,char*,int {
	    {ReadOnlyArgs 2} {NonNullArgs 2} NoCapture NoAliasResult
	    NonNullResult AssertZeroRefCount} "objPtr"
	my API 25 Tcl_DbNewListObj Tcl_Obj*<-int,Tcl_Obj**,char*,int {
	    {ReadOnlyArgs 2 3} {NonNullArgs 2 3} NoCapture NoAliasArgs
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 26 Tcl_DbNewLongObj Tcl_Obj*<-long,char*,int {
	    {ReadOnlyArgs 2} {NonNullArgs 2} NoCapture NoAliasResult
	    NonNullResult AssertZeroRefCount} "objPtr"
	my API 27 Tcl_DbNewObj Tcl_Obj*<-char*,int {
	    {ReadOnlyArgs 1} {NonNullArgs 1} NoCapture NoAliasResult
	    NonNullResult AssertZeroRefCount} "objPtr"
	my API 28 Tcl_DbNewStringObj Tcl_Obj*<-char*,int,char*,int {
	    {ReadOnlyArgs 1 3} {NonNullArgs 1 3} NoCapture NoAliasArgs
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 29 Tcl_DuplicateObj Tcl_Obj*<-Tcl_Obj* {
	    NoAliasResult NoCapture NonNullResult AssertZeroRefCount
	    {NonNullArgs 1} {ReadOnlyArgs 1}} "objPtr"
	my API 30 TclFreeObj void<-Tcl_Obj* {{NonNullArgs 1}}
	# 31 unused: Tcl_GetBoolean
	my API 32 Tcl_GetBooleanFromObj int<-Interp*,Tcl_Obj*,int* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3} {WriteOnlyArgs 3}} "code"
	my API 33 Tcl_GetByteArrayFromObj char*<-Tcl_Obj*,$size_t* {
	    NoAliasArgs NonNullResult NoCapture {NonNullArgs 1}
	    {WriteOnlyArgs 2}} "bytes"
	my closure Tcl_GetByteArray {obj} {
	    my Tcl_GetByteArrayFromObj $obj {}
	}
	oo::objdefine [self] export Tcl_GetByteArray
	# 34 unused: Tcl_GetDouble
	my API 35 Tcl_GetDoubleFromObj int<-Interp*,Tcl_Obj*,double* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3} {WriteOnlyArgs 3}} "code"
	my API 36 Tcl_GetIndexFromObj \
	    int<-Interp*,Tcl_Obj*,char**,char*,int,int* {
		NoAliasArgs {NoCapture 1 2 4 6} {NonNullArgs 2 3 6}
		{WriteOnlyArgs 6}} "code"
	# 37 unused: Tcl_GetInt
	my API 38 Tcl_GetIntFromObj int<-Interp*,Tcl_Obj*,int* {
	    NoAliasArgs NoCapture {NonNullArgs 2 3} {WriteOnlyArgs 3}} "code"
	# 39 unused: Tcl_GetLong
	my API 40 Tcl_GetObjType ObjType*<-char* {
	    NoCapture ReadOnly {NonNullArgs 1} {ReadOnlyArgs 1}} "objTypePtr"
	my API 41 Tcl_GetStringFromObj char*<-Tcl_Obj*,$size_t* {
	    NoAliasArgs NonNullResult NoCapture {NonNullArgs 1}
	    {WriteOnlyArgs 2}} "str"
	my API 42 Tcl_InvalidateStringRep void<-Tcl_Obj* {
	    NoCapture {NonNullArgs 1}}
	my API 43 Tcl_ListObjAppendList int<-Interp*,Tcl_Obj*,Tcl_Obj* {
	    NoCapture {NonNullArgs 2 3}} "code"
	my API 44 Tcl_ListObjAppendElement int<-Interp*,Tcl_Obj*,Tcl_Obj* {

	    NoAliasArgs {NonNullArgs 2 3} {NoCapture 1 2}} "code"
	my API 45 Tcl_ListObjGetElements \
	    int<-Interp*,Tcl_Obj*,int*,Tcl_Obj*** {
		NoAliasArgs NoCapture {NonNullArgs 2 3 4}
		{WriteOnlyArgs 3 4}} "code"
	my API 46 Tcl_ListObjIndex int<-Interp*,Tcl_Obj*,int,Tcl_Obj** {
	    NoAliasArgs NoCapture {NonNullArgs 2 4} {WriteOnlyArgs 4}} "code"
	my API 47 Tcl_ListObjLength int<-Interp*,Tcl_Obj*,int* {
	    NoAliasArgs NoCapture {NonNullArgs 2} {WriteOnlyArgs 3}} "code"
	my API 48 Tcl_ListObjReplace \
	    int<-Interp*,Tcl_Obj*,int,int,int,Tcl_Obj** {
		NoAliasArgs NoCapture {NonNullArgs 2 6} {ReadOnlyArgs 6}
	    } "code"
	my API 49 Tcl_NewBooleanObj Tcl_Obj*<-int {
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 50 Tcl_NewByteArrayObj Tcl_Obj*<-char*,$size_t {
	    NoAliasResult NonNullResult AssertZeroRefCount
	    NoCapture ReadOnly {NonNullArgs 1} {ReadOnlyArgs 1}} "objPtr"
	my API 51 Tcl_NewDoubleObj Tcl_Obj*<-double {
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 52 Tcl_NewIntObj Tcl_Obj*<-int {
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 53 Tcl_NewListObj Tcl_Obj*<-int,Tcl_Obj** {
	    NoAliasResult NonNullResult AssertZeroRefCount NoCapture
	    {ReadOnlyArgs 2}} "objPtr"
	my API 54 Tcl_NewLongObj Tcl_Obj*<-long {
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 55 Tcl_NewObj Tcl_Obj*<- {
	    NoAliasResult NonNullResult AssertZeroRefCount} "objPtr"
	my API 56 Tcl_NewStringObj Tcl_Obj*<-char*,$size_t {
	    NoAliasResult NonNullResult AssertZeroRefCount NoCapture
	    {ReadOnlyArgs 1}} "objPtr"
	my API 57 Tcl_SetBooleanObj void<-Tcl_Obj*,int {
	    NoCapture {NonNullArgs 1}}
	my API 58 Tcl_SetByteArrayLength char*<-Tcl_Obj*,int {
	    NoCapture {NonNullArgs 1} NonNullResult} "bytes"
	my API 59 Tcl_SetByteArrayObj void<-Tcl_Obj*,char*,int {
	    NoCapture {NonNullArgs 1 2} {ReadOnlyArgs 2}}
	my API 60 Tcl_SetDoubleObj void<-Tcl_Obj*,double {
	    NoCapture {NonNullArgs 1}}
	my API 61 Tcl_SetIntObj void<-Tcl_Obj*,int {
	    NoCapture {NonNullArgs 1}}
	my API 62 Tcl_SetListObj void<-Tcl_Obj*,int,Tcl_Obj** {
	    NoCapture {NonNullArgs 1 3} NoAliasArgs {ReadOnlyArgs 3}}
	my API 63 Tcl_SetLongObj void<-Tcl_Obj*,long {
	    NoCapture {NonNullArgs 1}}
	my API 64 Tcl_SetObjLength void<-Tcl_Obj*,int NoCapture
	my API 65 Tcl_SetStringObj void<-Tcl_Obj*,char*,int {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 2}}
	my API 66 Tcl_AddErrorInfo void<-Interp*,char* {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 2}}
	my API 67 Tcl_AddObjErrorInfo void<-Interp*,char*,int {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 2}}
	my API 68 Tcl_AllowExceptions void<-Interp* {
	    Cold NoCapture {NonNullArgs 1}}
	# 69 obsolete: Tcl_AppendElement
	my API 70 Tcl_AppendResult void<-Interp*,... {
	    NoCapture {NonNullArgs 1} {NoAliasArgs 1}}
	my API 71 Tcl_AsyncCreate AsyncHandler*<-$AsyncProc*,ClientData {
	    Cold {NonNullArgs 1} NoAliasArgs NoAliasResult
	    NonNullResult} "handler"
	my API 72 Tcl_AsyncDelete void<-AsyncHandler* Cold
	my API 73 Tcl_AsyncInvoke int<-Interp*,int {
	    Cold {NonNullArgs 1}} "code"
	my API 74 Tcl_AsyncMark void<-AsyncHandler*
	my API 75 Tcl_AsyncReady int<- {} "ready"
	my API 76 Tcl_BackgroundError void<-Interp* {
	    Cold {NonNullArgs 1}}
	my API 77 Tcl_Backslash char<-char*,int* {
	    {NonNullArgs 1} NoAliasArgs {ReadOnlyArgs 1} NoCapture
	    {WriteOnlyArgs 2}} "chr"
	my API 78 Tcl_BadChannelOption int<-Interp*,char*,char* {
	    Cold {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3} NoCapture} "code"
	my API 79 Tcl_CallWhenDeleted \
	    void<-Interp*,$InterpDeleteProc*,ClientData {
		{NonNullArgs 1 2}}
	my API 80 Tcl_CancelIdleCall void<-$IdleProc*,ClientData {
	    NoCapture NoAliasArgs {NonNullArgs 1}}
	my API 81 Tcl_Close int<-Interp*,Channel* {
	    NoCapture NoAliasArgs {NonNullArgs 2}} "code"
	my API 82 Tcl_CommandComplete int<-char* {
	    NoCapture {NonNullArgs 1} {ReadOnlyArgs 1}} "complete"
	my API 83 Tcl_Concat char*<-int,char** {
	    NoAliasResult NonNullResult NoCapture {NonNullArgs 2}
	    {ReadOnlyArgs 2}} "str"
	# 84 obsolete: Tcl_ConvertElement
	my API 85 Tcl_ConvertCountedElement int<-char*,int,char*,int {
	    NoCapture {ReadOnlyArgs 1} NoAliasArgs} "count"
	# 86 unused: Tcl_CreateAlias
	my API 87 Tcl_CreateAliasObj \
	    int<-Interp*,char*,Interp*,char*,int,Tcl_Obj** {
		NoCapture {NonNullArgs 1 2 3 4 6} {ReadOnlyArgs 2 4}} "code"
	my API 88 Tcl_CreateChannel \
	    Channel*<-ChannelType*,char*,ClientData,int {
		NoAliasResult {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 1 2}
		NonNullResult} "chan"
	my API 89 Tcl_CreateChannelHandler \
	    void<-Channel*,int,$ChannelProc*,ClientData {
		{NoCapture 1} NoAliasArgs {ReadOnlyArgs 3}}
	my API 90 Tcl_CreateCloseHandler \
	    void<-Channel*,$CloseProc*,ClientData {
		{NoCapture 1} NoAliasArgs {ReadOnlyArgs 2}}
	# 91 unused: Tcl_CreateCommand
	my API 92 Tcl_CreateEventSource \
	    void<-$EventSetupProc*,$EventCheckProc*,ClientData {
		NonNullArgs}
	my API 93 Tcl_CreateExitHandler void<-$ExitProc*,ClientData
	my API 94 Tcl_CreateInterp Interp*<- {
	    NoAliasResult NonNullResult} "interp"
	# 95 deprecated: Tcl_CreateMathFunc
	my API 96 Tcl_CreateObjCommand \

	    Command*<-Interp*,char*,$ObjCmdProc*,ClientData,$CmdDeleteProc* {
		{NonNullArgs 1 2 3} {NoCapture 2} {ReadOnlyArgs 2 3 5}
		NoAliasResult} "cmdPtr"
	my API 97 Tcl_CreateSlave Interp*<-Interp*,char*,int {
	    NoAliasResult {NonNullArgs 1 2} {ReadOnlyArgs 2}} "slaveInterp"
	my API 98 Tcl_CreateTimerHandler \
	    TimerToken*<-int,$TimerProc*,ClientData {
		{NonNullArgs 2} NoAliasResult NonNullResult} "timer"
	my API 99 Tcl_CreateTrace \
	    Trace*<-Interp*,int,$CmdTraceProc*,ClientData {
		{NoCapture 1} NoAliasResult {NonNullArgs 1 3}} "trace"
	my API 100 Tcl_DeleteAssocData void<-Interp*,char* {
	    {NonNullArgs 1 2} {ReadOnlyArgs 2} NoCapture NoAliasArgs}
	my API 101 Tcl_DeleteChannelHandler \
	    void<-Channel*,$ChannelProc*,ClientData {
		NoAliasArgs NoCapture {NonNullArgs 1 2}}
	my API 102 Tcl_DeleteCloseHandler \
	    void<-Channel*,$CloseProc*,ClientData {
		NoAliasArgs NoCapture {NonNullArgs 1 2}}
	my API 103 Tcl_DeleteCommand int<-Interp*,char* {
	    NoCapture {NonNullArgs 1 2} {ReadOnlyArgs 2}} "code"
	my API 104 Tcl_DeleteCommandFromToken int<-Interp*,Command* {
	    NoCapture {NonNullArgs 1 2}} "code"
	my API 105 Tcl_DeleteEvents void<-$EventDeleteProc*,ClientData {
	    {NonNullArgs 1}}
	my API 106 Tcl_DeleteEventSource \
	    void<-$EventSetupProc*,$EventCheckProc*,ClientData
	my API 107 Tcl_DeleteExitHandler void<-$ExitProc*,ClientData {
	    {NonNullArgs 1}}
	my API 108 Tcl_DeleteHashEntry void<-HashEntry* {
	    {NonNullArgs 1}}
	my API 109 Tcl_DeleteHashTable void<-HashTable* {
	    {NonNullArgs 1}}
	my API 110 Tcl_DeleteInterp void<-Interp* {
	    Cold {NonNullArgs 1}}
	# 111 very unlikly: Tcl_DetachPids
	my API 112 Tcl_DeleteTimerHandler void<-TimerToken* {
	    {NonNullArgs 1}}
	my API 113 Tcl_DeleteTrace void<-Interp*,Trace* {
	    {NoCapture 1} {NonNullArgs 1 2}}
	my API 114 Tcl_DontCallWhenDeleted \
	    void<-Interp*,$InterpDeleteProc*,ClientData {
		Cold {NoCapture 1} {NonNullArgs 1 2}}
	my API 115 Tcl_DoOneEvent int<-int {} "eventWasProcessed"
	my API 116 Tcl_DoWhenIdle void<-$IdleProc*,ClientData {
	    {NonNullArgs 1}}
	my API 117 Tcl_DStringAppend char*<-DString*,char*,int {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 2}
	    NonNullResult} "buffer"
	my API 118 Tcl_DStringAppendElement char*<-DString*,char* {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 2}
	    NonNullResult} "buffer"
	my API 119 Tcl_DStringEndSublist void<-DString* {
	    NoCapture {NonNullArgs 1}}
	my API 120 Tcl_DStringFree void<-DString* {
	    NoCapture {NonNullArgs 1}}
	my API 121 Tcl_DStringGetResult void<-Interp*,DString* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}}
	my API 122 Tcl_DStringInit void<-DString* {
	    NoCapture {NonNullArgs 1} {WriteOnlyArgs 1}}
	my API 123 Tcl_DStringResult void<-Interp*,DString* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}}
	my API 124 Tcl_DStringSetLength void<-DString*,int {
	    NoCapture {NonNullArgs 1}}
	my API 125 Tcl_DStringStartSublist void<-DString* {
	    NoCapture {NonNullArgs 1}}
	my closure Tcl_DStringLength {dstring} {
	    if {[TypeOf $dstring] ne [Type DString*]} {
		return -code error \
		    "can only get apply Tcl_DStringLength to a DString*"
	    }
	    $b dereference $dstring 0 DString.length
	}
	my closure Tcl_DStringValue {dstring} {
	    if {[TypeOf $dstring] ne [Type DString*]} {
		return -code error \
		    "can only get apply Tcl_DStringValue to a DString*"
	    }
	    $b dereference $dstring 0 DString.string
	}
	my API 126 Tcl_Eof int<-Channel* {
	    NoCapture {ReadOnlyArgs 1} {NonNullArgs 1}} "eof"
	my API 127 Tcl_ErrnoId char*<- {Cold NonNullResult} "id"
	my API 128 Tcl_ErrnoMsg char*<-int {
	    Cold ReadNone NonNullResult} "msg"
	# 129 unused: Tcl_Eval
	# 130 obsolete: Tcl_EvalFile
	my API 131 Tcl_EvalObj int<-Interp*,Tcl_Obj* {
	    {NoCapture 1} {NonNullArgs 1 2}} "code"
	my API 132 Tcl_EventuallyFree void<-ClientData,$FreeProc*
	my API 133 Tcl_Exit void<-int NoReturn
	my API 134 Tcl_ExposeCommand int<-Interp*,char*,char* {
	    NoCapture {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3}} "code"
	# 135 obsolete: Tcl_ExprBoolean
	# 136 unused: Tcl_ExprBooleanObj
	# 137 obsolete: Tcl_ExprDouble
	# 138 unused: Tcl_ExprDoubleObj
	# 139 obsolete: Tcl_ExprLong
	# 140 unused: Tcl_ExprLongObj
	my API 141 Tcl_ExprObj int<-Interp*,Tcl_Obj*,Tcl_Obj** {
	    {NoCapture 1 3} {NonNullArgs 1 2 3} {WriteOnlyArgs 3}} "code"
	# 142 obsolete: Tcl_ExprString
	my API 143 Tcl_Finalize void<- Cold
	# 144 unused: Tcl_FindExecutable
	my API 145 Tcl_FirstHashEntry HashEntry*<-HashTable*,HashSearch* {

	    {NonNullArgs 1 2} {NoCapture 2} {ReadOnlyArgs 1}
	    {WriteOnlyArgs 2}} "hPtr"
	my API 146 Tcl_Flush int<-Channel* {
	    {NonNullArgs 1} NoCapture} "e"
	# 147 obsolete: Tcl_FreeResult
	my API 148 Tcl_GetAlias \
	    int<-Interp*,char*,Interp**,char**,int*,char*** {
		{NonNullArgs 1 2 3 4 5 6} NoCapture NoAliasArgs
		{ReadOnlyArgs 2} {WriteOnlyArgs 3 4 5 6}} "code"
	my API 149 Tcl_GetAliasObj \
	    int<-Interp*,char*,Interp**,char**,int*,Tcl_Obj*** {
		{NonNullArgs 1 2 3 4 5 6} NoCapture NoAliasArgs
		{ReadOnlyArgs 2} {WriteOnlyArgs 3 4 5 6}} "code"
	my API 150 Tcl_GetAssocData \
	    void*<-Interp*,char*,$InterpDeleteProc** {
		NoCapture NoAliasArgs {NonNullArgs 1 2}
		{ReadOnlyArgs 1 2} {WriteOnlyArgs 3}} "assoc"
	my API 151 Tcl_GetChannel Channel*<-Interp*,char*,int* {
	    {NonNullArgs 1 2} NoCapture NoAliasArgs {ReadOnlyArgs 2}
	    {WriteOnlyArgs 3}} "chan"
	my API 152 Tcl_GetChannelBufferSize int<-Channel* {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}} "size"
	my API 153 Tcl_GetChannelHandle int<-Channel*,int,ClientData* {
	    {NonNullArgs 1 3} NoCapture {ReadOnlyArgs 1}
	    {WriteOnlyArgs 3}} "code"
	my API 154 Tcl_GetChannelInstanceData ClientData<-Channel* {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}} "instanceData"
	my API 155 Tcl_GetChannelMode int<-Channel* {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}} "mode"
	my API 156 Tcl_GetChannelName char*<-Channel* {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}
	    NonNullResult} "name"
	my API 157 Tcl_GetChannelOption int<-Interp*,Channel*,char*,DString* {
	    {NonNullArgs 1 2 4} NoCapture {ReadOnlyArgs 3}} "code"
	my API 158 Tcl_GetChannelType ChannelType*<-Channel* {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}
	    NonNullResult} "type"
	my API 159 Tcl_GetCommandInfo int<-Interp*,char*,CmdInfo* {
	    Cold {NonNullArgs 1 2 3} NoCapture {ReadOnlyArgs 2}
	    {WriteOnlyArgs 3}} "code"
	my API 160 Tcl_GetCommandName char*<-Interp*,Command* {
	    {NonNullArgs 1 2} NoCapture {ReadOnlyArgs 1 2}} "name"
	my API 161 Tcl_GetErrno int<- Cold "errno"
	my API 162 Tcl_GetHostName char*<- {} "hostname"
	my API 163 Tcl_GetInterpPath int<-Interp*,Interp* {
	    {NonNullArgs 1 2} NoCapture {ReadOnlyArgs 2}} "code"
	my API 164 Tcl_GetMaster Interp*<-Interp* {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}} "master"
	my API 165 Tcl_GetNameOfExecutable char*<- {} "exename"
	my API 166 Tcl_GetObjResult Tcl_Obj*<-Interp* {
	    NoCapture NonNullResult} "objPtr"
	# 167 unused: Tcl_GetOpenFile
	# 168 obsolete: Tcl_GetPathType
	my API 169 Tcl_Gets int<-Channel*,DString* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}} "numBytes"
	my API 170 Tcl_GetsObj int<-Channel*,Tcl_Obj* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}} "numBytes"
	# 171 unused: Tcl_GetServiceMode
	my API 172 Tcl_GetSlave Interp*<-Interp,char* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2} {ReadOnlyArgs 2}} "slave"
	my API 173 Tcl_GetStdChannel Channel*<-int {
	    NonNullResult} "chan"
	# 174 obsolete: Tcl_GetStringResult
	# 175 unused: Tcl_GetVar
	# 176 unused: Tcl_GetVar2
	# 177 obsolete: Tcl_GlobalEval
	# 178 obsolete: Tcl_GlobalEvalObj
	my API 179 Tcl_HideCommand int<-Interp*,char*,char* {
	    Cold NoCapture {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3}} "code"
	# 180 unused: Tcl_Init
	my API 181 Tcl_InitHashTable void<-HashTable*,int {
	    NoCapture {NonNullArgs 1} {WriteOnlyArgs 1}}
	my API 182 Tcl_InputBlocked int<-Channel* {
	    NoCapture {NonNullArgs 1} {ReadOnlyArgs 1}} "blocked"
	my API 183 Tcl_InputBuffered int<-Channel* {
	    NoCapture {NonNullArgs 1} {ReadOnlyArgs 1}} "buffered"
	my API 184 Tcl_InterpDeleted int<-Interp* {
	    NoCapture {NonNullArgs 1} {ReadOnlyArgs 1}} "deleted"
	my API 185 Tcl_IsSafe int<-Interp* {
	    NoCapture {NonNullArgs 1} {ReadOnlyArgs 1}} "safe"
	# 186 obsolete: Tcl_JoinPath
	my API 187 Tcl_LinkVar int<-Interp*,char*,void*,int {
	    {NoCapture 1 2} {NonNullArgs 1 2 3} {ReadOnlyArgs 2}} "code"

	# 188 unused: Tcl_MainLoop
	my API 189 Tcl_MakeFileChannel Channel*<-ClientData,int {
	    NoAliasResult NonNullResult} "chan"
	my API 190 Tcl_MakeSafe int<-Interp* {
	    Cold {NonNullArgs 1} NoCapture} "code"
	# 191 unused: Tcl_MakeTcpClientChannel
	my API 192 Tcl_Merge char*<-int,char** {
	    NoAliasResult NonNullResult {NonNullArgs 2} {ReadOnlyArgs 2}
	    NoCapture} "str"
	my API 193 Tcl_NextHashEntry HashEntry*<-HashSearch* {
	    {NonNullArgs 1} NoCapture} "hPtr"
	my API 194 Tcl_NotifyChannel void<-Channel*,int {
	    {NonNullArgs 1} NoCapture}
	my API 195 Tcl_ObjGetVar2 Tcl_Obj*<-Interp*,Tcl_Obj*,Tcl_Obj*,int {

	    NoCapture {NonNullArgs 1 2}} "objPtr"
	my API 196 Tcl_ObjSetVar2 \
	    Tcl_Obj*<-Interp*,Tcl_Obj*,Tcl_Obj*,Tcl_Obj*,int {
		{NoCapture 1 2} {NonNullArgs 1 2 4}} "objPtr"
	my API 197 Tcl_OpenCommandChannel Channel*<-Interp*,int,char**,int {
	    NoCapture {NonNullArgs 1 3} NoAliasArgs} "chan"
	# 198 obsolete: Tcl_OpenFileChannel
	# 199 unused: Tcl_OpenTcpClient
	# 200 unused: Tcl_OpenTcpServer
	my API 201 Tcl_Preserve void<-ClientData {{NonNullArgs 1}}
	# 202 obsolete: Tcl_PrintDouble
	my API 203 Tcl_PutEnv int<-char* {
	    {ReadOnlyArgs 1} NoCapture} "code"
	my API 204 Tcl_PosixError char*<-Interp* {
	    Cold NoCapture {NonNullArgs 1} NonNullResult} "msg"
	my API 205 Tcl_QueueEvent void<-Event*,int {
	    {NonNullArgs 1}}
	my API 206 Tcl_Read int<-Channel*,char*,int {
	    NoCapture NoAliasArgs {NonNullArgs 1 2} {WriteOnlyArgs 2}
	} "numBytes"
	# 207 unused: Tcl_ReapDetachedProcs
	# 208 obsolete: Tcl_RecordAndEval
	# 209 unused: Tcl_RecordAndEvalObj
	my API 210 Tcl_RegisterChannel void<-Interp*,Channel* {
	    {NoCapture 1} {NonNullArgs 1 2} NoAliasArgs}
	# 211 obsolete: Tcl_RegisterObjType
	# 212 obsolete: Tcl_RegExpCompile
	# 213 obsolete: Tcl_RegExpExec
	# 214 obsolete: Tcl_RegExpMatch
	my API 215 Tcl_RegExpRange void<-RegExp*,int,char**,char** {
	    NoCapture {NonNullArgs 1 3 4} NoAliasArgs {WriteOnlyArgs 3 4}}
	my API 216 Tcl_Release void<-ClientData {{NonNullArgs 1}}
	my API 217 Tcl_ResetResult void<-Interp* {
	    NoCapture {NonNullArgs 1}}
	# 218 obsolete: Tcl_ScanElement
	my API 219 Tcl_ScanCountedElement int<-char*,int,int* {
	    {NonNullArgs 1 3} NoAliasArgs NoCapture {WriteOnlyArgs 3}} "code"
	# 220 obsolete: Tcl_SeekOld
	# 221 unused: Tcl_ServiceAll
	# 222 unused: Tcl_ServiceEvent
	my API 223 Tcl_SetAssocData \
	    void<-Interp*,char*,$InterpDeleteProc*,void* {
		NoAliasArgs {NoCapture 1 2} {NonNullArgs 1 2}
		{ReadOnlyArgs 2 3}}
	my API 224 Tcl_SetChannelBufferSize void<-Channel*,int {
	    {NonNullArgs 1} NoCapture}
	my API 225 Tcl_SetChannelOption int<-Interp*,Channel*,char*,char* {
	    {NonNullArgs 1 2 3 4} NoCapture {ReadOnlyArgs 3 4}} "code"
	my API 226 Tcl_SetCommandInfo int<-Interp*,char*,CmdInfo* {
	    Cold {NonNullArgs 1 2 3} NoCapture {ReadOnlyArgs 2 3}} "code"
	my API 227 Tcl_SetErrno void<-int Cold
	my API 228 Tcl_SetErrorCode void<-Interp*,... {
	    Cold NoCapture {NonNullArgs 1}}
	# 229 unused: Tcl_SetMaxBlockTime
	my API 230 Tcl_SetPanicProc void<-$PanicProc* Cold
	my API 231 Tcl_SetRecursionLimit int<-Interp*,int {
	    Cold {NonNullArgs 1} NoCapture} "code"
	# 232 unused: Tcl_SetResult
	# 233 unused: Tcl_SetServiceMode
	my API 234 Tcl_SetObjErrorCode void<-Interp*,Tcl_Obj* {
	    Cold NoAliasArgs {NonNullArgs 1 2} {NoCapture 1}}
	my API 235 Tcl_SetObjResult void<-Interp*,Tcl_Obj* {
	    NoAliasArgs {NonNullArgs 1 2} {NoCapture 1}}
	# 236 unused: Tcl_SetStdChannel
	# 237 obsolete: Tcl_SetVar
	# 238 obsolete: Tcl_SetVar2
	my API 239 Tcl_SignalId char*<-int {
	    Cold ReadOnly NonNullResult} "id"
	my API 240 Tcl_SignalMsg char*<-int {
	    Cold ReadOnly NonNullResult} "msg"
	# 241 unused: Tcl_SourceRCFile
	my API 242 Tcl_SplitList int<-Interp*,char*,int*,char*** {
	    NoAliasArgs {ReadOnlyArgs 2} {NonNullArgs 1 2 3 4}
	    NoCapture {WriteOnlyArgs 3 4}} "code"
	# 243 obsolete: Tcl_SplitPath
	my API 244 Tcl_StaticPackage \
	    void<-Interp*,char*,$PackageInitProc*,$PackageInitProc* {
		Cold {NoCapture 1 2} {ReadOnlyArgs 2} {NoAliasArgs 1 2}
		{NonNullArgs 1 2}}
	my API 245 Tcl_StringMatch int<-char*,char* {
	    NoCapture {ReadOnlyArgs 1 2} {NonNullArgs 1 2}} "matched"
	# 246 obsolete: Tcl_TellOld
	# 247 unused: Tcl_TraceVar
	# 248 unused: Tcl_TraceVar2
	my API 249 Tcl_TranslateFileName char*<-Interp*,char*,DString* {
	    NoCapture NoAliasArgs {ReadOnlyArgs 2}
	    {NonNullArgs 1 2 3}} "fileName"
	my API 250 Tcl_Ungets int<-Channel*,char*,int,int {
	    NoCapture NoAliasArgs} "len"
	my API 251 Tcl_UnlinkVar void<-Interp*,char* {
	    NoCapture NoAliasArgs {ReadOnlyArgs 2} {NonNullArgs 1 2}}
	my API 252 Tcl_UnregisterChannel int<-Interp*,Channel* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}} "code"
	# 253 unused: Tcl_UnsetVar
	my API 254 Tcl_UnsetVar2 int<-Interp*,char*,char*,int {
	    NoCapture {NonNullArgs 1 2} {ReadOnlyArgs 2 3}} "code"
	# 255 unused: Tcl_UntraceVar
	# 256 unused: Tcl_UntraceVar2
	my API 257 Tcl_UpdateLinkedVar void<-Interp*,char* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2} {ReadOnlyArgs 2}}
	# 258 unused: Tcl_UpVar
	my API 259 Tcl_UpVar2 int<-Interp*,char*,char*,char*,char*,int {
	    NoCapture {NonNullArgs 1 2 3 5} {ReadOnlyArgs 2 3 4 5}} "code"
	# 260 obsolete: Tcl_VarEval
	# 261 unused: Tcl_VarTraceInfo
	my API 262 Tcl_VarTraceInfo2 \
	    ClientData<-Interp*,char*,char*,int,$VarTraceProc*,ClientData {
		{NonNullArgs 1 2 5} {ReadOnlyArgs 2 3 5 6}} "clientData"
	my API 263 Tcl_Write int<-Channel*,char*,int {
	    NoAliasArgs {ReadOnlyArgs 2} NoCapture} "numBytes"
	my API 264 Tcl_WrongNumArgs void<-Interp*,int,Tcl_Obj**,char* {
	    Cold NoCapture NoAliasArgs {NonNullArgs 1} {ReadOnlyArgs 3 4}}
	# 265 unused: Tcl_DumpActiveMemory
	# 266 unused: Tcl_ValidateAllMemory
	# 267 unused: Tcl_AppendResultVA
	# 268 unused: Tcl_AppendStringsToObjVA
	my API 269 Tcl_HashStats char*<-HashTable* {
	    Cold NoCapture {NonNullArgs 1} {ReadOnlyArgs 1}} "description"
	my API 270 Tcl_ParseVar char*<-Interp*,char*,char** {
	    NoCapture {NonNullArgs 1 2 3} {ReadOnlyArgs 2} {WriteOnlyArgs 3}
	} "value"
	my API 271 Tcl_PkgPresent char*<-Interp*,char*,char*,int {
	    NoCapture {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3}} "version"
	my API 272 Tcl_PkgPresentEx char*<-Interp*,char*,char*,int,void* {
	    NoCapture {NonNullArgs 1 2 3} {ReadOnlyArgs 2 3}
	    {NoAliasArgs 1 5}} "version"
	my API 273 Tcl_PkgProvide int<-Interp*,char*,char* {
	    {NoAliasArgs 1} {ReadOnlyArgs 2 3} {NonNullArgs 1 2 3}
	    NoCapture} "code"
	# 274 obsolete: Tcl_PkgRequire
	# 275 unused: Tcl_SetErrorCodeVA
	# 276 unused: Tcl_VarEvalVA
	# 277 unused: Tcl_WaitPid
	# 278 unused: Tcl_PanicVA
	my API 279 Tcl_GetVersion void<-int*,int*,int*,int* {
	    NoCapture NoAliasArgs {WriteOnlyArgs 1 2 3 4}}
	# 280 unused: Tcl_InitMemory
	my API 281 Tcl_StackChannel \
	    Channel*<-Interp*,ChannelType*,ClientData,int,Channel* {
		{NoCapture 1} {ReadOnlyArgs 2} {NonNullArgs 1 2 5}} "chan"
	my API 282 Tcl_UnstackChannel int<-Interp*,Channel* {
	    {NonNullArgs 1 2} NoCapture} "code"
	my API 283 Tcl_GetStackedChannel Channel*<-Channel* {
	    {NonNullArgs 1} NoCapture} "chan"
	# 284 unused: Tcl_SetMainLoop
	# 285 reserved
	my API 286 Tcl_AppendObjToObj void<-Tcl_Obj*,Tcl_Obj* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2}}
	# 287 unused: Tcl_CreateEncoding
	my API 288 Tcl_CreateThreadExitHandler void<-$ExitProc*,ClientData {
	    {NonNullArgs 1}}
	my API 289 Tcl_DeleteThreadExitHandler void<-$ExitProc*,ClientData {
	    Cold {NonNullArgs 1}}
	# 290 obsolete: Tcl_DiscardResult
	# 291 unused: Tcl_EvalEx
	my API 292 Tcl_EvalObjv int<-Interp*,int,Tcl_Obj**,int {
	    NoCapture NoAliasArgs {NonNullArgs 1 3} {ReadOnlyArgs 3}} "code"
	my API 293 Tcl_EvalObjEx int<-Interp*,Tcl_Obj*,int {
	    {NonNullArgs 1 2} NoAliasArgs {NoCapture 1}} "code"
	my API 294 Tcl_ExitThread void<-int NoReturn
	# 295 unused (I hope!): Tcl_ExternalToUtf
	my API 296 Tcl_ExternalToUtfDString \
	    char*<-Encoding*,char*,int,DString* {
		{NonNullArgs 1 2 4} NoAliasArgs NonNullResult NoCapture
		{ReadOnlyArgs 1 2}} "string"
	my API 297 Tcl_FinalizeThread void<- Cold
	# 298 unused: Tcl_FinalizeNotifier
	# 299 unused: Tcl_FreeEncoding
	my API 300 Tcl_GetCurrentThread ThreadId*<- {} "tid"
	my API 301 Tcl_GetEncoding Encoding*<-Interp*,char* {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs {ReadOnlyArgs 2}} "encoding"
	my API 302 Tcl_GetEncodingName char*<-Encoding* {
	    NoCapture {NonNullArgs 1} ReadOnly NonNullResult} "name"
	# 303 unused: Tcl_GetEncodingNames
	my API 304 Tcl_GetIndexFromObjStruct \
	    int<-Interp*,Tcl_Obj*,char*,int,char*,int,int* {
		NoAliasArgs {NoCapture 1 2 5 7} {NonNullArgs 2 3 7}
		{WriteOnlyArgs 7}} "code"
	my API 305 Tcl_GetThreadData void*<-ThreadDataKey*,int {
	    NonNullResult {NonNullArgs 1}} "threadDataPtr"
	my API 306 Tcl_GetVar2Ex Tcl_Obj*<-Interp*,char*,char*,int {
	    {NonNullArgs 1 2} {NoCapture 1 2 3}} "objPtr"
	# 307 unused: Tcl_InitNotifier
	my API 308 Tcl_MutexLock void<-Mutex* {{NonNullArgs 1}}
	my API 309 Tcl_MutexUnlock void<-Mutex* {{NonNullArgs 1}}
	my API 310 Tcl_ConditionNotify void<-Condition* {{NonNullArgs 1}}
	my API 311 Tcl_ConditionWait void<-Condition*,Mutex*,Time* {
	    {NoCapture 3}}
	my API 312 Tcl_NumUtfChars int<-char*,int {
	    {NonNullArgs 1} NoCapture {ReadOnlyArgs 1}} "numChars"
	my API 313 Tcl_ReadChars int<-Channel*,Tcl_Obj*,int,int {
	    {NonNullArgs 1 2} NoCapture NoAliasArgs} "numChars"
	# 314 obsolete: Tcl_RestoreResult
	# 315 obsolete: Tcl_SaveResult
	# 316 unused: Tcl_SetSystemEncoding
	my API 317 Tcl_SetVar2Ex Tcl_Obj*<-Interp*,char*,char*,Tcl_Obj*,int {
	    {NonNullArgs 1 2 4} {NoCapture 1 2 3} {ReadOnlyArgs 2 3}
	    {NoAliasArgs 1 4}} "objPtr"
	my API 318 Tcl_ThreadAlert void<-ThreadId* {
	    {NonNullArgs 1} NoCapture}
	my API 319 Tcl_ThreadQueueEvent void<-ThreadId*,Event*,int {
	    {NonNullArgs 1 2} {NoCapture 1}}
	my API 320 Tcl_UniCharAtIndex $Unicode<-char*,int {
	    NoCapture ReadOnly {ReadOnlyArgs 1} {NonNullArgs 1}} "ch"
	my API 321 Tcl_UniCharToLower $Unicode<-int ReadNone "ch"
	my API 322 Tcl_UniCharToTitle $Unicode<-int ReadNone "ch"
	my API 323 Tcl_UniCharToUpper $Unicode<-int ReadNone "ch"
	my API 324 Tcl_UniCharToUtf int<-int,char* {
	    NoCapture {NonNullArgs 2} {WriteOnlyArgs 2}} "len"
	my API 325 Tcl_UtfAtIndex char*<-char*,int {
	    NoCapture {NonNullArgs 1} ReadOnly} "str"
	my API 326 Tcl_UtfCharComplete int<-char*,int {
	    NoCapture {NonNullArgs 1} ReadOnly} "complete"
	my API 327 Tcl_UtfBackslash int<-char*,int*,char* {
	    NoCapture {NonNullArgs 1 3} {ReadOnlyArgs 1}
	    {WriteOnlyArgs 2 3}} "numBytes"
	my API 328 Tcl_UtfFindFirst char*<-char*,int {
	    NoCapture {NonNullArgs 1} ReadOnly} "chPtr"
	my API 329 Tcl_UtfFindLast char*<-char*,int {
	    NoCapture {NonNullArgs 1} ReadOnly} "chPtr"
	my API 330 Tcl_UtfNext char*<-char* {
	    NoCapture ReadOnly NonNullResult {NonNullArgs 1}
	    {ReadOnlyArgs 1}} "chPtr"
	my API 331 Tcl_UtfPrev char*<-char*,char* {
	    NoCapture ReadOnly NonNullResult {NonNullArgs 1 2}
	    {ReadOnlyArgs 1 2}} "chPtr"
	# 332 unused (I hope!): Tcl_UtfToExternal
	my API 333 Tcl_UtfToExternalDString \
	    char*<-Encoding*,char*,int,DString* {
		{NonNullArgs 1 2 4} NoAliasArgs NonNullResult NoCapture
		{ReadOnlyArgs 1 2}} "string"
	my API 334 Tcl_UtfToLower int<-char* {
	    NoCapture {NonNullArgs 1}} "len"
	my API 335 Tcl_UtfToTitle int<-char* {
	    NoCapture  {NonNullArgs 1}} "len"
	my API 336 Tcl_UtfToUniChar int<-char*,$Unicode* {
	    NoCapture NoAliasArgs {NonNullArgs 1 2} {ReadOnlyArgs 1}
	    {WriteOnlyArgs 2}} "len"
	my API 337 Tcl_UtfToUpper int<-char* {
	    NoCapture {NonNullArgs 1}} "len"
	my API 338 Tcl_WriteChars int<-Channel*,char*,int {
	    NoCapture {NonNullArgs 1 2} NoAliasArgs