-
Notifications
You must be signed in to change notification settings - Fork 68
/
TMethod.class.st
3355 lines (2911 loc) · 114 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',
'parseTree',
'primitive',
'properties',
'returnType',
'selector',
'sharedCase',
'sharedLabel',
'static',
'writtenToGlobalVarsCache',
'functionAttributes',
'cachedLocals'
],
#classVars : [
'CaseStatements'
],
#category : #'Slang-AST'
}
{ #category : #'class initialization' }
TMethod class >> initialize [
"TMethod initialize"
CaseStatements := IdentitySet new: 10.
CaseStatements addAll: #(dispatchOn:in: dispatchOn:in:with: dispatchOn:in:with:with:).
]
{ #category : #visiting }
TMethod >> accept: aVisitor [
^ aVisitor visitMethod: self
]
{ #category : #adding }
TMethod >> addCASTConditionalCompilationFor: cAST generator: aCodeGen [
| compileTimeOptionPragmas |
(compileTimeOptionPragmas := self compileTimeOptionPragmas: aCodeGen)
notEmpty ifTrue: [
| condition cppIf |
compileTimeOptionPragmas doWithIndex: [ :pragma :i |
| element |
element := CIdentifierNode name:
((compileTimeOptionPragmas at: i) argumentAt: 1).
pragma selector = #notOption: ifTrue: [
element := CUnaryOperatorNode operator: #! expression: element ].
i <= 1
ifTrue: [ condition := element ]
ifFalse: [
condition := CBinaryOperatorNode
operator: #&&
left: condition
right: element ] ].
cppIf := CPreprocessorIfNode if: condition then: cAST.
cAST isFunctionDeclarator ifTrue: [
(aCodeGen maybeGenerateCASTPrimitiveFailureDefineFor: selector)
ifNotNil: [ :define | cppIf else: define ] ].
^ cppIf ].
^ cAST
]
{ #category : #accessing }
TMethod >> addFunctionAttribute: aString [
functionAttributes := functionAttributes
ifNil: [aString]
ifNotNil: [functionAttributes, ' ', aString]
]
{ #category : #accessing }
TMethod >> addLabelsTo: aTMethod [
aTMethod labels addAll: labels
]
{ #category : #accessing }
TMethod >> addLocal: aString [
cachedLocals := nil.
self locals add: aString
]
{ #category : #adding }
TMethod >> addLocals: locals [
locals do: [ :local | self addLocal: local ]
]
{ #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 : #'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."
| newLocals |
newLocals := methodToBeInlined args , methodToBeInlined allLocals asOrderedCollection .
self addLocals: (newLocals copyWithoutAll: doNotRename).
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)"
| allLocals |
cachedLocals ifNotNil: [ ^ cachedLocals ].
allLocals := Set new.
allLocals addAll: (declarations keys asSet reject: [:k| (declarations at: k) == #implicit]).
allLocals addAll: self locals.
self nodesDo: [ :node |
node isStatementList ifTrue: [ allLocals addAll: node locals ] ].
^ cachedLocals := allLocals
]
{ #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 isStatementList ifTrue: [
node arguments ifNotNil: [ refs addAll: node arguments ] ].
(node isSend and: [ node selector value beginsWith: #cCode: ])
ifTrue: [ aCodeGen addVariablesInVerbatimCIn: node to: refs ] ]
unless: [ :node :parent |
parent notNil and: [
parent isSend and: [
aCodeGen nodeIsDeadCode: node withParent: parent ] ] ].
^ refs
]
{ #category : #accessing }
TMethod >> allStatements [
| statements |
statements := OrderedCollection new.
self allStatementsDo: [ :statement | statements add: statement ].
^ statements
]
{ #category : #accessing }
TMethod >> allStatementsDo: aFullBlockClosure [
"Iterate all statements in the tree with a block closure"
parseTree allStatementsDo: aFullBlockClosure
]
{ #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 arguments) size ifTrue: [
self assert: (meth args first beginsWith: 'self_in_').
argList := { aSendNode receiver } , aSendNode arguments ].
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).
self removeLocal: 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 : #'CAST translation' }
TMethod >> asCASTCommentIn: aCodeGen [
comment ifNotNil: [
^ CCommentNode comment: (String streamContents: [ :aStream |
aStream tab.
1 to: comment size do: [ :index |
self
printSingleComment: (comment at: index)
on: aStream
indent: 1
tabWidth: 4
lineBreak: 78 ].
aStream nextPut: Character space ]) ].
^ nil
]
{ #category : #'CAST translation' }
TMethod >> asCASTFunctionPrototypeIn: aCodeGen [
properties ifNotNil: [
(properties at: #api: ifAbsent: [ ]) ifNotNil: [ :pragma |
^ CRawCodeNode code: (pragma argumentAt: 1) , ';' ] ].
^ (self asCASTFunctionPrototypeIn: aCodeGen isPrototype: true)
isFunctionPrototype: true;
yourself
]
{ #category : #'CAST translation' }
TMethod >> asCASTFunctionPrototypeIn: aCodeGen isPrototype: isPrototype [
| returnTypeIsFunctionPointer specifiers arguments functionDeclaration |
specifiers := OrderedCollection new.
"If return type is a function pointer, the function prototype is contained in it, as a String. Maybe change it later, we dont want raw code in our C AST."
returnTypeIsFunctionPointer := returnType notNil and: [
returnType last = $) and: [
returnType includesSubstring:
(aCodeGen cFunctionNameFor:
selector) ] ].
export
ifTrue: [ specifiers add: 'EXPORT(' , returnType , ')' ]
ifFalse: [
self isStatic
ifTrue: [ specifiers add: 'static' ]
ifFalse: [ isPrototype ifTrue: [ specifiers add: 'extern' ] ].
(isPrototype or: [ inline ~~ #always ]) ifFalse: [
specifiers add: 'inline' ].
specifiers add: (returnType ifNil: [ #sqInt ]) ].
(functionAttributes isNil or: [ returnTypeIsFunctionPointer ])
ifFalse: [ specifiers add: functionAttributes ].
returnTypeIsFunctionPointer ifFalse: [
arguments := args isEmpty
ifTrue: [
{ (CParameterDeclarationNode declarator: (CIdentifierNode name: 'void')) } ]
ifFalse: [
args collect: [ :name |
CParameterDeclarationNode
declarator: (CIdentifierNode name: name)
cDeclaration: (self
declarationAt: name
ifAbsent: [ aCodeGen defaultType , ' ' , name ]) ] ] ].
functionDeclaration := isPrototype
ifTrue: [
CDeclarationNode
specifiers: specifiers
declarator: (CFunctionDeclaratorNode
declarator:
(CIdentifierNode name:
(aCodeGen cFunctionNameFor: selector))
parameters: arguments) ]
ifFalse: [
CFunctionDefinitionNode
declarator: (CFunctionDeclaratorNode
declarator:
(CIdentifierNode name:
(aCodeGen cFunctionNameFor: selector))
parameters: arguments)
specifiers: specifiers ].
returnTypeIsFunctionPointer ifTrue: [
functionDeclaration hasRawPrototype: true ].
^ functionDeclaration
]
{ #category : #'CAST translation' }
TMethod >> asCASTIn: aCodeGen [
| compoundStatement functionDefinition body|
aCodeGen currentMethod: self.
compoundStatement := CCompoundStatementNode new
needsBrackets: false;
yourself.
(self asCASTCommentIn: aCodeGen) ifNotNil: [ :e |
compoundStatement add: e ].
compoundStatement add:
(CCommentNode comment: (String streamContents: [ :aStream |
aStream
space;
nextPutAll: self definingClass name;
nextPutAll: '>>#';
nextPutAll: self smalltalkSelector;
space ])).
functionDefinition := self
asCASTFunctionPrototypeIn: aCodeGen
isPrototype: false.
aCodeGen
pushScope: self
while: [ body := (parseTree asCASTIn: aCodeGen) ].
functionDefinition body: body.
((returnType = #void) not and: [parseTree endsWithReturn not]) ifTrue: [
functionDefinition body
add: (CReturnStatementNode expression: (CConstantNode value: 0))
].
compoundStatement add: (self
addCASTConditionalCompilationFor: functionDefinition
generator: aCodeGen).
^ compoundStatement
]
{ #category : #'CAST translation' }
TMethod >> asCASTInlinedIn: aBuilder [
| compoundStatement body |
self removeUnusedTempsAndNilIfRequiredIn: aBuilder.
compoundStatement := CCompoundStatementNode new.
compoundStatement add: (aBuilder asmLabelNodeFor: selector ).
aBuilder
pushScope: self
while: [ body := (parseTree asCASTIn: aBuilder) ].
compoundStatement add: body.
sharedLabel ifNotNil: [
^ (CLabeledStatementNode new
label: (CIdentifierNode name: sharedLabel);
statement: compoundStatement;
comments: {selector};
yourself) ].
^ compoundStatement
]
{ #category : #linearisation }
TMethod >> asExpressionIn: aMLStatementListBuider [
"A TNode returns itself as an expression"
^ self
]
{ #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."
self parseTree: (parseTree bindVariablesIn: constantDictionary)
]
{ #category : #transformations }
TMethod >> bindVariableUsesIn: aDictionary [
self 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 >> bindVariablesIn: 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."
self parseTree: (parseTree bindVariablesIn: constantDictionary)
]
{ #category : #transformations }
TMethod >> bindVariablesIn: constantDictionary unless: cautionaryBlock [
"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."
(cautionaryBlock value: self) ifTrue: [^self].
self parseTree: (parseTree bindVariablesIn: constantDictionary unless: cautionaryBlock).
]
{ #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 arguments size >= 2 and: [
aSendNode arguments second isConstant and: [
aSendNode arguments second value isArray ] ]) ifFalse: [
self error: 'wrong node structure for a case statement' ].
unimplemented := aSendNode arguments 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 arguments first
selectors: aSendNode arguments second value
arguments:
(aSendNode arguments copyFrom: 3 to: aSendNode arguments 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 arguments first
otherwiseOrNil:
(aSendNode arguments at: 2 ifAbsent: [ nil ]).
(aSendNode receiver isVariable or: [ parentNode isStatementList ])
ifFalse: [
cachedLocals := nil.
switch switchVariable:
(self 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 >> children [
^ { parseTree }
]
{ #category : #accessing }
TMethod >> clearReferencesToGlobalStruct [
globalStructureBuildMethodHasFoo := false
]
{ #category : #accessing }
TMethod >> comment [
^comment
]
{ #category : #accessing }
TMethod >> comment: aComment [
comment := aComment
]
{ #category : #accessing }
TMethod >> compileTimeOptionPragmas: aCodeGenerator [
"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 selector or: [ #notOption: == pragma selector ])
and: [ aCodeGenerator 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: [(self allLocals 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 [
self error: 'Use declarationAt: arg ifAbsent: [aCodeGen defaultType, '' '', arg] instead'.
^declarations at: aVariableName ifAbsent: [#sqInt, ' ', aVariableName]
]
{ #category : #accessing }
TMethod >> declarationAt: aVariableName ifAbsent: absentBlock [
^declarations at: aVariableName ifAbsent: absentBlock
]
{ #category : #accessing }
TMethod >> declarationAt: aVariableName ifPresent: presentBlock [
^declarations at: aVariableName ifPresent: presentBlock
]
{ #category : #accessing }
TMethod >> declarationAt: aVariableName put: aDeclaration [
self validateVariableDeclarationExists: aVariableName.
^ declarations at: aVariableName put: aDeclaration
]
{ #category : #accessing }
TMethod >> declarations [
"The type declaration dictionary of this method."
^declarations
]
{ #category : #'automatic-localization' }
TMethod >> declareNonConflictingLocalNamedLike: aString [
| definedVariables n newVarName |
definedVariables := (self allLocals, args) asSet.
n := 1.
newVarName := aString.
[ definedVariables includes: newVarName ] whileTrue: [
newVarName := aString , n printString.
n := n + 1 ].
cachedLocals := nil.
self locals add: newVarName.
^ newVarName
]
{ #category : #testing }
TMethod >> declaresVariableWithName: aVariableName [
| referencesInScope |
referencesInScope := self allLocals , self args.
^ referencesInScope includes: aVariableName
]
{ #category : #testing }
TMethod >> definedAsComplexMacro [
^properties notNil and: [(properties includesKey: #cmacro:)]
]
{ #category : #testing }
TMethod >> definedAsMacro [
^self definedAsComplexMacro or: [
self definedAsValueMacro ]
]
{ #category : #testing }
TMethod >> definedAsValueMacro [
^properties notNil and: [(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 : #enumerating }
TMethod >> detect: aFullBlockClosure [
^ parseTree detect: aFullBlockClosure
]
{ #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 statements: stmtList ]
]
{ #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: aCodeGen)) 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
ifAbsent: [aCodeGen defaultType, ' ', 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
ifAbsent: [aCodeGen defaultType, ' ', 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 ifAbsent: [ aCodeGen defaultType, ' ', 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 ifAbsent: [ aCodeGen defaultType, ' ', 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 arguments first.
hasSideEffects := limitExpr anySatisfy: [ :subNode |
subNode isSend and: [
(aCodeGen isBuiltinSelector: subNode selector)
not and: [ (aCodeGen isStructSend: subNode) not ] ] ].
node arguments size = 4
ifTrue: [
hasSideEffects
ifTrue: [
cachedLocals := nil.
self addLocal: node arguments last name ]
ifFalse: [ node arguments: node arguments 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: self locals. "N.B. adds it to locals!!"
node arguments: node arguments , { (TVariableNode new
setName: var;
yourself) }.
declarations
at: node arguments third arguments first
ifPresent: [ :decl |
self
declarationAt: var
put:
(self
typeFor: node arguments third arguments 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: SlangClass) and: [definingClass isStructClass]) not
and: [returnType = #void or: [returnType = #sqInt]].
parseTree nodesDo:
[:node | | replacement |
node isReturn ifTrue:
[self transformReturnSubExpression: node
toAssignmentOf: exitVar
andGoto: exitLabel