/
TMethod.class.st
3144 lines (2816 loc) · 111 KB
/
TMethod.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
"
A TMethod is a translation method, representing a MethodNode that is to be translated to C source. It has a parseTree of translation nodes that mirrors the parse tree of the corresponding Smalltalk method.
"
Class {
#name : #TMethod,
#superclass : #Object,
#instVars : [
'args',
'comment',
'complete',
'declarations',
'definingClass',
'export',
'extraVariableNumber',
'globalStructureBuildMethodHasFoo',
'inline',
'labels',
'locals',
'parseTree',
'primitive',
'properties',
'returnType',
'selector',
'sharedCase',
'sharedLabel',
'static',
'writtenToGlobalVarsCache',
'functionAttributes',
'usedVariablesCache'
],
#classVars : [
'CaseStatements'
],
#category : #'VMMaker-Translation to C'
}
{ #category : #'class initialization' }
TMethod class >> initialize [
"TMethod initialize"
CaseStatements := IdentitySet new: 10.
CaseStatements addAll: #(dispatchOn:in: dispatchOn:in:with: dispatchOn:in:with:with:).
]
{ #category : #accessing }
TMethod >> addFunctionAttribute: aString [
functionAttributes := functionAttributes
ifNil: [aString]
ifNotNil: [functionAttributes, ' ', aString]
]
{ #category : #accessing }
TMethod >> addLabelsTo: aTMethod [
aTMethod labels addAll: labels
]
{ #category : #initialization }
TMethod >> addTypeForSelf [
"If self should be typed then add a suitable type declaration.
Preserve the flagging of an implicit self using the #implicit symbol as the fake type."
self typeForSelf ifNotNil:
[:typeForSelf|
self declarationAt: 'self'
put: (typeForSelf == #implicit
ifTrue: [typeForSelf]
ifFalse: [typeForSelf, ' self'])]
]
{ #category : #'type inference' }
TMethod >> addTypesFor: node to: typeSet in: aCodeGen [
"Add the value types for the node to typeSet.
Answer if any type was derived from an as-yet-untyped method or variable, which allows us to abort
inferReturnTypeFromReturnsIn: if the return type depends on a yet-to-be-typed method or variable."
| expr |
expr := node.
[expr isAssignment or: [expr isStmtList]] whileTrue:
[expr isAssignment ifTrue:
[expr := expr variable].
expr isStmtList ifTrue:
[expr := expr statements last]].
expr isSend ifTrue:
[(#(ifTrue: ifFalse: ifTrue:ifFalse: ifFalse:ifTrue:) includes: expr selector) ifTrue:
[^expr args
inject: false
into: [:asYetUntyped :block|
asYetUntyped | (self addTypesFor: block to: typeSet in: aCodeGen)]].
(aCodeGen returnTypeForSend: expr in: self ifNil: nil)
ifNil: [^(aCodeGen methodNamed: expr selector) notNil and: [expr selector ~~ selector]]
ifNotNil:
[:type |
typeSet add: type.
^false]].
expr isVariable ifTrue:
[(aCodeGen typeOfVariable: expr name)
ifNotNil: [:type| typeSet add: type]
ifNil: [(typeSet add: (expr name = 'self'
ifTrue: [#void]
ifFalse: [#sqInt])) == #sqInt ifTrue:
[^true]]].
expr isConstant ifTrue:
[(expr value isInteger and: [expr value >= 0]) "cannot determine if signed or unsigned yet..."
ifTrue: [typeSet add: expr value]
ifFalse:
[(expr typeOrNilFrom: aCodeGen in: self) ifNotNil:
[:type | typeSet add: type]]].
^false
]
{ #category : #'inlining support' }
TMethod >> addVarsDeclarationsAndLabelsOf: methodToBeInlined except: doNotRename [
"Prepare to inline the body of the given method into the receiver by making the args and locals of the argument to the receiver be locals of the receiver. Record any type declarations for these variables. Record labels. Assumes that the variables have already be renamed to avoid name clashes."
locals
addAll: (methodToBeInlined args reject: [ :v | doNotRename includes: v]);
addAll: (methodToBeInlined locals reject: [ :v | doNotRename includes: v]).
methodToBeInlined declarations keysAndValuesDo:
[ :v :decl |
(doNotRename includes: v) ifFalse:
[self declarationAt: v put: decl]].
labels addAll: methodToBeInlined labels
]
{ #category : #utilities }
TMethod >> allCalls [
"Answer a collection of selectors for the messages sent by this method."
^parseTree allCalls
]
{ #category : #accessing }
TMethod >> allLocals [
"The merge of locals and declarations (don't ask)"
^(declarations keys asSet reject: [:k| (declarations at: k) == #implicit])
addAll: locals; yourself
]
{ #category : #accessing }
TMethod >> allReferencedVariablesUsing: aCodeGen [
"Answer the set of all variables referenced in the receiver."
| refs |
refs := Set new.
"Find all the variable names referenced in this method.
Don't descend into conditionals that won't be generated."
parseTree
nodesWithParentsDo:
[:node :parent|
node isVariable ifTrue: [refs add: node name asString].
node isStmtList ifTrue: [refs addAll: node args].
(node isSend
and: [node selector beginsWith: #cCode:]) ifTrue:
[aCodeGen addVariablesInVerbatimCIn: node to: refs]]
unless:
[:node :parent|
parent notNil
and: [parent isSend
and: [aCodeGen nodeIsDeadCode: node withParent: parent]]].
^refs
]
{ #category : #inlining }
TMethod >> argAssignmentsFor: meth send: aSendNode except: elidedArgs in: aCodeGen [
"Return a collection of assignment nodes that assign the given argument expressions to the formal parameter variables of the given method."
"Optimization: If the actual parameters are either constants or local variables in the target method (the receiver), substitute them directly into the body of meth. Note that global variables cannot be subsituted because the inlined method might depend on the exact ordering of side effects to the globals."
| stmtList substitutionDict argList |
meth args size > (argList := aSendNode args) size ifTrue:
[self assert: (meth args first beginsWith: 'self_in_').
argList := {aSendNode receiver}, aSendNode args].
stmtList := OrderedCollection new: argList size.
substitutionDict := Dictionary new: argList size.
meth args with: argList do:
[:argName :exprNode |
(self isNode: exprNode substitutableFor: argName inMethod: meth in: aCodeGen)
ifTrue:
[substitutionDict
at: argName
put: (aCodeGen
node: exprNode
typeCompatibleWith: argName
inliningInto: meth
in: self).
locals remove: argName ifAbsent: [self assert: (argName beginsWith: 'self_in_')].
declarations removeKey: argName ifAbsent: nil]
ifFalse: "Add an assignment for anything except an unused self_in_foo argument"
[(elidedArgs includes: argName) ifFalse:
[stmtList addLast:
(TAssignmentNode new
setVariable: (TVariableNode new setName: argName)
expression: (aCodeGen
node: exprNode copy
typeCompatibleWith: argName
inliningInto: meth
in: self))]]].
meth parseTree: (meth parseTree bindVariablesIn: substitutionDict).
^stmtList
]
{ #category : #'primitive compilation' }
TMethod >> argConversionExprFor: varName stackIndex: stackIndex [
"Return the parse tree for an expression that fetches and converts the
primitive argument at the given stack offset."
| exprList decl type stmtList |
exprList := OrderedCollection new.
((decl := declarations at: varName ifAbsent: []) notNil
and: ['int' ~= (type := (decl copyReplaceAll: varName with: '') withBlanksTrimmed)])
ifTrue:
[(decl includes: $*) ifTrue: "array"
[(decl includesSubstring: 'char')
ifTrue:
[| expr |
expr := '(interpreterProxy isBytes: (interpreterProxy stackValue: (stackIndex))) ifFalse: [^interpreterProxy primitiveFail]'.
expr := expr copyReplaceAll: 'interpreterProxy' with: self vmNameString.
expr := expr copyReplaceAll: 'stackIndex' with: stackIndex printString.
exprList addLast: expr].
exprList addLast: varName , ' := ', self vmNameString, ' arrayValueOf: (', self vmNameString, ' stackValue: (' , stackIndex printString , '))'.
exprList addLast: varName , ' := ' , varName , ' - 1'] "so that varName[1] is the zero'th element"
ifFalse: "must be a double"
[type ~= 'double' ifTrue:
[self error: 'unsupported type declaration in a translated primitive method'].
exprList addLast: varName , ' := ', self vmNameString, ' stackFloatValue: ' , stackIndex printString]]
ifFalse: "undeclared variables are taken to be integer"
[exprList addLast: varName , ' := ', self vmNameString, ' stackIntegerValue: ' , stackIndex printString].
stmtList := OrderedCollection new.
exprList do: [:e | stmtList addAll: (self statementsFor: e varName: varName)].
^ stmtList
]
{ #category : #accessing }
TMethod >> args [
"The arguments of this method."
^args
]
{ #category : #transformations }
TMethod >> asInlineNode [
^TInlineNode new method: self
]
{ #category : #transformations }
TMethod >> bindClassVariablesIn: constantDictionary [
"Class variables are used as constants. This method replaces all references to class variables in the body of this method with the corresponding constant looked up in the class pool dictionary of the source class. The source class class variables should be initialized before this method is called."
parseTree := parseTree bindVariablesIn: constantDictionary.
]
{ #category : #transformations }
TMethod >> bindVariableUsesIn: aDictionary [
parseTree := parseTree bindVariableUsesIn: aDictionary.
]
{ #category : #transformations }
TMethod >> bindVariableUsesIn: aDictionary andConstantFoldIf: constantFold in: codeGen [
"Answer either the receiver, if it contains no references to the given variables, or a new node with the given variables rebound."
| newParseTree |
newParseTree := parseTree bindVariableUsesIn: aDictionary andConstantFoldIf: constantFold in: codeGen.
^newParseTree = parseTree
ifTrue: [self]
ifFalse: [self shallowCopy
parseTree: newParseTree;
yourself]
]
{ #category : #transformations }
TMethod >> buildCaseStmt: aSendNode in: aCodeGen [
"Build a case statement node for the given send of dispatchOn:in:."
"Note: the first argument is the variable to be dispatched on. The second argument is a constant node holding an array of unary selectors, which will be turned into sends to self."
| unimplemented errorMessage |
(aSendNode args size >= 2
and: [aSendNode args second isConstant
and: [aSendNode args second value isArray]]) ifFalse:
[self error: 'wrong node structure for a case statement'].
unimplemented := aSendNode args second value select: [:s| (aCodeGen methodNamed: s) isNil].
unimplemented isEmpty ifFalse:
[errorMessage := 'The following selectors in case statement "', (aSendNode printString copyUpTo: $#), '..." are unimplemented: ',
(String streamContents: [:s| unimplemented do: [:sel| s crtab; store: sel]]).
aCodeGen logger nextPutAll: errorMessage; cr; flush.
(self confirm: errorMessage
orCancel: aCodeGen abortBlock) ifFalse:
[self halt]].
^TCaseStmtNode new
setExpression: aSendNode args first
selectors: aSendNode args second value
arguments: (aSendNode args copyFrom: 3 to: aSendNode args size)
]
{ #category : #transformations }
TMethod >> buildSwitchStmt: aSendNode parent: parentNode [
"Build a switch statement node for the given send of caseOf: or caseOf:otherwise:."
| switch |
switch := TSwitchStmtNode new
expression: aSendNode receiver
cases: aSendNode args first
otherwiseOrNil: (aSendNode args at: 2 ifAbsent: [nil]).
(aSendNode receiver isVariable or: [parentNode isStmtList]) ifFalse:
[switch switchVariable: (locals add: (self extraVariableName: 'switch'))].
^switch
]
{ #category : #'inlining support' }
TMethod >> checkForCompletenessIn: aCodeGen [
"Set the complete flag if the parse tree contains no further candidates for inlining."
| foundIncompleteSend incompleteSends |
aCodeGen maybeBreakForTestOfInliningOf: selector.
foundIncompleteSend := false.
incompleteSends := IdentitySet new.
parseTree
nodesDo:
[:node|
node isSend ifTrue:
[(self methodIsEffectivelyComplete: node selector in: aCodeGen)
ifTrue:
[(self inlineableFunctionCall: node in: aCodeGen) ifTrue:
[complete := false. "more inlining to do"
^self]]
ifFalse:
[foundIncompleteSend := true.
incompleteSends add: node]]]
unless:
[:node|
node isSend
and: [node selector == #cCode:inSmalltalk:
or: [aCodeGen isAssertSelector: node selector]]].
foundIncompleteSend ifFalse:
[complete := true]
]
{ #category : #testing }
TMethod >> checkForRequiredInlinability [
"This is used in methods answering inlinability.
Always answer false. But if the receiver is marked as something that must be inlined (inline == #always) raise an error."
(inline == #always and: [complete]) ifTrue:
[self error: 'cannot inline method ', selector, ' marked as <inline: #always>'].
^false
]
{ #category : #'primitive compilation' }
TMethod >> checkSuccessExpr [
"Answer the parse tree for an expression that aborts the primitive if there has been a failure."
^self
statementsFor: 'interpreterProxy failed ifTrue: [^nil]'
varName: ''
]
{ #category : #accessing }
TMethod >> checkedDeclarationAt: aVariableName put: aDeclaration in: aCCodeGen [
((args includes: aVariableName)
or: [(locals includes: aVariableName)
or: [(definingClass instVarIndexFor: aVariableName asString ifAbsent: nil) notNil
or: [aDeclaration beginsWith: 'extern ']]]) ifFalse:
[| msg |
msg := definingClass name, '>>', selector, ' contains declaration for non-existent variable ', aVariableName.
aCCodeGen
ifNotNil: [aCCodeGen logger show: msg; cr]
ifNil: [self error: msg]].
^self declarationAt: aVariableName "<String>" put: aDeclaration
]
{ #category : #accessing }
TMethod >> clearReferencesToGlobalStruct [
globalStructureBuildMethodHasFoo := false
]
{ #category : #accessing }
TMethod >> comment [
^comment
]
{ #category : #accessing }
TMethod >> comment: aComment [
comment := aComment
]
{ #category : #accessing }
TMethod >> compileTimeOptionPragmas [
"Answer the (possibly empty) sequence of option: or notOption: pragmas
whose arguments are values to be defined at compile time."
^self compiledMethod pragmas select:
[:pragma|
(#option: == pragma keyword or: [#notOption: == pragma keyword])
and: [VMBasicConstants defineAtCompileTime: (pragma argumentAt: 1)]]
]
{ #category : #accessing }
TMethod >> compiledMethod [
^definingClass
compiledMethodAt: selector
ifAbsent: [definingClass compiledMethodAt: properties selector]
]
{ #category : #'inlining support' }
TMethod >> computePossibleSideEffectsInto: writtenToVars visited: visitedSelectors in: aCodeGen [
"Add all variables written to by this method and its callees to writtenToVars.
Avoid circularity via visitedSelectors"
(visitedSelectors includes: selector) ifTrue:
[^self].
visitedSelectors add: selector.
writtenToGlobalVarsCache ifNotNil:
[writtenToVars addAll: writtenToGlobalVarsCache.
^self].
parseTree nodesDo:
[ :node |
(node isAssignment
and: [(locals includes: node variable name) not])
ifTrue:
[writtenToVars add: node variable name].
(node isSend
and: [node isBuiltinOperator not
and: [(aCodeGen isStructSend: node) not]]) ifTrue:
[(aCodeGen methodNamed: node selector) ifNotNil:
[:method|
method
computePossibleSideEffectsInto: writtenToVars
visited: visitedSelectors
in: aCodeGen]]].
writtenToGlobalVarsCache := writtenToVars copy
]
{ #category : #accessing }
TMethod >> declarationAt: aVariableName [
^declarations at: aVariableName ifAbsent: [#sqInt, ' ', aVariableName]
]
{ #category : #accessing }
TMethod >> declarationAt: aVariableName ifAbsent: absentBlock [
^declarations at: aVariableName ifAbsent: absentBlock
]
{ #category : #accessing }
TMethod >> declarationAt: aVariableName "<String>" put: aDeclaration [ "<String>" "^aDeclaration"
^declarations at: aVariableName put: aDeclaration
]
{ #category : #accessing }
TMethod >> declarations [
"The type declaration dictionary of this method."
^declarations
]
{ #category : #testing }
TMethod >> definedAsMacro [
^properties notNil
and: [(properties includesKey: #cmacro:)
or: [properties includesKey: #cmacro]]
]
{ #category : #accessing }
TMethod >> definingClass [
^definingClass
]
{ #category : #accessing }
TMethod >> definingClass: aClass [
definingClass := aClass.
]
{ #category : #'error handling' }
TMethod >> deny: aBooleanOrBlock [
<doNotGenerate>
aBooleanOrBlock value ifTrue: [AssertionFailure signal: 'Assertion failed']
]
{ #category : #'C code generation' }
TMethod >> determineTypeFor: aNode in: aCodeGen [
aNode isSend ifTrue:
[^aCodeGen returnTypeForSend: aNode in: self ifNil: #sqInt].
aNode isAssignment ifTrue:
[^self determineTypeFor: aNode expression in: aCodeGen].
self error: 'don''t know how to extract return type from this kind of node'
]
{ #category : #transformations }
TMethod >> elideAnyFinalReturn [
"For super expansions we need to eliminate any final return to prevent premature exit.
Anything meaningful in the returned expression must be retained."
| stmtList expr |
stmtList := parseTree statements asOrderedCollection.
stmtList last isReturn ifTrue:
[expr := stmtList last expression.
(expr isVariable and: [expr name = 'self'])
ifTrue: [stmtList := stmtList allButLast]
ifFalse: [stmtList at: stmtList size put: expr].
parseTree setStatements: stmtList]
]
{ #category : #'C code generation' }
TMethod >> emitCCodeOn: aStream generator: aCodeGen [
"Emit C code for this method onto the given stream.
All calls to inlined methods should already have been expanded."
| bodyStream conditional |
aCodeGen currentMethod: self.
usedVariablesCache := Set new.
self emitCCommentOn: aStream. "place method comment and method name before function."
aStream crtab; nextPutAll: '/* '; nextPutAll: self definingClass name; nextPutAll: '>>#'; nextPutAll: self smalltalkSelector; nextPutAll: ' */'.
aStream cr.
conditional := self emitCFunctionPrototype: aStream generator: aCodeGen isPrototype: false.
aStream cr; nextPut: ${.
bodyStream := ReadWriteStream on: (ByteString new: 128).
aCodeGen "Generation will note used variables in usedVariablesCache"
pushScope: declarations
while: [parseTree emitCCodeOn: bodyStream level: 1 generator: aCodeGen].
self emitCLocalsOn: aStream generator: aCodeGen.
usedVariablesCache := nil.
aStream nextPutAll: bodyStream contents.
(returnType = #void or: [parseTree endsWithReturn]) ifFalse:
[aStream tab; nextPutAll: 'return 0;'; cr].
aStream nextPut: $}; cr.
conditional ifTrue:
[self terminateConditionalDefineFor: self compileTimeOptionPragmas on: aStream]
]
{ #category : #'C code generation' }
TMethod >> emitCCommentOn: aStream [
"Emit the transferred Smalltalk comments as C comments."
comment ifNotNil: [
aStream cr;cr.
1 to: comment size do: [:index | | startPos |
aStream nextPutAll: '/*'; tab.
startPos := aStream position.
self printSingleComment: (comment at: index)
on: aStream
indent: 1
tabWidth: 4
lineBreak: 78.
aStream position - startPos > (comment at: index) size ifTrue: "probably a multi-line comment"
[aStream cr].
aStream nextPutAll: ' */'; cr]]
]
{ #category : #'C code generation' }
TMethod >> emitCFunctionPrototype: aStream generator: aCodeGen [
"Emit a C function header for this method onto the given stream."
properties ifNotNil:
[(properties at: #api: ifAbsent: []) ifNotNil:
[:pragma|
aStream
nextPutAll: (pragma argumentAt: 1);
nextPut: $;;
cr.
^self]].
self emitCFunctionPrototype: aStream generator: aCodeGen isPrototype: true
]
{ #category : #'C code generation' }
TMethod >> emitCFunctionPrototype: aStream generator: aCodeGen isPrototype: isPrototype [ "<Boolean>"
"Emit a C function header for this method onto the given stream.
Answer if the method has any compileTimeOptionPragmas"
| compileTimeOptionPragmas returnTypeIsFunctionPointer |
(compileTimeOptionPragmas := self compileTimeOptionPragmas) notEmpty ifTrue:
[self outputConditionalDefineFor: compileTimeOptionPragmas on: aStream].
returnTypeIsFunctionPointer := returnType notNil
and: [returnType last = $)
and: [returnType includesSubstring: (aCodeGen cFunctionNameFor: selector)]].
export
ifTrue:
[aStream nextPutAll: 'EXPORT('; nextPutAll: returnType; nextPut: $)]
ifFalse:
[self isStatic
ifTrue: [aStream nextPutAll: 'static ']
ifFalse:
[isPrototype ifTrue:
[aStream nextPutAll: 'extern ']].
(isPrototype or: [inline ~~ #always]) ifFalse: [aStream nextPutAll: 'inline '].
aStream nextPutAll: (returnType ifNil: [#sqInt])].
(functionAttributes isNil or: [returnTypeIsFunctionPointer]) ifFalse:
[aStream space; nextPutAll: functionAttributes].
isPrototype ifTrue: [aStream space] ifFalse: [aStream cr].
returnTypeIsFunctionPointer ifFalse:
[aStream
nextPutAll: (aCodeGen cFunctionNameFor: selector);
nextPut: $(.
args isEmpty
ifTrue: [aStream nextPutAll: #void]
ifFalse:
[args
do: [:arg| aStream nextPutAll: (self declarationAt: arg)]
separatedBy: [aStream nextPutAll: ', ']].
aStream nextPut: $)].
isPrototype ifTrue:
[aStream nextPut: $;; cr.
compileTimeOptionPragmas isEmpty ifFalse:
[aCodeGen maybeEmitPrimitiveFailureDefineFor: selector on: aStream.
self terminateConditionalDefineFor: compileTimeOptionPragmas on: aStream]].
^compileTimeOptionPragmas notEmpty
]
{ #category : #'C code generation' }
TMethod >> emitCLocalsOn: aStream generator: aCodeGen [
"Emit a C function header for this method onto the given stream."
| volatileVariables maybeExternFunctions |
volatileVariables := properties includesKey: #volatile.
self refersToGlobalStruct ifTrue:
[aStream
next: 3 put: Character space; "there's already an opening ${ on this line; see sender"
nextPutAll: (volatileVariables
ifTrue: ['DECL_MAYBE_VOLATILE_SQ_GLOBAL_STRUCT']
ifFalse: ['DECL_MAYBE_SQ_GLOBAL_STRUCT'])].
aStream cr.
maybeExternFunctions := (declarations select: [:decl| decl beginsWith: 'extern']) keys.
(locals isEmpty and: [maybeExternFunctions isEmpty]) ifFalse:
[(aCodeGen sortStrings: locals, maybeExternFunctions) do:
[ :var | | decl |
decl := self declarationAt: var.
(volatileVariables
or: [(decl beginsWith: 'static')
or: [(decl beginsWith: 'extern')
or: [usedVariablesCache includes: var]]]) ifTrue:
[aStream next: 4 put: Character space.
volatileVariables ifTrue:
[aStream nextPutAll: #volatile; space].
aStream
nextPutAll: decl;
nextPut: $;;
cr]].
aStream cr]
]
{ #category : #'C code generation' }
TMethod >> emitInlineOn: aStream level: level generator: aCodeGen [
"Emit C code for this method onto the given stream. All calls to inlined methods should already have been expanded."
self removeUnusedTempsAndNilIfRequiredIn: aCodeGen.
sharedLabel ifNotNil:
[aStream crtab: level-1; nextPutAll: sharedLabel; nextPut: $:.
aStream crtab: level.
aStream nextPutAll: '/* '; nextPutAll: selector; nextPutAll: ' */'.
aStream crtab: level].
aStream nextPut: ${.
locals isEmpty ifFalse:
[(aCodeGen sortStrings: locals) do:
[:var|
aStream
crtab: level+1;
nextPutAll: (self declarationAt: var);
nextPut: $;].
aStream cr].
aStream crtab: level+1.
aCodeGen outputAsmLabel: selector on: aStream.
aStream crtab: level+1.
aCodeGen
pushScope: declarations
while: [parseTree emitCCodeOn: aStream level: level+1 generator: aCodeGen].
aStream tab: level; nextPut: $}
]
{ #category : #'C code generation' }
TMethod >> emitProxyFunctionPrototype: aStream generator: aCodeGen [
"Emit an indirect C function header for this method onto the given stream."
aStream
nextPutAll: returnType;
space;
nextPutAll: '(*';
nextPutAll: (aCodeGen cFunctionNameFor: selector);
nextPutAll: ')('.
args isEmpty
ifTrue: [aStream nextPutAll: #void]
ifFalse:
[args
do: [:arg| aStream nextPutAll: (self declarationAt: arg)]
separatedBy: [ aStream nextPutAll: ', ' ]].
aStream nextPut: $)
]
{ #category : #testing }
TMethod >> endsWithReturn [
"Answer true if the last statement of this method is a return."
^parseTree endsWithReturn
]
{ #category : #inlining }
TMethod >> ensureConditionalAssignmentsAreTransformedIn: aCodeGen [
"Make passes transforming
foo := expr ifTrue: [a] ifFalse: [b]
into
expr ifTrue: [foo := a] ifFalse: [foo := b]
until no such instances exist in the tree. This is needed for correct inlining
given the limitations of inlineCodeOrNilForStatement:returningNodes:in:"
| transformedAssignments |
[transformedAssignments := Dictionary new.
parseTree
nodesDo:
[:node|
(self transformConditionalAssignment: node in: aCodeGen) ifNotNil:
[:replacement|
transformedAssignments at: node put: replacement]]
unless: "Don't inline the arguments to asserts to keep the asserts readable"
[:node|
node isSend
and: [node selector == #cCode:inSmalltalk:
or: [aCodeGen isAssertSelector: node selector]]].
transformedAssignments notEmpty
and: [self replaceNodesIn: transformedAssignments.
true]] whileTrue
]
{ #category : #transformations }
TMethod >> ensureToByDoLoopLimitIsSafeAndEfficient: node in: aCodeGen [
"For both safety and efficiency, make sure that to:[by:]do: loops
with complex limits have a variable to hold the limit expression.
In C the limit expression is evaluated each time round the loop
so if the loop has side-effects (which it usually will), the C compiler
may not be able to optimize the limit expression itself."
| limitExpr hasSideEffects |
limitExpr := node args first.
hasSideEffects := limitExpr anySatisfy:
[:subNode|
subNode isSend
and: [(aCodeGen isBuiltinSelector: subNode selector) not
and: [(aCodeGen isStructSend: subNode) not]]].
node args size = 4
ifTrue:
[hasSideEffects
ifTrue: [locals add: node args last name]
ifFalse: [node arguments: node args allButLast]]
ifFalse: "If the expression is complex but as yet there is no limit variable, add it"
[hasSideEffects ifTrue:
[| var |
var := self unusedNamePrefixedBy: 'toDoLimit' avoiding: locals. "N.B. adds it to locals!!"
node arguments: node args, {TVariableNode new setName: var; yourself}.
declarations
at: node args third args first
ifPresent: [:decl| self declarationAt: var put: (self typeFor: node args third args first in: aCodeGen), ' ', var]]]
]
{ #category : #inlining }
TMethod >> exitVar: exitVar label: exitLabel [
"Replace each return statement in this method with an assignment to the
exit variable followed by either a return or a goto to the given label.
Answer if a goto was generated."
"Optimization: If exitVar is nil, the return value of the inlined method is not being used, so don't add the assignment statement."
| labelUsed map elisions eliminateReturnSelfs |
labelUsed := false.
map := Dictionary new.
elisions := Set new.
"Conceivably one might ^self from a struct class and mean it. In most cases though
^self means `get me outta here, fast'. So unless this method is from a VMStruct class,
elide any ^self's"
eliminateReturnSelfs := ((definingClass inheritsFrom: VMClass) and: [definingClass isStructClass]) not
and: [returnType = #void or: [returnType = #sqInt]].
parseTree nodesDo:
[:node | | replacement |
node isReturn ifTrue:
[self transformReturnSubExpression: node
toAssignmentOf: exitVar
andGoto: exitLabel
unless: eliminateReturnSelfs
into: [:rep :labelWasUsed|
replacement := rep.
labelWasUsed ifTrue: [labelUsed := true]].
"replaceNodesIn: is strictly top-down, so any replacement for ^expr ifTrue: [...^fu...] ifFalse: [...^bar...]
will prevent replacement of either ^fu or ^bar. The corollary is that ^expr ifTrue: [foo] ifFalse: [^bar]
must be transformed into expr ifTrue: [^foo] ifFalse: [^bar]"
(node expression isConditionalSend
and: [node expression hasExplicitReturn])
ifTrue:
[elisions add: node.
(node expression args reject: [:arg| arg endsWithReturn]) do:
[:nodeNeedingReturn|
self transformReturnSubExpression: nodeNeedingReturn statements last
toAssignmentOf: exitVar
andGoto: exitLabel
unless: eliminateReturnSelfs
into: [:rep :labelWasUsed|
replacement := rep.
labelWasUsed ifTrue: [labelUsed := true]].
map
at: nodeNeedingReturn statements last
put: replacement]]
ifFalse:
[map
at: node
put: (replacement ifNil:
[TLabeledCommentNode new setComment: 'return ', node expression printString])]]].
map isEmpty ifTrue:
[self deny: labelUsed.
^false].
"Now do a top-down replacement for all returns that should be mapped to assignments and gotos"
parseTree replaceNodesIn: map.
"Now it is safe to eliminate the returning ifs..."
elisions isEmpty ifFalse:
[| elisionMap |
elisionMap := Dictionary new.
elisions do: [:returnNode| elisionMap at: returnNode put: returnNode expression].
parseTree replaceNodesIn: elisionMap].
"Now flatten any new statement lists..."
parseTree nodesDo:
[:node| | list |
(node isStmtList
and: [node statements notEmpty
and: [node statements last isStmtList]]) ifTrue:
[list := node statements last statements.
node statements removeLast; addAllLast: list]].
^labelUsed
]
{ #category : #accessing }
TMethod >> export [
^ export
]
{ #category : #accessing }
TMethod >> export: aBoolean [
export := aBoolean
]
{ #category : #initialization }
TMethod >> extraVariableName: root [
extraVariableNumber := extraVariableNumber
ifNil: [0]
ifNotNil: [extraVariableNumber + 1].
^root, extraVariableNumber printString
]
{ #category : #transformations }
TMethod >> extraVariableNumber [
^extraVariableNumber
]
{ #category : #transformations }
TMethod >> extractDirective: theSelector valueBlock: aBlock default: defaultResult [
"Find a pragma of the form:
<theSelector[args]>
Answer the result of evaluating aBock with a TSendNode corresponding
to the pragma node, or defaultResult if there is no matching pragma."
| result found newStatements |
(properties at: theSelector ifAbsent: []) ifNotNil:
[:pragma|
^aBlock value: (TSendNode new
setSelector: pragma keyword
receiver: (TVariableNode new setName: 'self')
arguments: (pragma arguments collect: [:const| TConstantNode new setValue: const]))].
"Pre-pragma backward compatibility:
Scan the top-level statements for a labelling directive of the form:
self theSelector[args]
and remove the directive from the method body if found.
Answer the result of evaluating aBock with the send node,
or defaultResult if there is no labelling directive." result := defaultResult.
found := false.
newStatements := OrderedCollection new: parseTree statements size.
parseTree statements do:
[ :stmt |
(stmt isSend
and: [stmt selector = theSelector])
ifTrue:
[found := true.
result := aBlock value: stmt]
ifFalse:
[newStatements add: stmt]].
^found
ifTrue:
[parseTree setStatements: newStatements asArray.
result]
ifFalse: [defaultResult]
]
{ #category : #transformations }
TMethod >> extractExpandCaseDirective [
"Scan the top-level statements for an inlining directive of the form:
self expandCases
and remove the directive from the method body. Answer whether
there was such a directive."
^self
extractDirective: #expandCases
valueBlock: [:sendNode| true]
default: false
]
{ #category : #transformations }
TMethod >> extractExportDirective [
"Scan the top-level statements for an inlining directive of the form:
self export: <boolean>
and remove the directive from the method body. Answer the
argument of the directive or false if there is no export directive."
^self
extractDirective: #export:
valueBlock: [:sendNode| sendNode args first value ~= false]
default: false
]
{ #category : #'inlining support' }
TMethod >> extractInlineDirective [
"Scan the pragmas (or top-level statements) for an inlining directive of the form:
<inline: <boolean|#never|#dontCare|#asSpecified|#always>
Answer a boolean equivalent to the argument of the directive or #dontCare if there is no inlining directive."
sharedCase ifNotNil: [^false]. "don't auto-inline shared code; it gets handled specially"
^self
extractDirective: #inline:
valueBlock:
[:sendNode| #(true always) includes: (inline := sendNode args first value)]
default: #dontCare
]
{ #category : #transformations }
TMethod >> extractSharedCase [
"Scan the pragmas for an shared case directive of the form:
<sharedCodeNamed: 'sharedLabel' inCase: 'sharedCase'.>
<sharedCodeInCase: 'sharedCase'.>
or the older top-level statements for the form
self sharedCodeNamed: 'sharedLabel' inCase: 'sharedCase'.
self sharedCodeInCase: 'sharedCase'.
in which case remove the directive from the method body."
self extractDirective: #sharedCodeNamed:inCase:
valueBlock: [:sendNode|
args isEmpty ifFalse:
[self error: 'Cannot share code sections in methods with arguments'].
sharedLabel := sendNode args first value.
sharedCase := sendNode args last value]
default: nil.
self extractDirective: #sharedCodeInCase:
valueBlock: [:sendNode|
args isEmpty ifFalse:
[self error: 'Cannot share code sections in methods with arguments'].
sharedLabel := selector.
sharedCase := sendNode args last value]
default: nil
]
{ #category : #transformations }
TMethod >> extractStaticDirective [
"Scan the top-level statements for an inlining directive of the form:
self static: <boolean>
and remove the directive from the method body. Answer the
argument of the directive or true if there is no static directive."
^self
extractDirective: #static:
valueBlock: [:sendNode| sendNode args first value ~= false]
default: (export or: [(properties includesKey: #api) or: [properties includesKey: #api:]]) not
]
{ #category : #'primitive compilation' }
TMethod >> fetchRcvrExpr [
"Return the parse tree for an expression that fetches the receiver from the stack."
| expr |
expr := 'rcvr := ', self vmNameString, ' stackValue: (', args size printString, ')'.
^ self statementsFor: expr varName: ''
]
{ #category : #utilities }
TMethod >> findReadBeforeAssignedIn: variables in: aCodeGen [
| readBeforeAssigned |
readBeforeAssigned := Set new.
parseTree
addReadBeforeAssignedIn: variables
to: readBeforeAssigned
assignments: Set new
in: aCodeGen.
^readBeforeAssigned
]
{ #category : #'primitive compilation' }
TMethod >> fixUpReturns: argCount postlog: postlog [
"Replace each return statement in this method with (a) the given postlog, (b) code to pop the receiver and the given number of arguments, and (c) code to push the integer result and return."
| newStmts |
parseTree nodesDo: [:node |
node isStmtList ifTrue: [
newStmts := OrderedCollection new: 100.
node statements do: [:stmt |
stmt isReturn
ifTrue: [
(stmt expression isSend and: