/
ExpressionCodegen.java
3813 lines (3191 loc) · 158 KB
/
ExpressionCodegen.java
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
/*
* Copyright 2010-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.codegen;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.org.objectweb.asm.Label;
import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method;
import org.jetbrains.jet.codegen.binding.CalculatedClosure;
import org.jetbrains.jet.codegen.binding.CodegenBinding;
import org.jetbrains.jet.codegen.binding.MutableClosure;
import org.jetbrains.jet.codegen.context.*;
import org.jetbrains.jet.codegen.inline.InlineCodegen;
import org.jetbrains.jet.codegen.inline.NameGenerator;
import org.jetbrains.jet.codegen.intrinsics.IntrinsicMethod;
import org.jetbrains.jet.codegen.signature.JvmMethodSignature;
import org.jetbrains.jet.codegen.state.GenerationState;
import org.jetbrains.jet.codegen.state.JetTypeMapper;
import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils;
import org.jetbrains.jet.lang.evaluate.EvaluatePackage;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
import org.jetbrains.jet.lang.resolve.calls.model.*;
import org.jetbrains.jet.lang.resolve.calls.util.CallMaker;
import org.jetbrains.jet.lang.resolve.constants.CompileTimeConstant;
import org.jetbrains.jet.lang.resolve.constants.IntegerValueTypeConstant;
import org.jetbrains.jet.lang.resolve.java.AsmTypeConstants;
import org.jetbrains.jet.lang.resolve.java.JvmAbi;
import org.jetbrains.jet.lang.resolve.java.descriptor.JavaClassDescriptor;
import org.jetbrains.jet.lang.resolve.java.descriptor.SamConstructorDescriptor;
import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.receivers.*;
import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
import org.jetbrains.jet.lexer.JetTokens;
import org.jetbrains.jet.renderer.DescriptorRenderer;
import java.util.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
import static org.jetbrains.jet.codegen.AsmUtil.*;
import static org.jetbrains.jet.codegen.CodegenUtil.*;
import static org.jetbrains.jet.codegen.FunctionTypesUtil.functionTypeToImpl;
import static org.jetbrains.jet.codegen.FunctionTypesUtil.getFunctionImplType;
import static org.jetbrains.jet.codegen.binding.CodegenBinding.*;
import static org.jetbrains.jet.lang.resolve.BindingContext.*;
import static org.jetbrains.jet.lang.resolve.BindingContextUtils.getNotNull;
import static org.jetbrains.jet.lang.resolve.BindingContextUtils.isVarCapturedInClosure;
import static org.jetbrains.jet.lang.resolve.java.AsmTypeConstants.*;
import static org.jetbrains.jet.lang.resolve.java.JvmAnnotationNames.KotlinSyntheticClass;
import static org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue.NO_RECEIVER;
public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implements LocalLookup, ParentCodegenAware {
private static final Set<DeclarationDescriptor> INTEGRAL_RANGES = KotlinBuiltIns.getInstance().getIntegralRanges();
private int myLastLineNumber = -1;
public final InstructionAdapter v;
final MethodVisitor methodVisitor;
final FrameMap myFrameMap;
final JetTypeMapper typeMapper;
private final GenerationState state;
private final Type returnType;
private final BindingContext bindingContext;
final MethodContext context;
private final CodegenStatementVisitor statementVisitor;
private final Stack<BlockStackElement> blockStackElements = new Stack<BlockStackElement>();
@Nullable
private final MemberCodegen parentCodegen;
/*
* When we create a temporary variable to hold some value not to compute it many times
* we put it into this map to emit access to that variable instead of evaluating the whole expression
*/
private final Map<JetElement, StackValue.Local> tempVariables = Maps.newHashMap();
@NotNull
private final TailRecursionCodegen tailRecursionCodegen;
public final CallGenerator defaultCallGenerator;
public CalculatedClosure generateObjectLiteral(GenerationState state, JetObjectLiteralExpression literal) {
JetObjectDeclaration objectDeclaration = literal.getObjectDeclaration();
Type asmType = asmTypeForAnonymousClass(bindingContext, objectDeclaration);
ClassBuilder classBuilder = state.getFactory().newVisitor(asmType, literal.getContainingFile());
ClassDescriptor classDescriptor = bindingContext.get(CLASS, objectDeclaration);
assert classDescriptor != null;
//noinspection SuspiciousMethodCalls
CalculatedClosure closure = bindingContext.get(CLOSURE, classDescriptor);
ClassContext objectContext = context.intoAnonymousClass(classDescriptor, this);
ImplementationBodyCodegen implementationBodyCodegen =
new ImplementationBodyCodegen(objectDeclaration, objectContext, classBuilder, state, getParentCodegen());
implementationBodyCodegen.generate();
return closure;
}
static class BlockStackElement {
}
static class LoopBlockStackElement extends BlockStackElement {
final Label continueLabel;
final Label breakLabel;
public final JetSimpleNameExpression targetLabel;
LoopBlockStackElement(Label breakLabel, Label continueLabel, JetSimpleNameExpression targetLabel) {
this.breakLabel = breakLabel;
this.continueLabel = continueLabel;
this.targetLabel = targetLabel;
}
}
static class FinallyBlockStackElement extends BlockStackElement {
List<Label> gaps = new ArrayList<Label>();
final JetTryExpression expression;
FinallyBlockStackElement(JetTryExpression expression) {
this.expression = expression;
}
private void addGapLabel(Label label){
gaps.add(label);
}
}
public ExpressionCodegen(
@NotNull MethodVisitor v,
@NotNull FrameMap myMap,
@NotNull Type returnType,
@NotNull MethodContext context,
@NotNull GenerationState state,
@Nullable MemberCodegen parentCodegen
) {
this.myFrameMap = myMap;
this.parentCodegen = parentCodegen;
this.typeMapper = state.getTypeMapper();
this.returnType = returnType;
this.state = state;
this.methodVisitor = v;
this.v = new InstructionAdapter(methodVisitor);
this.bindingContext = state.getBindingContext();
this.context = context;
this.statementVisitor = new CodegenStatementVisitor(this);
this.tailRecursionCodegen = new TailRecursionCodegen(context, this, this.v, state);
this.defaultCallGenerator = new CallGenerator.DefaultCallGenerator(this);
}
public GenerationState getState() {
return state;
}
@NotNull
private StackValue castToRequiredTypeOfInterfaceIfNeeded(
StackValue inner,
@NotNull ClassDescriptor provided,
@NotNull ClassDescriptor required
) {
if (!isInterface(provided) && isInterface(required)) {
inner.put(OBJECT_TYPE, v);
Type type = asmType(required.getDefaultType());
v.checkcast(type);
return StackValue.onStack(type);
}
return inner;
}
public BindingContext getBindingContext() {
return bindingContext;
}
@Nullable
@Override
public MemberCodegen getParentCodegen() {
return parentCodegen;
}
public StackValue genQualified(StackValue receiver, JetElement selector) {
return genQualified(receiver, selector, this);
}
private StackValue genQualified(StackValue receiver, JetElement selector, JetVisitor<StackValue, StackValue> visitor) {
if (tempVariables.containsKey(selector)) {
throw new IllegalStateException("Inconsistent state: expression saved to a temporary variable is a selector");
}
if (!(selector instanceof JetBlockExpression)) {
markLineNumber(selector);
}
try {
if (selector instanceof JetExpression) {
JetExpression expression = (JetExpression) selector;
JavaClassDescriptor samInterface = bindingContext.get(CodegenBinding.SAM_VALUE, expression);
if (samInterface != null) {
return genSamInterfaceValue(expression, samInterface, visitor);
}
}
return selector.accept(visitor, receiver);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (CompilationException e) {
throw e;
}
catch (Throwable error) {
String message = error.getMessage();
throw new CompilationException(message != null ? message : "null", error, selector);
}
}
public StackValue gen(JetElement expr) {
StackValue tempVar = tempVariables.get(expr);
return tempVar != null ? tempVar : genQualified(StackValue.none(), expr);
}
public void gen(JetElement expr, Type type) {
StackValue value = gen(expr);
value.put(type, v);
}
public void genToJVMStack(JetExpression expr) {
gen(expr, expressionType(expr));
}
private StackValue genStatement(JetElement statement) {
return genQualified(StackValue.none(), statement, statementVisitor);
}
@Override
public StackValue visitClass(@NotNull JetClass klass, StackValue data) {
return visitClassOrObject(klass);
}
private StackValue visitClassOrObject(JetClassOrObject declaration) {
ClassDescriptor descriptor = bindingContext.get(BindingContext.CLASS, declaration);
assert descriptor != null;
Type asmType = asmTypeForAnonymousClass(bindingContext, declaration);
ClassBuilder classBuilder = state.getFactory().newVisitor(asmType, declaration.getContainingFile());
ClassContext objectContext = context.intoAnonymousClass(descriptor, this);
new ImplementationBodyCodegen(declaration, objectContext, classBuilder, state, getParentCodegen()).generate();
classBuilder.done();
return StackValue.none();
}
@Override
public StackValue visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, StackValue data) {
return visitClassOrObject(declaration);
}
@Override
public StackValue visitExpression(@NotNull JetExpression expression, StackValue receiver) {
throw new UnsupportedOperationException("Codegen for " + expression + " is not yet implemented");
}
@Override
public StackValue visitSuperExpression(@NotNull JetSuperExpression expression, StackValue data) {
return StackValue.thisOrOuter(this, getSuperCallLabelTarget(expression), true, true);
}
private ClassDescriptor getSuperCallLabelTarget(JetSuperExpression expression) {
return getSuperCallLabelTarget(expression, bindingContext, context);
}
@NotNull
private static ClassDescriptor getSuperCallLabelTarget(JetSuperExpression expression, BindingContext bindingContext, CodegenContext context) {
PsiElement labelPsi = bindingContext.get(BindingContext.LABEL_TARGET, expression.getTargetLabel());
ClassDescriptor labelTarget = (ClassDescriptor) bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, labelPsi);
DeclarationDescriptor descriptor = bindingContext.get(BindingContext.REFERENCE_TARGET, expression.getInstanceReference());
// "super<descriptor>@labelTarget"
if (labelTarget != null) {
return labelTarget;
}
assert descriptor instanceof ClassDescriptor : "Don't know how to generate super-call to not a class";
return getParentContextSubclassOf((ClassDescriptor) descriptor, context).getThisDescriptor();
}
@NotNull
private Type asmType(@NotNull JetType type) {
return typeMapper.mapType(type);
}
@NotNull
private Type asmTypeOrVoid(@Nullable JetType type) {
return type == null ? Type.VOID_TYPE : asmType(type);
}
@Override
public StackValue visitParenthesizedExpression(@NotNull JetParenthesizedExpression expression, StackValue receiver) {
return genQualified(receiver, expression.getExpression());
}
@Override
public StackValue visitAnnotatedExpression(@NotNull JetAnnotatedExpression expression, StackValue receiver) {
return genQualified(receiver, expression.getBaseExpression());
}
private static boolean isEmptyExpression(@Nullable JetElement expr) {
if (expr == null) {
return true;
}
if (expr instanceof JetBlockExpression) {
JetBlockExpression blockExpression = (JetBlockExpression) expr;
List<JetElement> statements = blockExpression.getStatements();
if (statements.size() == 0 || statements.size() == 1 && isEmptyExpression(statements.get(0))) {
return true;
}
}
return false;
}
@Override
public StackValue visitIfExpression(@NotNull JetIfExpression expression, StackValue receiver) {
return generateIfExpression(expression, false);
}
/* package */ StackValue generateIfExpression(JetIfExpression expression, boolean isStatement) {
Type asmType = isStatement ? Type.VOID_TYPE : expressionType(expression);
StackValue condition = gen(expression.getCondition());
JetExpression thenExpression = expression.getThen();
JetExpression elseExpression = expression.getElse();
if (isEmptyExpression(thenExpression)) {
if (isEmptyExpression(elseExpression)) {
condition.put(asmType, v);
return StackValue.onStack(asmType);
}
return generateSingleBranchIf(condition, expression, elseExpression, false, isStatement);
}
else {
if (isEmptyExpression(elseExpression)) {
return generateSingleBranchIf(condition, expression, thenExpression, true, isStatement);
}
}
Label elseLabel = new Label();
condition.condJump(elseLabel, true, v); // == 0, i.e. false
Label end = new Label();
gen(thenExpression, asmType);
v.goTo(end);
v.mark(elseLabel);
gen(elseExpression, asmType);
markLineNumber(expression);
v.mark(end);
return StackValue.onStack(asmType);
}
@Override
public StackValue visitWhileExpression(@NotNull JetWhileExpression expression, StackValue receiver) {
Label condition = new Label();
v.mark(condition);
Label end = new Label();
blockStackElements.push(new LoopBlockStackElement(end, condition, targetLabel(expression)));
StackValue conditionValue = gen(expression.getCondition());
conditionValue.condJump(end, true, v);
JetExpression body = expression.getBody();
if (body != null) {
gen(body, Type.VOID_TYPE);
}
v.goTo(condition);
v.mark(end);
blockStackElements.pop();
return StackValue.onStack(Type.VOID_TYPE);
}
@Override
public StackValue visitDoWhileExpression(@NotNull JetDoWhileExpression expression, StackValue receiver) {
Label continueLabel = new Label();
v.mark(continueLabel);
Label breakLabel = new Label();
blockStackElements.push(new LoopBlockStackElement(breakLabel, continueLabel, targetLabel(expression)));
JetExpression body = expression.getBody();
JetExpression condition = expression.getCondition();
StackValue conditionValue;
if (body instanceof JetBlockExpression) {
// If body's a block, it can contain variable declarations which may be used in the condition of a do-while loop.
// We handle this case separately because otherwise such variable will be out of the frame map after the block ends
List<JetElement> doWhileStatements = ((JetBlockExpression) body).getStatements();
List<JetElement> statements = new ArrayList<JetElement>(doWhileStatements.size() + 1);
statements.addAll(doWhileStatements);
statements.add(condition);
conditionValue = generateBlock(statements, true);
}
else {
if (body != null) {
gen(body, Type.VOID_TYPE);
}
conditionValue = gen(condition);
}
conditionValue.condJump(continueLabel, false, v);
v.mark(breakLabel);
blockStackElements.pop();
return StackValue.none();
}
@Override
public StackValue visitForExpression(@NotNull JetForExpression forExpression, StackValue receiver) {
// Is it a "1..2" or so
RangeCodegenUtil.BinaryCall binaryCall = RangeCodegenUtil.getRangeAsBinaryCall(forExpression);
if (binaryCall != null) {
ResolvedCall<?> resolvedCall = bindingContext.get(RESOLVED_CALL, binaryCall.op);
if (resolvedCall != null) {
if (RangeCodegenUtil.isOptimizableRangeTo(resolvedCall.getResultingDescriptor())) {
generateForLoop(new ForInRangeLiteralLoopGenerator(forExpression, binaryCall));
return StackValue.none();
}
}
}
JetExpression loopRange = forExpression.getLoopRange();
JetType loopRangeType = bindingContext.get(BindingContext.EXPRESSION_TYPE, loopRange);
assert loopRangeType != null;
Type asmLoopRangeType = asmType(loopRangeType);
if (asmLoopRangeType.getSort() == Type.ARRAY) {
generateForLoop(new ForInArrayLoopGenerator(forExpression));
return StackValue.none();
}
else {
if (RangeCodegenUtil.isRange(loopRangeType)) {
generateForLoop(new ForInRangeInstanceLoopGenerator(forExpression));
return StackValue.none();
}
if (RangeCodegenUtil.isProgression(loopRangeType)) {
generateForLoop(new ForInProgressionExpressionLoopGenerator(forExpression));
return StackValue.none();
}
generateForLoop(new IteratorForLoopGenerator(forExpression));
return StackValue.none();
}
}
private OwnerKind contextKind() {
return context.getContextKind();
}
private void generateForLoop(AbstractForLoopGenerator generator) {
Label loopExit = new Label();
Label loopEntry = new Label();
Label continueLabel = new Label();
generator.beforeLoop();
generator.checkEmptyLoop(loopExit);
v.mark(loopEntry);
generator.checkPreCondition(loopExit);
generator.beforeBody();
blockStackElements.push(new LoopBlockStackElement(loopExit, continueLabel, targetLabel(generator.forExpression)));
generator.body();
blockStackElements.pop();
v.mark(continueLabel);
generator.afterBody(loopExit);
v.goTo(loopEntry);
v.mark(loopExit);
generator.afterLoop();
}
private abstract class AbstractForLoopGenerator {
// for (e : E in c) {...}
protected final JetForExpression forExpression;
private final Label bodyStart = new Label();
private final Label bodyEnd = new Label();
private final List<Runnable> leaveVariableTasks = Lists.newArrayList();
protected final JetType elementType;
protected final Type asmElementType;
protected int loopParameterVar;
private AbstractForLoopGenerator(@NotNull JetForExpression forExpression) {
this.forExpression = forExpression;
this.elementType = getElementType(forExpression);
this.asmElementType = asmType(elementType);
}
@NotNull
private JetType getElementType(JetForExpression forExpression) {
JetExpression loopRange = forExpression.getLoopRange();
assert loopRange != null;
ResolvedCall<FunctionDescriptor> nextCall = getNotNull(bindingContext,
LOOP_RANGE_NEXT_RESOLVED_CALL, loopRange,
"No next() function " + DiagnosticUtils.atLocation(loopRange));
//noinspection ConstantConditions
return nextCall.getResultingDescriptor().getReturnType();
}
public void beforeLoop() {
JetParameter loopParameter = forExpression.getLoopParameter();
if (loopParameter != null) {
// E e = tmp<iterator>.next()
final VariableDescriptor parameterDescriptor = bindingContext.get(BindingContext.VALUE_PARAMETER, loopParameter);
@SuppressWarnings("ConstantConditions") final Type asmTypeForParameter = asmType(parameterDescriptor.getType());
loopParameterVar = myFrameMap.enter(parameterDescriptor, asmTypeForParameter);
scheduleLeaveVariable(new Runnable() {
@Override
public void run() {
myFrameMap.leave(parameterDescriptor);
v.visitLocalVariable(parameterDescriptor.getName().asString(),
asmTypeForParameter.getDescriptor(), null,
bodyStart, bodyEnd,
loopParameterVar);
}
});
}
else {
JetMultiDeclaration multiParameter = forExpression.getMultiParameter();
assert multiParameter != null;
// E tmp<e> = tmp<iterator>.next()
loopParameterVar = createLoopTempVariable(asmElementType);
}
}
public abstract void checkEmptyLoop(@NotNull Label loopExit);
public abstract void checkPreCondition(@NotNull Label loopExit);
public void beforeBody() {
v.mark(bodyStart);
assignToLoopParameter();
if (forExpression.getLoopParameter() == null) {
JetMultiDeclaration multiParameter = forExpression.getMultiParameter();
assert multiParameter != null;
generateMultiVariables(multiParameter.getEntries());
}
}
private void generateMultiVariables(List<JetMultiDeclarationEntry> entries) {
for (JetMultiDeclarationEntry variableDeclaration : entries) {
final VariableDescriptor componentDescriptor = bindingContext.get(BindingContext.VARIABLE, variableDeclaration);
@SuppressWarnings("ConstantConditions") final Type componentAsmType = asmType(componentDescriptor.getReturnType());
final int componentVarIndex = myFrameMap.enter(componentDescriptor, componentAsmType);
scheduleLeaveVariable(new Runnable() {
@Override
public void run() {
myFrameMap.leave(componentDescriptor);
v.visitLocalVariable(componentDescriptor.getName().asString(),
componentAsmType.getDescriptor(), null,
bodyStart, bodyEnd,
componentVarIndex);
}
});
ResolvedCall<FunctionDescriptor> resolvedCall =
bindingContext.get(BindingContext.COMPONENT_RESOLVED_CALL, variableDeclaration);
assert resolvedCall != null : "Resolved call is null for " + variableDeclaration.getText();
Call call = makeFakeCall(new TransientReceiver(elementType));
invokeFunction(call, StackValue.local(loopParameterVar, asmElementType), resolvedCall);
v.store(componentVarIndex, componentAsmType);
}
}
protected abstract void assignToLoopParameter();
protected abstract void increment(@NotNull Label loopExit);
public void body() {
JetExpression body = forExpression.getBody();
if (body != null) {
gen(body, Type.VOID_TYPE);
}
}
private void scheduleLeaveVariable(Runnable runnable) {
leaveVariableTasks.add(runnable);
}
protected int createLoopTempVariable(final Type type) {
int varIndex = myFrameMap.enterTemp(type);
scheduleLeaveVariable(new Runnable() {
@Override
public void run() {
myFrameMap.leaveTemp(type);
}
});
return varIndex;
}
public void afterBody(@NotNull Label loopExit) {
increment(loopExit);
v.mark(bodyEnd);
}
public void afterLoop() {
for (Runnable task : Lists.reverse(leaveVariableTasks)) {
task.run();
}
}
// This method consumes range/progression from stack
// The result is stored to local variable
protected void generateRangeOrProgressionProperty(Type loopRangeType, String getterName, Type elementType, int varToStore) {
Type boxedType = boxType(elementType);
v.invokevirtual(loopRangeType.getInternalName(), getterName, "()" + boxedType.getDescriptor());
StackValue.coerce(boxedType, elementType, v);
v.store(varToStore, elementType);
}
}
private class IteratorForLoopGenerator extends AbstractForLoopGenerator {
private int iteratorVarIndex;
private final ResolvedCall<FunctionDescriptor> iteratorCall;
private final ResolvedCall<FunctionDescriptor> nextCall;
private final Type asmTypeForIterator;
private IteratorForLoopGenerator(@NotNull JetForExpression forExpression) {
super(forExpression);
JetExpression loopRange = forExpression.getLoopRange();
assert loopRange != null;
this.iteratorCall = getNotNull(bindingContext,
LOOP_RANGE_ITERATOR_RESOLVED_CALL, loopRange,
"No .iterator() function " + DiagnosticUtils.atLocation(loopRange));
JetType iteratorType = iteratorCall.getResultingDescriptor().getReturnType();
assert iteratorType != null;
this.asmTypeForIterator = asmType(iteratorType);
this.nextCall = getNotNull(bindingContext,
LOOP_RANGE_NEXT_RESOLVED_CALL, loopRange,
"No next() function " + DiagnosticUtils.atLocation(loopRange));
}
@Override
public void beforeLoop() {
super.beforeLoop();
// Iterator<E> tmp<iterator> = c.iterator()
iteratorVarIndex = createLoopTempVariable(asmTypeForIterator);
Call call = bindingContext.get(LOOP_RANGE_ITERATOR_CALL, forExpression.getLoopRange());
invokeFunction(call, StackValue.none(), iteratorCall);
v.store(iteratorVarIndex, asmTypeForIterator);
}
@Override
public void checkEmptyLoop(@NotNull Label loopExit) {
}
@Override
public void checkPreCondition(@NotNull Label loopExit) {
// tmp<iterator>.hasNext()
JetExpression loopRange = forExpression.getLoopRange();
@SuppressWarnings("ConstantConditions") ResolvedCall<FunctionDescriptor> hasNextCall = getNotNull(bindingContext,
LOOP_RANGE_HAS_NEXT_RESOLVED_CALL, loopRange,
"No hasNext() function " + DiagnosticUtils.atLocation(loopRange));
@SuppressWarnings("ConstantConditions") Call fakeCall = makeFakeCall(new TransientReceiver(iteratorCall.getResultingDescriptor().getReturnType()));
invokeFunction(fakeCall, StackValue.local(iteratorVarIndex, asmTypeForIterator), hasNextCall);
JetType type = hasNextCall.getResultingDescriptor().getReturnType();
assert type != null && JetTypeChecker.INSTANCE.isSubtypeOf(type, KotlinBuiltIns.getInstance().getBooleanType());
Type asmType = asmType(type);
StackValue.coerce(asmType, Type.BOOLEAN_TYPE, v);
v.ifeq(loopExit);
}
@Override
protected void assignToLoopParameter() {
@SuppressWarnings("ConstantConditions") Call fakeCall =
makeFakeCall(new TransientReceiver(iteratorCall.getResultingDescriptor().getReturnType()));
invokeFunction(fakeCall, StackValue.local(iteratorVarIndex, asmTypeForIterator), nextCall);
//noinspection ConstantConditions
v.store(loopParameterVar, asmType(nextCall.getResultingDescriptor().getReturnType()));
}
@Override
protected void increment(@NotNull Label loopExit) {
}
}
private class ForInArrayLoopGenerator extends AbstractForLoopGenerator {
private int indexVar;
private int arrayVar;
private final JetType loopRangeType;
private ForInArrayLoopGenerator(@NotNull JetForExpression forExpression) {
super(forExpression);
loopRangeType = bindingContext.get(BindingContext.EXPRESSION_TYPE, forExpression.getLoopRange());
}
@Override
public void beforeLoop() {
super.beforeLoop();
indexVar = createLoopTempVariable(Type.INT_TYPE);
JetExpression loopRange = forExpression.getLoopRange();
StackValue value = gen(loopRange);
Type asmLoopRangeType = asmType(loopRangeType);
if (value instanceof StackValue.Local && value.type.equals(asmLoopRangeType)) {
arrayVar = ((StackValue.Local) value).index; // no need to copy local variable into another variable
}
else {
arrayVar = createLoopTempVariable(OBJECT_TYPE);
value.put(asmLoopRangeType, v);
v.store(arrayVar, OBJECT_TYPE);
}
v.iconst(0);
v.store(indexVar, Type.INT_TYPE);
}
@Override
public void checkEmptyLoop(@NotNull Label loopExit) {
}
@Override
public void checkPreCondition(@NotNull Label loopExit) {
v.load(indexVar, Type.INT_TYPE);
v.load(arrayVar, OBJECT_TYPE);
v.arraylength();
v.ificmpge(loopExit);
}
@Override
protected void assignToLoopParameter() {
Type arrayElParamType;
if (KotlinBuiltIns.getInstance().isArray(loopRangeType)) {
arrayElParamType = boxType(asmElementType);
}
else {
arrayElParamType = asmElementType;
}
v.load(arrayVar, OBJECT_TYPE);
v.load(indexVar, Type.INT_TYPE);
v.aload(arrayElParamType);
StackValue.onStack(arrayElParamType).put(asmElementType, v);
v.store(loopParameterVar, asmElementType);
}
@Override
protected void increment(@NotNull Label loopExit) {
v.iinc(indexVar, 1);
}
}
private abstract class AbstractForInProgressionOrRangeLoopGenerator extends AbstractForLoopGenerator {
protected int endVar;
// For integer progressions instead of comparing loopParameterVar with endVar at the beginning of an iteration we check whether
// loopParameterVar == finalVar at the end of the iteration (and also if there should be any iterations at all, before the loop)
protected final boolean isIntegerProgression;
private AbstractForInProgressionOrRangeLoopGenerator(@NotNull JetForExpression forExpression) {
super(forExpression);
switch (asmElementType.getSort()) {
case Type.INT:
case Type.BYTE:
case Type.SHORT:
case Type.CHAR:
case Type.LONG:
isIntegerProgression = true;
break;
case Type.DOUBLE:
case Type.FLOAT:
isIntegerProgression = false;
break;
default:
throw new IllegalStateException("Unexpected range element type: " + asmElementType);
}
}
@Override
public void beforeLoop() {
super.beforeLoop();
endVar = createLoopTempVariable(asmElementType);
}
// Index of the local variable holding the actual last value of the loop parameter.
// For ranges it equals end, for progressions it's a function of start, end and increment
protected abstract int getFinalVar();
protected void checkPostCondition(@NotNull Label loopExit) {
int finalVar = getFinalVar();
assert isIntegerProgression && finalVar != -1 :
"Post-condition should be checked only in case of integer progressions, finalVar = " + finalVar;
v.load(loopParameterVar, asmElementType);
v.load(finalVar, asmElementType);
if (asmElementType.getSort() == Type.LONG) {
v.lcmp();
v.ifeq(loopExit);
}
else {
v.ificmpeq(loopExit);
}
}
}
private abstract class AbstractForInRangeLoopGenerator extends AbstractForInProgressionOrRangeLoopGenerator {
private AbstractForInRangeLoopGenerator(@NotNull JetForExpression forExpression) {
super(forExpression);
}
@Override
public void beforeLoop() {
super.beforeLoop();
storeRangeStartAndEnd();
}
protected abstract void storeRangeStartAndEnd();
@Override
protected int getFinalVar() {
return endVar;
}
@Override
public void checkPreCondition(@NotNull Label loopExit) {
if (isIntegerProgression) return;
v.load(loopParameterVar, asmElementType);
v.load(endVar, asmElementType);
v.cmpg(asmElementType);
v.ifgt(loopExit);
}
@Override
public void checkEmptyLoop(@NotNull Label loopExit) {
if (!isIntegerProgression) return;
v.load(loopParameterVar, asmElementType);
v.load(endVar, asmElementType);
if (asmElementType.getSort() == Type.LONG) {
v.lcmp();
v.ifgt(loopExit);
}
else {
v.ificmpgt(loopExit);
}
}
@Override
protected void assignToLoopParameter() {
}
@Override
protected void increment(@NotNull Label loopExit) {
if (isIntegerProgression) {
checkPostCondition(loopExit);
}
if (asmElementType == Type.INT_TYPE) {
v.iinc(loopParameterVar, 1);
}
else {
v.load(loopParameterVar, asmElementType);
genIncrement(asmElementType, 1, v);
v.store(loopParameterVar, asmElementType);
}
}
}
private class ForInRangeLiteralLoopGenerator extends AbstractForInRangeLoopGenerator {
private final RangeCodegenUtil.BinaryCall rangeCall;
private ForInRangeLiteralLoopGenerator(
@NotNull JetForExpression forExpression,
@NotNull RangeCodegenUtil.BinaryCall rangeCall
) {
super(forExpression);
this.rangeCall = rangeCall;
}
@Override
protected void storeRangeStartAndEnd() {
gen(rangeCall.left, asmElementType);
v.store(loopParameterVar, asmElementType);
gen(rangeCall.right, asmElementType);
v.store(endVar, asmElementType);
}
}
private class ForInRangeInstanceLoopGenerator extends AbstractForInRangeLoopGenerator {
private ForInRangeInstanceLoopGenerator(@NotNull JetForExpression forExpression) {
super(forExpression);
}
@Override
protected void storeRangeStartAndEnd() {
JetType loopRangeType = bindingContext.get(EXPRESSION_TYPE, forExpression.getLoopRange());
assert loopRangeType != null;
Type asmLoopRangeType = asmType(loopRangeType);
gen(forExpression.getLoopRange(), asmLoopRangeType);
v.dup();
generateRangeOrProgressionProperty(asmLoopRangeType, "getStart", asmElementType, loopParameterVar);
generateRangeOrProgressionProperty(asmLoopRangeType, "getEnd", asmElementType, endVar);
}
}
private class ForInProgressionExpressionLoopGenerator extends AbstractForInProgressionOrRangeLoopGenerator {
private int incrementVar;
private Type incrementType;
private int finalVar;
private ForInProgressionExpressionLoopGenerator(@NotNull JetForExpression forExpression) {
super(forExpression);
}
@Override
protected int getFinalVar() {
return finalVar;
}
@Override
public void beforeLoop() {
super.beforeLoop();
incrementVar = createLoopTempVariable(asmElementType);