-
Notifications
You must be signed in to change notification settings - Fork 71
/
CCodeGenerator.class.st
5268 lines (4530 loc) · 176 KB
/
CCodeGenerator.class.st
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"
This class oversees the translation of a subset of Smalltalk to C, allowing the comforts of Smalltalk during development and the efficiency and portability of C for the resulting interpreter.
See VMMaker for more useful info
# toto
"
Class {
#name : #CCodeGenerator,
#superclass : #Object,
#instVars : [
'structClasses',
'translationDict',
'asArgumentTranslationDict',
'inlineList',
'constants',
'variables',
'variableDeclarations',
'scopeStack',
'methods',
'macros',
'apiMethods',
'apiVariables',
'kernelReturnTypes',
'headerFiles',
'globalVariableUsage',
'useSymbolicConstants',
'generateDeadCode',
'requiredSelectors',
'previousCommentMarksInlining',
'previousCommenter',
'logger',
'suppressAsmLabels',
'asmLabelCounts',
'pools',
'selectorTranslations',
'staticallyResolvedPolymorphicReceivers',
'optionsDictionary',
'breakSrcInlineSelectors',
'breakDestInlineSelectors',
'breakOnInline',
'environment',
'compileTimeOptions',
'stopOnErrors',
'castTranslationDict',
'castAsArgumentTranslationDict',
'wordSize'
],
#classVars : [
'NoRegParmsInAssertVMs'
],
#category : #'Slang-CodeGeneration'
}
{ #category : #'class initialization' }
CCodeGenerator class >> initialize [
"CCodeGenerator initialize"
NoRegParmsInAssertVMs := true
"If NoRegParmsInAssertVMs is true the generator spits out an attribute turning off register parameters for static functions in the Assert and Debug VMs which makes debugging easier, since all functions can be safely called from gdb. One might hope that -mregparm=0 would work but at least on Mac OS X's gcc 4.2.1 it does not and hence we have to use a per funciton attribute. Sigh..."
]
{ #category : #testing }
CCodeGenerator class >> isVarargsSelector: aRBSelectorNode [
^aRBSelectorNode value endsWith: 'printf:'
]
{ #category : #'C code generator' }
CCodeGenerator class >> monticelloDescriptionFor: aClass [
"Answer a suitable Monticello package stamp to include in the header."
| pkgInfo pkg uuid |
pkgInfo := aClass package.
pkg := MCWorkingCopy allManagers detect: [:ea| ea packageName = pkgInfo packageName].
pkg ancestry ancestors isEmpty ifFalse:
[uuid := pkg ancestry ancestors first id].
^aClass name, (pkg modified ifTrue: [' * '] ifFalse: [' ']), pkg ancestry ancestorString, ' uuid: ', uuid asString
]
{ #category : #'C translation support' }
CCodeGenerator class >> reservedWords [
^#( 'auto'
'break'
'case' 'char' 'const' 'continue'
'default' 'do' 'double'
'else' "'entry' obsolete" 'enum' 'extern'
'float' 'for'
'goto'
'if' 'int'
'long'
'register' 'return'
'short' 'signed' 'sizeof' 'static' 'struct' 'switch'
'typedef'
'union' 'unsigned'
'void' 'volatile'
'while')
]
{ #category : #'C code generator' }
CCodeGenerator class >> shortMonticelloDescriptionForClass: aClass [
"Answer a suitable Monticello package stamp to include in a moduleName."
| mdesc |
mdesc := [self monticelloDescriptionFor: aClass]
on: Error
do: [:ex| ^' ', Date today asString].
^mdesc copyFrom: 1 to: (mdesc indexOfSubCollection: ' uuid:') - 1
]
{ #category : #accessing }
CCodeGenerator >> abortBlock [
^ nil
]
{ #category : #public }
CCodeGenerator >> addAllClassVarsFor: aClass [
"Add the class variables for the given class (and its superclasses) to the code base as constants."
| allClasses |
allClasses := aClass withAllSuperclasses.
allClasses do: [:c | self addClassVarsFor: c].
]
{ #category : #public }
CCodeGenerator >> addClass: aClass [
"Add the variables and methods of the given class to the code base."
self addClass: aClass silently: false
]
{ #category : #public }
CCodeGenerator >> addClass: aClass silently: silentlyBoolean [
"Add the variables and methods of the given class to the code base."
aClass prepareToBeAddedToCodeGenerator: self.
self checkClassForNameConflicts: aClass.
self addClassVarsFor: aClass.
"ikp..."
self addPoolVarsFor: aClass.
(aClass inheritsFrom: SlangStructType) ifFalse:
[variables addAll: (self instVarNamesForClass: aClass)].
self retainMethods: (aClass requiredMethodNames: self options).
silentlyBoolean ifTrue: [
aClass selectors do: [:sel | self addMethodFor: aClass selector: sel ].
aClass declareCVarsIn: self.
^ self
].
"Not silent"
UIManager default
displayProgress: 'Adding Class ' , aClass name , '...'
from: 0
to: aClass selectors size
during:
[:bar |
aClass selectors doWithIndex:
[:sel :i |
bar value: i.
self addMethodFor: aClass selector: sel]].
aClass declareCVarsIn: self
]
{ #category : #public }
CCodeGenerator >> addClassVarsFor: aClass [
"Add the class variables for the given class to the code base as constants."
aClass classPool associationsDo:
[:assoc | self addConstantForBinding: assoc]
]
{ #category : #public }
CCodeGenerator >> addConstantForBinding: variableBinding [
"Add the pool variable to the code base as a constant."
| node val |
val := variableBinding value.
node := (useSymbolicConstants and: [self isCLiteral: val])
ifTrue:[TDefineNode new
setName: variableBinding key
value: variableBinding value]
ifFalse:[TConstantNode value: variableBinding value].
constants at: variableBinding key put: node
]
{ #category : #public }
CCodeGenerator >> addHeaderFile: aString [
"Add a header file. As a hack we allow C preprocessor defs such as #ifdef"
self assert: (('"<#' includes: aString first) or: [(aString last: 2) = '_H']).
(aString first ~= $#
and: [headerFiles includes: aString]) ifTrue:
[logger nextPutAll: 'warning, attempt to include ', aString, ' a second time'; cr; flush.
^self].
headerFiles addLast: aString
]
{ #category : #public }
CCodeGenerator >> addHeaderFileFirst: aString [
"Add a header file to the front of the sequence."
self assert: (('"<' includes: aString first) and: ['">' includes: aString last]).
self assert: (headerFiles includes: aString) not.
headerFiles addFirst: aString
]
{ #category : #public }
CCodeGenerator >> addMacro: aString for: selector [
"Add a macro. aString must be the macro arguments and body without the leading #define or name"
macros at: selector put: aString
]
{ #category : #utilities }
CCodeGenerator >> addMethod: aTMethod [
"Add the given method to the code base and answer it.
Only allow duplicate definitions for struct accessors, since we don't actually
generate code for these methods and hence the conflict doesn't matter.
Allow subclasses to redefine methods (Smalltalk has inheritance after all)."
(methods at: aTMethod selector ifAbsent: []) ifNotNil:
[:conflict |
aTMethod compiledMethod isSubclassResponsibility ifTrue:
[^nil].
(conflict isStructAccessor
and: [aTMethod isStructAccessor
and: [conflict compiledMethod decompileString = aTMethod compiledMethod decompileString]]) ifTrue:
[^nil].
((aTMethod definingClass inheritsFrom: conflict definingClass)
or: [(aTMethod compiledMethod pragmaAt: #option:) notNil]) ifFalse:
[self error: 'Method name conflict: ', aTMethod selector]].
^methods at: aTMethod selector put: aTMethod
]
{ #category : #utilities }
CCodeGenerator >> addMethodFor: aClass selector: selector [
"Add the given method to the code base and answer its translation
or nil if it shouldn't be translated."
| method tmethod |
method := aClass compiledMethodAt: selector.
(method pragmaAt: #doNotGenerate) ifNotNil:
["only remove a previous method if this one overrides it, i.e. this is a subclass method.
If the existing method is in a different hierarchy this method must be merely a redeirect."
(methods at: selector ifAbsent: []) ifNotNil:
[:tm|
(aClass includesBehavior: tm definingClass) ifTrue:
[self removeMethodForSelector: selector]].
^nil].
method isSubclassResponsibility ifTrue:
[^nil].
(self shouldIncludeMethodFor: aClass selector: selector) ifFalse:
[^nil].
tmethod := self compileToTMethodSelector: selector in: aClass.
"Even though we exclude initialize methods, we must consider their
global variable usage, otherwise globals may be incorrectly localized."
selector == #initialize ifTrue:
[self checkForGlobalUsage: (tmethod allReferencedVariablesUsing: self) in: tmethod.
^nil].
self addMethod: tmethod.
"If the method has a macro then add the macro. But keep the method
for analysis purposes (e.g. its variable accesses)."
(method pragmaAt: #cmacro:) ifNotNil:
[:pragma|
self addMacro: (pragma argumentAt: 1) for: selector.
(inlineList includes: selector) ifTrue:
[inlineList := inlineList copyWithout: selector]].
(method pragmaAt: #cmacro) ifNotNil:
[:pragma| | literal | "Method should be just foo ^const"
self assert: (method numArgs = 0 and: [method numLiterals = 3 or: [method isQuick]]).
literal := method isQuick
ifTrue: [method decompile quickMethodReturnLiteral]
ifFalse: [method literalAt: 1].
self addMacro: '() ', (method isReturnField
ifTrue: [literal]
ifFalse: [self cLiteralFor: literal value name: method selector]) for: selector.
(inlineList includes: selector) ifTrue:
[inlineList := inlineList copyWithout: selector]].
^tmethod
]
{ #category : #public }
CCodeGenerator >> addMethodsForTranslatedPrimitives: classAndSelectorList [
| verbose |
verbose := false.
classAndSelectorList do:
[:classAndSelector | | aClass selector meth |
aClass := Smalltalk at: classAndSelector first.
selector := classAndSelector last.
self addAllClassVarsFor: aClass.
"compile the method source and convert to a suitable translation method.
find the method in either the class or the metaclass"
meth := self
compileToTMethodSelector: selector
in: ((aClass includesSelector: selector)
ifTrue: [aClass]
ifFalse: [aClass class]).
meth primitive > 0 ifTrue:
[meth preparePrimitiveName].
meth replaceSizeMessages.
self addMethod: meth].
self prepareMethods
]
{ #category : #public }
CCodeGenerator >> addPoolVarsFor: aClass [
"Add the pool variables for the given class to the code base as constants."
(aClass sharedPools reject: [:pool| pools includes: pool]) do:
[:pool |
pools add: pool.
pool bindingsDo:
[:binding |
self addConstantForBinding: binding]]
]
{ #category : #public }
CCodeGenerator >> addSelectorTranslation: aSelector to: aString [
selectorTranslations at: aSelector asSymbol put: aString
]
{ #category : #public }
CCodeGenerator >> addStructClass: aClass [
"Add the non-accessor methods of the given struct class to the code base."
^ self addStructClass: aClass silently: false
]
{ #category : #public }
CCodeGenerator >> addStructClass: aClass silently: silentlyBoolean [
"Add the non-accessor methods of the given struct class to the code base."
aClass prepareToBeAddedToCodeGenerator: self.
self addClassVarsFor: aClass.
self addPoolVarsFor: aClass.
self retainMethods: (aClass requiredMethodNames: self options).
"Silent version"
silentlyBoolean ifTrue: [
aClass selectors do: [:sel | self addStructMethodFor: aClass selector: sel ].
aClass declareCVarsIn: self.
^ self
].
"Non silent version"
UIManager default
displayProgress: 'Adding Class ' , aClass name , '...'
from: 0
to: aClass selectors size
during:
[:bar |
aClass selectors doWithIndex:
[:sel :i |
bar value: i.
self addStructMethodFor: aClass selector: sel]].
aClass declareCVarsIn: self
]
{ #category : #accessing }
CCodeGenerator >> addStructClasses: classes [
"Add the struct classes and save them for emitCTypesOn: later."
structClasses := classes.
structClasses do:
[:structClass|
(structClass withAllSuperclasses copyUpTo: structClass baseStructClass) do:
[:structClassOrSuperclass|
self addStructClass: structClassOrSuperclass]]
]
{ #category : #accessing }
CCodeGenerator >> addStructClasses: classes silently: aSilentlyBoolean [
"Add the struct classes and save them for emitCTypesOn: later."
structClasses := classes.
structClasses do:
[:structClass|
(structClass withAllSuperclasses copyUpTo: SlangStructType) do:
[:structClassOrSuperclass|
self addStructClass: structClassOrSuperclass silently: aSilentlyBoolean ]]
]
{ #category : #utilities }
CCodeGenerator >> addStructMethodFor: aClass selector: selector [
"Add the given struct method to the code base and answer its translation
or nil if it shouldn't be translated."
(self methodNamed: selector) ifNotNil:
[:tmethod|
"If we're repeating an attempt to add the same thing, or
if the existing method overrides this one,don't complain."
(tmethod definingClass includesBehavior: aClass) ifTrue:
[^self].
"If the methods are both simple accessors, don't complain."
((tmethod definingClass isAccessor: selector)
and: [aClass isAccessor: selector]) ifTrue:
[^self].
"If the method is overriding a method in a superclass, don't complain"
(aClass inheritsFrom: tmethod definingClass)
ifTrue: [methods removeKey: selector]
ifFalse: [self error: 'conflicting implementations for ', selector storeString]].
^(self addMethodFor: aClass selector: selector) ifNotNil:
[:tmethod|
tmethod transformToStructClassMethodFor: self.
tmethod]
]
{ #category : #utilities }
CCodeGenerator >> addVariablesInVerbatimCIn: aCCodeSendNode to: aCollection [
"If aCCodeSendNode has a string argument, parse it and extract anything
that looks like a variable, and add the resulting vars to aCollection."
| separators tokens |
(aCCodeSendNode isSend and: [
(aCCodeSendNode selector beginsWith: #cCode:) and: [
aCCodeSendNode arguments first isConstant and: [
aCCodeSendNode arguments first value isString ] ] ]) ifFalse: [
^ self ].
separators := (Character space to: 255 asCharacter) reject: [ :char |
char isLetter or: [ char isDigit or: [ char = $_ ] ] ].
tokens := aCCodeSendNode arguments first value findTokens: separators.
aCollection addAll:
(tokens select: [ :token | token first isLetter ]) asSet
]
{ #category : #utilities }
CCodeGenerator >> anyMethodNamed: selector [
"Answer any method in the code base (including api methods) with the given selector."
^methods
at: selector
ifAbsent:
[apiMethods ifNotNil:
[apiMethods
at: selector
ifAbsent: []]]
]
{ #category : #accessing }
CCodeGenerator >> apiMethods [
^ apiMethods
]
{ #category : #utilities }
CCodeGenerator >> arrayInitializerCalled: varName for: array sizeString: sizeStringOrNil type: cType [
"array is a literal array or a CArray on some array."
^String streamContents:
[:s| | sequence lastLine index newLine allIntegers |
sequence := array isCollection ifTrue: [array] ifFalse: [array object].
"this is to align -ve and +ve integers nicely in the primitiveAccessorDepthTable"
allIntegers := sequence allSatisfy: [:element| element isInteger].
lastLine := index := 0.
newLine := [sequence size >= 20
ifTrue: [s cr; nextPutAll: '/*'; print: index; nextPutAll: '*/'; tab]
ifFalse: [s crtab: 2].
lastLine := s position].
s nextPutAll: cType;
space;
nextPutAll: varName;
nextPut: $[.
sizeStringOrNil ifNotNil: [s nextPutAll: sizeStringOrNil].
s nextPutAll: '] = '.
sequence isString
ifTrue: [s nextPutAll: (self cLiteralFor: sequence)]
ifFalse:
[s nextPut: ${.
newLine value.
sequence
do: [:element|
(allIntegers
and: [element < 0
and: [s peekLast = Character space]]) ifTrue:
[s skip: -1].
s nextPutAll: (self cLiteralFor: element). index := index + 1]
separatedBy:
[s nextPut: $,.
((s position - lastLine) >= 76
or: [(index \\ 20) = 0])
ifTrue: [newLine value]
ifFalse: [s space]].
s crtab; nextPut: $}]]
]
{ #category : #utilities }
CCodeGenerator >> asmLabelNodeFor: selector [
| count label |
suppressAsmLabels ifTrue: [^CEmptyStatementNode new].
asmLabelCounts ifNil:
[asmLabelCounts := Dictionary new].
count := asmLabelCounts
at: selector
put: 1 + (asmLabelCounts at: selector ifAbsent: [-1]).
label := (self cFunctionNameFor: selector), (count = 0 ifTrue: [''] ifFalse: [count printString]).
^ CCallNode
identifier: (CIdentifierNode name: 'VM_LABEL')
arguments: { CIdentifierNode name: label }
]
{ #category : #utilities }
CCodeGenerator >> baseTypeForPointerType: aCType [
"Answer the type of the referent of a pointer type."
self assert: aCType last == $*.
^self baseTypeForType: aCType allButLast
]
{ #category : #utilities }
CCodeGenerator >> baseTypeForType: aCType [
"Reduce various declarations to the most basic type we can determine."
| type fpIndex closeidx openidx |
type := aCType.
((openidx := type indexOfSubCollection: 'const ') > 0
and: [openidx = 1 or: [(type at: openidx) isSeparator]]) ifTrue:
[type := type copyReplaceFrom: openidx to: openidx + 5 with: ''].
((type beginsWith: 'unsigned') and: [(type includes: $:) and: [type last isDigit]]) ifTrue:
[^#usqInt].
"collapse e.g. void (*foo(int bar))(void) to void (*)(void)"
(fpIndex := type indexOfSubCollection: '(*') > 0 ifTrue:
["elide the function arguments after *, if there are any"
type := type copyReplaceFrom: (type indexOf: $( startingAt: fpIndex + 1)
to: (type indexOf: $) startingAt: fpIndex + 1)
with: ''.
"elide the function name after *, if there is one"
type := type copyReplaceFrom: fpIndex + 2
to: (type indexOf: $) startingAt: fpIndex + 1)
with: ')'].
"collapse [size] to *"
openidx := 0.
[(openidx := type indexOf: $[ startingAt: openidx + 1) > 0
and: [(closeidx := type indexOf: $] startingAt: openidx + 1) > 0]] whileTrue:
[type := type copyReplaceFrom: openidx to: closeidx with: '*'].
"map foo* to foo *"
^self conventionalTypeForType: type
]
{ #category : #accessing }
CCodeGenerator >> breakDestInlineSelector: aSelector [
breakDestInlineSelectors add: aSelector
]
{ #category : #accessing }
CCodeGenerator >> breakOnInline: aBooleanOrNil [
breakOnInline := aBooleanOrNil
]
{ #category : #accessing }
CCodeGenerator >> breakSrcInlineSelector: aSelector [
breakSrcInlineSelectors add: aSelector
]
{ #category : #inlining }
CCodeGenerator >> bytesPerOop [
^ 8
]
{ #category : #inlining }
CCodeGenerator >> bytesPerWord [
^ 8
]
{ #category : #utilities }
CCodeGenerator >> cCodeForMethod: selector [
"Answer a string containing the C code for the given method."
"Example:
((CCodeGenerator new initialize addClass: TestCClass1; prepareMethods)
cCodeForMethod: #ifTests)"
| m s cast |
m := self methodNamed: selector.
m = nil ifTrue: [
self error: 'method not found in code base: ' , selector ].
s := ReadWriteStream on: ''.
cast := m asCASTIn: self.
cast prettyPrintOn: s.
^ s contents
]
{ #category : #'C code generator' }
CCodeGenerator >> cFunctionNameFor: aSelector [
"Create a C function name from the given selector by finding
a specific translation, or if none, simply omitting colons, and
any trailing underscores (this supports a varargs convention)."
^selectorTranslations
at: aSelector
ifAbsent:
[| cSelector |
cSelector := aSelector copyWithout: $:.
aSelector last = $: ifTrue:
[[cSelector last = $_] whileTrue:
[cSelector := cSelector allButLast]].
cSelector]
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralFor: anObject [
"Return a string representing the C literal value for the given object."
anObject isNumber
ifTrue:
[anObject isInteger ifTrue:
[| hex |
hex := (anObject > 0
and: [(anObject >> anObject lowBit + 1) isPowerOfTwo
and: [(anObject highBit = anObject lowBit and: [anObject > 65536])
or: [anObject highBit - anObject lowBit >= 4]]]).
^self cLiteralForInteger: anObject hex: hex].
anObject isFloat ifTrue:
[^anObject printString]]
ifFalse:
[anObject isSymbol ifTrue:
[^self cFunctionNameFor: anObject].
anObject isString ifTrue:
[^'"', (anObject copyReplaceAll: (String with: Character cr) with: '\n') , '"'].
anObject == nil ifTrue: [^ self nilTranslation ].
anObject == true ifTrue: [^ '1' ].
anObject == false ifTrue: [^ '0' ].
anObject isCharacter ifTrue:
[^anObject == $'
ifTrue: ['''\'''''] "i.e. '\''"
ifFalse: [anObject asString printString]]].
self error: 'Warning: A Smalltalk literal could not be translated into a C constant: ', anObject printString.
^'"XXX UNTRANSLATABLE CONSTANT XXX"'
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralFor: anObject name: smalltalkName [
"Return a string representing the C literal value for the given object.
This version may use hex for integers that are bit masks."
anObject isInteger
ifTrue: [ | hex dec useHexa |
hex := anObject printStringBase: 16.
dec := anObject printStringBase: 10.
useHexa := (smalltalkName endsWith: 'Mask')
or: [ anObject bytesCount > 1
and: [ hex asSet size * 3 <= (dec asSet size * 2)
and: [ (smalltalkName endsWith: 'Size') not ] ] ].
^ self cLiteralForInteger: anObject hex: useHexa ].
^ self cLiteralFor: anObject
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForInteger: anInteger hex: aBoolean [
"Answer the string for generating a literal integer.
Use hexadecimal notation as prescribed by aBoolean.
Use long long suffix (LL) if the integer does not fit on 32 bits.
Use unsigned suffix (U) if the integer does not fit on a signed integer (resp. long long).
Correctly generate INT_MIN and LONG_LONG_MIN.
Indeed -0x8000000 is parsed as - (0x8000000) by C Compiler.
0x8000000 does not fit on a signed int, it is interpreted as unsigned.
That makes INT_MIN unsigned which is badly broken..."
| printString |
printString := aBoolean
ifTrue: [anInteger positive
ifTrue: ['0x' , (anInteger printStringBase: 16)]
ifFalse: ['-0x' , (anInteger negated printStringBase: 16)]]
ifFalse: [anInteger printString].
^anInteger positive
ifTrue: [anInteger > 16r7FFFFFFF "INT_MAX"
ifTrue: [anInteger > 16rFFFFFFFF "UINT_MAX"
ifTrue: [anInteger > 16r7FFFFFFFFFFFFFFF "LONG_LONG_MAX"
ifTrue: [printString , 'ULL']
ifFalse: [printString , 'LL']]
ifFalse: [printString , 'U']]
ifFalse: [printString]]
ifFalse: [anInteger < -16r8000000
ifTrue: [anInteger = -16r800000000000000 "LONG_LONG_MIN"
ifTrue: ['(-0x7FFFFFFFFFFFFFFFLL-1)']
ifFalse: [printString , 'LL']]
ifFalse: [anInteger = -16r8000000 "INT_MIN"
ifTrue: ['(-0x7FFFFFFF-1)']
ifFalse: [printString]]]
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForPrintfString: aString [
^(('"', (PrintfFormatString new setFormat: aString) transformForVMMaker, '"')
copyReplaceAll: (String with: Character cr) with: '\n')
copyReplaceAll: (String with: Character tab) with: '\t'
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForUnsignedInteger: anInteger hex: aBoolean longlong: llBoolean [
"Answer the string for generating an unsigned literal integer.
Use hexadecimal notation as prescribed by aBoolean.
Force long long suffix (LL) if the integer does not fit on 32 bits, or if llBoolean is true."
| printString |
printString := aBoolean
ifTrue: [anInteger positive
ifTrue: ['0x' , (anInteger printStringBase: 16)]
ifFalse: ['-0x' , (anInteger negated printStringBase: 16)]]
ifFalse: [anInteger printString].
^anInteger positive
ifTrue: [(llBoolean or: [anInteger > 16rFFFFFFFF "UINT_MAX"])
ifTrue: [printString , 'ULL']
ifFalse: [printString , 'U']]
ifFalse: [self error: 'please provide positive integer']
]
{ #category : #'C code generator' }
CCodeGenerator >> cLiteralForUnsignedInteger: anInteger longlong: llBoolean [
"Answer the string for generating an unsigned literal integer.
Eventually use hexadecimal.
Force long long suffix (LL) if the integer does not fit on 32 bits, or if llBoolean is true."
| hex |
hex := (anInteger > 0
and: [(anInteger >> anInteger lowBit + 1) isPowerOfTwo
and: [(anInteger highBit = anInteger lowBit and: [anInteger > 65536])
or: [anInteger highBit - anInteger lowBit >= 4]]]).
^self cLiteralForUnsignedInteger: anInteger hex: hex longlong: llBoolean
]
{ #category : #inlining }
CCodeGenerator >> cannotInline: selector [
self error: 'Failed to inline ', selector,
' as it contains unrenamable C declarations or C code'
]
{ #category : #'error notification' }
CCodeGenerator >> checkClassForNameConflicts: aClass [
"Verify that the given class does not have constant, variable, or method names that conflict with
those of previously added classes. Raise an error if a conflict is found, otherwise just return."
"check for constant name collisions in class pools"
aClass classPool associationsDo:
[:assoc |
(constants includesKey: assoc key) ifTrue:
[self error: 'Constant ', assoc key, ' was defined in a previously added class']].
"and in shared pools"
(aClass sharedPools reject: [:pool| pools includes: pool]) do:
[:pool |
pool bindingsDo:
[:assoc |
(constants includesKey: assoc key) ifTrue:
[self error: 'Constant ', assoc key, ' was defined in a previously added class']]].
"check for instance variable name collisions"
(aClass inheritsFrom: SlangStructType) ifFalse:
[(self instVarNamesForClass: aClass) do:
[:varName |
(variables includes: varName) ifTrue:
[self error: 'Instance variable ', varName, ' was defined in a previously added class']]].
"check for method name collisions"
aClass selectors do:
[:sel | | tmeth meth |
((self shouldIncludeMethodFor: aClass selector: sel)
and: [(tmeth := methods at: sel ifAbsent: nil) notNil
and: [(aClass isStructClass and: [(aClass isAccessor: sel)
and: [(methods at: sel) isStructAccessor]]) not
and: [(meth := aClass >> sel) isSubclassResponsibility not
and: [(aClass includesBehavior: tmeth definingClass) not]]]]) ifTrue:
[((aClass >>sel) pragmaAt: #option:)
ifNil: [self error: 'Method ', sel, ' was defined in a previously added class.']
ifNotNil:
[logger
newLine;
show: 'warning, method ', aClass name, '>>', sel storeString,
' overrides ', tmeth definingClass, '>>', sel storeString;
cr]]]
]
{ #category : #utilities }
CCodeGenerator >> checkForGlobalUsage: vars in: aTMethod [
vars do:
[:var |
(variables includes: var) ifTrue: "find the set of method names using this global var"
[(globalVariableUsage at: var ifAbsentPut: [Set new])
add: aTMethod selector]].
aTMethod clearReferencesToGlobalStruct.
(aTMethod allLocals select: [:l| self reservedWords includes: l]) do:
[:l| | em |
em := aTMethod definingClass name, '>>', aTMethod smalltalkSelector, ' has variable that is a C reserved word: ', l.
self error: em.
self logger cr; nextPutAll: em; cr; flush]
]
{ #category : #inlining }
CCodeGenerator >> collectInlineList: strategy [
"Make a list of methods that should be inlined. If inlineFlagOrSymbol == #asSpecified
only inline methods marked with <inline: true>. If inlineFlagOrSymbol == #asSpecifiedOrQuick
only inline methods marked with <inline: true> or methods that are quick (^constant, ^inst var)."
"Details: The method must not include any inline C, since the
translator cannot currently map variable names in inlined C code.
Methods to be inlined must be small or called from only one place."
| selectorsOfMethodsNotToInline callsOf inlineStrategy selectorsWithBlocks |
inlineStrategy := strategy asCCodeInlineStrategy.
inlineStrategy codeGenerator: self.
"Set of selectors that takes blocks as argument. The associated methods must be inlined and not compiled separately."
selectorsWithBlocks := Set new.
selectorsOfMethodsNotToInline := Set new: methods size.
selectorsOfMethodsNotToInline addAll: macros keys.
apiMethods ifNotNil: [ selectorsOfMethodsNotToInline addAll: apiMethods keys ].
selectorsOfMethodsNotToInline addAll: self structAccessorSelectors.
"build dictionary to record the number of calls to each method"
callsOf := Dictionary new: methods size * 2.
methods keysAndValuesDo:
[:s :m|
(m isRealMethod
and: [self shouldGenerateMethod: m]) ifTrue:
[callsOf at: s put: 0]].
"For each method, scan its parse tree once or twice to:
1. determine if the method contains unrenamable C code or declarations or has a C builtin
2. determine how many nodes it has
3. increment the sender counts of the methods it calls"
inlineList := Set new: methods size * 2.
methods
reject: [:m|
(selectorsOfMethodsNotToInline includes: m selector)
or: [ self isSpecialSelector: m selector ] ]
thenDo: [:m|
m parseTree nodesDo: [:node|
node isSend ifTrue: [
"Special case of methods that takes block as arguments.
The only way to call them is to inline them since blocks are not values in C."
(node arguments anySatisfy: [ :arg | arg class == TStatementListNode ])
ifTrue: [ selectorsWithBlocks add: node selector. ].
"Increase call count"
callsOf
at: node selector
ifPresent: [:senderCount| callsOf at: node selector put: senderCount + 1 ] ] ].
inlineStrategy validateCanInline: m.
(inlineStrategy canInline: m)
ifFalse: [ selectorsOfMethodsNotToInline add: m selector ]
ifTrue: [
(inlineStrategy shouldInlineMethod: m)
ifTrue: [
"inline if method has no C code and is either small or contains inline directive"
inlineList add: m selector]
ifFalse: [
inlineStrategy isSelectiveInlineStrategy
ifTrue: [selectorsOfMethodsNotToInline add: m selector] ] ] ].
"Inline all methods that takes block and mark them inline:#always to ensure they are not compiled sepately"
inlineList addAll: selectorsWithBlocks.
methods select: [ :m | selectorsWithBlocks includes: m selector ] thenDo: [ :m | m inline: #always ].
inlineStrategy isSelectiveInlineStrategy
ifTrue:
[methods do: [:m| m inline ifNil: [m inline: (inlineList includes: m selector)]]]
ifFalse:
[callsOf associationsDo:
[:assoc|
(assoc value = 1
and: [(selectorsOfMethodsNotToInline includes: assoc key) not]) ifTrue:
[ inlineList add: assoc key ]]]
]
{ #category : #accessing }
CCodeGenerator >> compileTimeOptions: aCollection [
compileTimeOptions := aCollection
]
{ #category : #utilities }
CCodeGenerator >> compileToTMethodSelector: selector in: aClass [
"Compile a method to a TMethod"
^ aClass >> selector
asTranslationMethodOfClass: self translationMethodClass
forCodeGenerator: self
]
{ #category : #public }
CCodeGenerator >> const: constName declareC: declarationString [
"Record the given C declaration for a constant."
constants
at: constName
put: (TDefineNode new
setName: constName
value: declarationString)
]
{ #category : #'C code generator' }
CCodeGenerator >> constants [
^ constants keys
]
{ #category : #utilities }
CCodeGenerator >> conventionalTypeForType: aCTypeString [
"The pointer type convention in this version of VMMaker is to have a space between the base type and any *'s.
C type comparisons are simple string comparisons; therefore the convention matters.
Ensure there is a space between the base type and any trailing *'s. Trim whitespace."
| type index |
type := aCTypeString withBlanksTrimmed.
index := type size.
[(type at: index) == $*] whileTrue:
[index := index - 1].
(index < type size
and: [(type at: index) ~~ Character space]) ifTrue:
[type := (type copyFrom: 1 to: index), ' ', (type copyFrom: index + 1 to: type size)].
^type asSymbol
]
{ #category : #accessing }
CCodeGenerator >> currentMethod [
"The method is the bottom of the scope stack"
^ scopeStack first
]
{ #category : #accessing }
CCodeGenerator >> currentMethod: aTMethod [
scopeStack := OrderedCollection with: aTMethod.
previousCommenter := nil
]
{ #category : #accessing }
CCodeGenerator >> currentScope [
^ scopeStack last
]
{ #category : #'C code generator' }
CCodeGenerator >> declarationAt: aVariableName ifAbsent: absentBlock [
scopeStack reverseDo: [:scope|
scope declarationAt: aVariableName ifPresent: [ :declaration | ^ declaration ] ].
variableDeclarations
at: aVariableName
ifPresent: [ :declaration | ^ declaration ].
^(constants at: aVariableName ifAbsent: [ ^ absentBlock value ]) ifNotNil:
[:const|
const value isInteger
ifTrue: [self defaultType]
ifFalse:
[const value isFloat ifTrue:
[#double]]]
]
{ #category : #public }
CCodeGenerator >> declareModuleName: nameString [
"add the declaration of a module name, version and local/external tag"
self var: #moduleName declareC:'const char *moduleName =
#ifdef SQUEAK_BUILTIN_PLUGIN
"', nameString,' (i)"
#else
"', nameString,' (e)"
#endif
'.
"and for run-time use, answer the string"
^nameString, ' (i)'
]
{ #category : #public }
CCodeGenerator >> declareVar: varName type: type [
"This both creates a varable and provides its type"
self var: (variables add: varName asString) type: type
]
{ #category : #'C code generator' }
CCodeGenerator >> declaredConstants [
^ constants keys asSet
]
{ #category : #'type inference' }
CCodeGenerator >> defaultType [
^ #int
]
{ #category : #'compile-time-options' }
CCodeGenerator >> defineAtCompileTime: aString [
"Define if the code generator should define the option at compile time or at generation time.
If true, the decision of the option will be delayed to compilation time.
Otherwise, do it at transpilation time,
- the code with the option is generated if the value of the option is true
- if not true or unset, do not generate"
compileTimeOptions ifNil: [ ^ false ].
^ (compileTimeOptions includes: aString)
]
{ #category : #inlining }
CCodeGenerator >> doBasicInlining: inlineFlagOrSymbol [
"Inline the bodies of all methods that are suitable for inlining.
This method does only the basic inlining suitable for both the core VM and plugins - no bytecode inlining etc"
| pass progress |
self collectInlineList: inlineFlagOrSymbol.
pass := 0.
progress := true.
[progress] whileTrue: [
"repeatedly attempt to inline methods until no further progress is made"
progress := false.