/
Gen.java
2302 lines (2114 loc) · 90.2 KB
/
Gen.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 1999-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javac.jvm;
import java.util.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.comp.*;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.jvm.Code.*;
import com.sun.tools.javac.jvm.Items.*;
import com.sun.tools.javac.tree.JCTree.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*;
import static com.sun.tools.javac.jvm.ByteCodes.*;
import static com.sun.tools.javac.jvm.CRTFlags.*;
/** This pass maps flat Java (i.e. without inner classes) to bytecodes.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Gen extends JCTree.Visitor {
protected static final Context.Key<Gen> genKey =
new Context.Key<Gen>();
private final Log log;
private final Symtab syms;
private final Check chk;
private final Resolve rs;
private final TreeMaker make;
private final Name.Table names;
private final Target target;
private final Type stringBufferType;
private final Map<Type,Symbol> stringBufferAppend;
private Name accessDollar;
private final Types types;
/** Switch: GJ mode?
*/
private final boolean allowGenerics;
/** Set when Miranda method stubs are to be generated. */
private final boolean generateIproxies;
/** Format of stackmap tables to be generated. */
private final Code.StackMapFormat stackMap;
/** A type that serves as the expected type for all method expressions.
*/
private final Type methodType;
public static Gen instance(Context context) {
Gen instance = context.get(genKey);
if (instance == null)
instance = new Gen(context);
return instance;
}
protected Gen(Context context) {
context.put(genKey, this);
names = Name.Table.instance(context);
log = Log.instance(context);
syms = Symtab.instance(context);
chk = Check.instance(context);
rs = Resolve.instance(context);
make = TreeMaker.instance(context);
target = Target.instance(context);
types = Types.instance(context);
methodType = new MethodType(null, null, null, syms.methodClass);
allowGenerics = Source.instance(context).allowGenerics();
stringBufferType = target.useStringBuilder()
? syms.stringBuilderType
: syms.stringBufferType;
stringBufferAppend = new HashMap<Type,Symbol>();
accessDollar = names.
fromString("access" + target.syntheticNameChar());
Options options = Options.instance(context);
lineDebugInfo =
options.get("-g:") == null ||
options.get("-g:lines") != null;
varDebugInfo =
options.get("-g:") == null
? options.get("-g") != null
: options.get("-g:vars") != null;
genCrt = options.get("-Xjcov") != null;
debugCode = options.get("debugcode") != null;
generateIproxies =
target.requiresIproxy() ||
options.get("miranda") != null;
if (target.generateStackMapTable()) {
// ignore cldc because we cannot have both stackmap formats
this.stackMap = StackMapFormat.JSR202;
} else {
if (target.generateCLDCStackmap()) {
this.stackMap = StackMapFormat.CLDC;
} else {
this.stackMap = StackMapFormat.NONE;
}
}
// by default, avoid jsr's for simple finalizers
int setjsrlimit = 50;
String jsrlimitString = options.get("jsrlimit");
if (jsrlimitString != null) {
try {
setjsrlimit = Integer.parseInt(jsrlimitString);
} catch (NumberFormatException ex) {
// ignore ill-formed numbers for jsrlimit
}
}
this.jsrlimit = setjsrlimit;
this.useJsrLocally = false; // reset in visitTry
}
/** Switches
*/
private final boolean lineDebugInfo;
private final boolean varDebugInfo;
private final boolean genCrt;
private final boolean debugCode;
/** Default limit of (approximate) size of finalizer to inline.
* Zero means always use jsr. 100 or greater means never use
* jsr.
*/
private final int jsrlimit;
/** True if jsr is used.
*/
private boolean useJsrLocally;
/* Constant pool, reset by genClass.
*/
private Pool pool = new Pool();
/** Code buffer, set by genMethod.
*/
private Code code;
/** Items structure, set by genMethod.
*/
private Items items;
/** Environment for symbol lookup, set by genClass
*/
private Env<AttrContext> attrEnv;
/** The top level tree.
*/
private JCCompilationUnit toplevel;
/** The number of code-gen errors in this class.
*/
private int nerrs = 0;
/** A hash table mapping syntax trees to their ending source positions.
*/
private Map<JCTree, Integer> endPositions;
/** Generate code to load an integer constant.
* @param n The integer to be loaded.
*/
void loadIntConst(int n) {
items.makeImmediateItem(syms.intType, n).load();
}
/** The opcode that loads a zero constant of a given type code.
* @param tc The given type code (@see ByteCode).
*/
public static int zero(int tc) {
switch(tc) {
case INTcode: case BYTEcode: case SHORTcode: case CHARcode:
return iconst_0;
case LONGcode:
return lconst_0;
case FLOATcode:
return fconst_0;
case DOUBLEcode:
return dconst_0;
default:
throw new AssertionError("zero");
}
}
/** The opcode that loads a one constant of a given type code.
* @param tc The given type code (@see ByteCode).
*/
public static int one(int tc) {
return zero(tc) + 1;
}
/** Generate code to load -1 of the given type code (either int or long).
* @param tc The given type code (@see ByteCode).
*/
void emitMinusOne(int tc) {
if (tc == LONGcode) {
items.makeImmediateItem(syms.longType, new Long(-1)).load();
} else {
code.emitop0(iconst_m1);
}
}
/** Construct a symbol to reflect the qualifying type that should
* appear in the byte code as per JLS 13.1.
*
* For target >= 1.2: Clone a method with the qualifier as owner (except
* for those cases where we need to work around VM bugs).
*
* For target <= 1.1: If qualified variable or method is defined in a
* non-accessible class, clone it with the qualifier class as owner.
*
* @param sym The accessed symbol
* @param site The qualifier's type.
*/
Symbol binaryQualifier(Symbol sym, Type site) {
if (site.tag == ARRAY) {
if (sym == syms.lengthVar ||
sym.owner != syms.arrayClass)
return sym;
// array clone can be qualified by the array type in later targets
Symbol qualifier = target.arrayBinaryCompatibility()
? new ClassSymbol(Flags.PUBLIC, site.tsym.name,
site, syms.noSymbol)
: syms.objectType.tsym;
return sym.clone(qualifier);
}
if (sym.owner == site.tsym ||
(sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) {
return sym;
}
if (!target.obeyBinaryCompatibility())
return rs.isAccessible(attrEnv, (TypeSymbol)sym.owner)
? sym
: sym.clone(site.tsym);
if (!target.interfaceFieldsBinaryCompatibility()) {
if ((sym.owner.flags() & INTERFACE) != 0 && sym.kind == VAR)
return sym;
}
// leave alone methods inherited from Object
// JLS2 13.1.
if (sym.owner == syms.objectType.tsym)
return sym;
if (!target.interfaceObjectOverridesBinaryCompatibility()) {
if ((sym.owner.flags() & INTERFACE) != 0 &&
syms.objectType.tsym.members().lookup(sym.name).scope != null)
return sym;
}
return sym.clone(site.tsym);
}
/** Insert a reference to given type in the constant pool,
* checking for an array with too many dimensions;
* return the reference's index.
* @param type The type for which a reference is inserted.
*/
int makeRef(DiagnosticPosition pos, Type type) {
checkDimension(pos, type);
return pool.put(type.tag == CLASS ? (Object)type.tsym : (Object)type);
}
/** Check if the given type is an array with too many dimensions.
*/
private void checkDimension(DiagnosticPosition pos, Type t) {
switch (t.tag) {
case METHOD:
checkDimension(pos, t.getReturnType());
for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail)
checkDimension(pos, args.head);
break;
case ARRAY:
if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) {
log.error(pos, "limit.dimensions");
nerrs++;
}
break;
default:
break;
}
}
/** Create a tempory variable.
* @param type The variable's type.
*/
LocalItem makeTemp(Type type) {
VarSymbol v = new VarSymbol(Flags.SYNTHETIC,
names.empty,
type,
env.enclMethod.sym);
code.newLocal(v);
return items.makeLocalItem(v);
}
/** Generate code to call a non-private method or constructor.
* @param pos Position to be used for error reporting.
* @param site The type of which the method is a member.
* @param name The method's name.
* @param argtypes The method's argument types.
* @param isStatic A flag that indicates whether we call a
* static or instance method.
*/
void callMethod(DiagnosticPosition pos,
Type site, Name name, List<Type> argtypes,
boolean isStatic) {
Symbol msym = rs.
resolveInternalMethod(pos, attrEnv, site, name, argtypes, null);
if (isStatic) items.makeStaticItem(msym).invoke();
else items.makeMemberItem(msym, name == names.init).invoke();
}
/** Is the given method definition an access method
* resulting from a qualified super? This is signified by an odd
* access code.
*/
private boolean isAccessSuper(JCMethodDecl enclMethod) {
return
(enclMethod.mods.flags & SYNTHETIC) != 0 &&
isOddAccessName(enclMethod.name);
}
/** Does given name start with "access$" and end in an odd digit?
*/
private boolean isOddAccessName(Name name) {
return
name.startsWith(accessDollar) &&
(name.byteAt(name.len - 1) & 1) == 1;
}
/* ************************************************************************
* Non-local exits
*************************************************************************/
/** Generate code to invoke the finalizer associated with given
* environment.
* Any calls to finalizers are appended to the environments `cont' chain.
* Mark beginning of gap in catch all range for finalizer.
*/
void genFinalizer(Env<GenContext> env) {
if (code.isAlive() && env.info.finalize != null)
env.info.finalize.gen();
}
/** Generate code to call all finalizers of structures aborted by
* a non-local
* exit. Return target environment of the non-local exit.
* @param target The tree representing the structure that's aborted
* @param env The environment current at the non-local exit.
*/
Env<GenContext> unwind(JCTree target, Env<GenContext> env) {
Env<GenContext> env1 = env;
while (true) {
genFinalizer(env1);
if (env1.tree == target) break;
env1 = env1.next;
}
return env1;
}
/** Mark end of gap in catch-all range for finalizer.
* @param env the environment which might contain the finalizer
* (if it does, env.info.gaps != null).
*/
void endFinalizerGap(Env<GenContext> env) {
if (env.info.gaps != null && env.info.gaps.length() % 2 == 1)
env.info.gaps.append(code.curPc());
}
/** Mark end of all gaps in catch-all ranges for finalizers of environments
* lying between, and including to two environments.
* @param from the most deeply nested environment to mark
* @param to the least deeply nested environment to mark
*/
void endFinalizerGaps(Env<GenContext> from, Env<GenContext> to) {
Env<GenContext> last = null;
while (last != to) {
endFinalizerGap(from);
last = from;
from = from.next;
}
}
/** Do any of the structures aborted by a non-local exit have
* finalizers that require an empty stack?
* @param target The tree representing the structure that's aborted
* @param env The environment current at the non-local exit.
*/
boolean hasFinally(JCTree target, Env<GenContext> env) {
while (env.tree != target) {
if (env.tree.getTag() == JCTree.TRY && env.info.finalize.hasFinalizer())
return true;
env = env.next;
}
return false;
}
/* ************************************************************************
* Normalizing class-members.
*************************************************************************/
/** Distribute member initializer code into constructors and <clinit>
* method.
* @param defs The list of class member declarations.
* @param c The enclosing class.
*/
List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
ListBuffer<JCStatement> initCode = new ListBuffer<JCStatement>();
ListBuffer<JCStatement> clinitCode = new ListBuffer<JCStatement>();
ListBuffer<JCTree> methodDefs = new ListBuffer<JCTree>();
// Sort definitions into three listbuffers:
// - initCode for instance initializers
// - clinitCode for class initializers
// - methodDefs for method definitions
for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
JCTree def = l.head;
switch (def.getTag()) {
case JCTree.BLOCK:
JCBlock block = (JCBlock)def;
if ((block.flags & STATIC) != 0)
clinitCode.append(block);
else
initCode.append(block);
break;
case JCTree.METHODDEF:
methodDefs.append(def);
break;
case JCTree.VARDEF:
JCVariableDecl vdef = (JCVariableDecl) def;
VarSymbol sym = vdef.sym;
checkDimension(vdef.pos(), sym.type);
if (vdef.init != null) {
if ((sym.flags() & STATIC) == 0) {
// Always initialize instance variables.
JCStatement init = make.at(vdef.pos()).
Assignment(sym, vdef.init);
initCode.append(init);
if (endPositions != null) {
Integer endPos = endPositions.remove(vdef);
if (endPos != null) endPositions.put(init, endPos);
}
} else if (sym.getConstValue() == null) {
// Initialize class (static) variables only if
// they are not compile-time constants.
JCStatement init = make.at(vdef.pos).
Assignment(sym, vdef.init);
clinitCode.append(init);
if (endPositions != null) {
Integer endPos = endPositions.remove(vdef);
if (endPos != null) endPositions.put(init, endPos);
}
} else {
checkStringConstant(vdef.init.pos(), sym.getConstValue());
}
}
break;
default:
assert false;
}
}
// Insert any instance initializers into all constructors.
if (initCode.length() != 0) {
List<JCStatement> inits = initCode.toList();
for (JCTree t : methodDefs) {
normalizeMethod((JCMethodDecl)t, inits);
}
}
// If there are class initializers, create a <clinit> method
// that contains them as its body.
if (clinitCode.length() != 0) {
MethodSymbol clinit = new MethodSymbol(
STATIC, names.clinit,
new MethodType(
List.<Type>nil(), syms.voidType,
List.<Type>nil(), syms.methodClass),
c);
c.members().enter(clinit);
List<JCStatement> clinitStats = clinitCode.toList();
JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
block.endpos = TreeInfo.endPos(clinitStats.last());
methodDefs.append(make.MethodDef(clinit, block));
}
// Return all method definitions.
return methodDefs.toList();
}
/** Check a constant value and report if it is a string that is
* too large.
*/
private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
if (nerrs != 0 || // only complain about a long string once
constValue == null ||
!(constValue instanceof String) ||
((String)constValue).length() < Pool.MAX_STRING_LENGTH)
return;
log.error(pos, "limit.string");
nerrs++;
}
/** Insert instance initializer code into initial constructor.
* @param md The tree potentially representing a
* constructor's definition.
* @param initCode The list of instance initializer statements.
*/
void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode) {
if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
// We are seeing a constructor that does not call another
// constructor of the same class.
List<JCStatement> stats = md.body.stats;
ListBuffer<JCStatement> newstats = new ListBuffer<JCStatement>();
if (stats.nonEmpty()) {
// Copy initializers of synthetic variables generated in
// the translation of inner classes.
while (TreeInfo.isSyntheticInit(stats.head)) {
newstats.append(stats.head);
stats = stats.tail;
}
// Copy superclass constructor call
newstats.append(stats.head);
stats = stats.tail;
// Copy remaining synthetic initializers.
while (stats.nonEmpty() &&
TreeInfo.isSyntheticInit(stats.head)) {
newstats.append(stats.head);
stats = stats.tail;
}
// Now insert the initializer code.
newstats.appendList(initCode);
// And copy all remaining statements.
while (stats.nonEmpty()) {
newstats.append(stats.head);
stats = stats.tail;
}
}
md.body.stats = newstats.toList();
if (md.body.endpos == Position.NOPOS)
md.body.endpos = TreeInfo.endPos(md.body.stats.last());
}
}
/* ********************************************************************
* Adding miranda methods
*********************************************************************/
/** Add abstract methods for all methods defined in one of
* the interfaces of a given class,
* provided they are not already implemented in the class.
*
* @param c The class whose interfaces are searched for methods
* for which Miranda methods should be added.
*/
void implementInterfaceMethods(ClassSymbol c) {
implementInterfaceMethods(c, c);
}
/** Add abstract methods for all methods defined in one of
* the interfaces of a given class,
* provided they are not already implemented in the class.
*
* @param c The class whose interfaces are searched for methods
* for which Miranda methods should be added.
* @param site The class in which a definition may be needed.
*/
void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) {
for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) {
ClassSymbol i = (ClassSymbol)l.head.tsym;
for (Scope.Entry e = i.members().elems;
e != null;
e = e.sibling)
{
if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0)
{
MethodSymbol absMeth = (MethodSymbol)e.sym;
MethodSymbol implMeth = absMeth.binaryImplementation(site, types);
if (implMeth == null)
addAbstractMethod(site, absMeth);
else if ((implMeth.flags() & IPROXY) != 0)
adjustAbstractMethod(site, implMeth, absMeth);
}
}
implementInterfaceMethods(i, site);
}
}
/** Add an abstract methods to a class
* which implicitly implements a method defined in some interface
* implemented by the class. These methods are called "Miranda methods".
* Enter the newly created method into its enclosing class scope.
* Note that it is not entered into the class tree, as the emitter
* doesn't need to see it there to emit an abstract method.
*
* @param c The class to which the Miranda method is added.
* @param m The interface method symbol for which a Miranda method
* is added.
*/
private void addAbstractMethod(ClassSymbol c,
MethodSymbol m) {
MethodSymbol absMeth = new MethodSymbol(
m.flags() | IPROXY | SYNTHETIC, m.name,
m.type, // was c.type.memberType(m), but now only !generics supported
c);
c.members().enter(absMeth); // add to symbol table
}
private void adjustAbstractMethod(ClassSymbol c,
MethodSymbol pm,
MethodSymbol im) {
MethodType pmt = (MethodType)pm.type;
Type imt = types.memberType(c.type, im);
pmt.thrown = chk.intersect(pmt.getThrownTypes(), imt.getThrownTypes());
}
/* ************************************************************************
* Traversal methods
*************************************************************************/
/** Visitor argument: The current environment.
*/
Env<GenContext> env;
/** Visitor argument: The expected type (prototype).
*/
Type pt;
/** Visitor result: The item representing the computed value.
*/
Item result;
/** Visitor method: generate code for a definition, catching and reporting
* any completion failures.
* @param tree The definition to be visited.
* @param env The environment current at the definition.
*/
public void genDef(JCTree tree, Env<GenContext> env) {
Env<GenContext> prevEnv = this.env;
try {
this.env = env;
tree.accept(this);
} catch (CompletionFailure ex) {
chk.completionError(tree.pos(), ex);
} finally {
this.env = prevEnv;
}
}
/** Derived visitor method: check whether CharacterRangeTable
* should be emitted, if so, put a new entry into CRTable
* and call method to generate bytecode.
* If not, just call method to generate bytecode.
* @see #genStat(Tree, Env)
*
* @param tree The tree to be visited.
* @param env The environment to use.
* @param crtFlags The CharacterRangeTable flags
* indicating type of the entry.
*/
public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) {
if (!genCrt) {
genStat(tree, env);
return;
}
int startpc = code.curPc();
genStat(tree, env);
if (tree.getTag() == JCTree.BLOCK) crtFlags |= CRT_BLOCK;
code.crt.put(tree, crtFlags, startpc, code.curPc());
}
/** Derived visitor method: generate code for a statement.
*/
public void genStat(JCTree tree, Env<GenContext> env) {
if (code.isAlive()) {
code.statBegin(tree.pos);
genDef(tree, env);
} else if (env.info.isSwitch && tree.getTag() == JCTree.VARDEF) {
// variables whose declarations are in a switch
// can be used even if the decl is unreachable.
code.newLocal(((JCVariableDecl) tree).sym);
}
}
/** Derived visitor method: check whether CharacterRangeTable
* should be emitted, if so, put a new entry into CRTable
* and call method to generate bytecode.
* If not, just call method to generate bytecode.
* @see #genStats(List, Env)
*
* @param trees The list of trees to be visited.
* @param env The environment to use.
* @param crtFlags The CharacterRangeTable flags
* indicating type of the entry.
*/
public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) {
if (!genCrt) {
genStats(trees, env);
return;
}
if (trees.length() == 1) { // mark one statement with the flags
genStat(trees.head, env, crtFlags | CRT_STATEMENT);
} else {
int startpc = code.curPc();
genStats(trees, env);
code.crt.put(trees, crtFlags, startpc, code.curPc());
}
}
/** Derived visitor method: generate code for a list of statements.
*/
public void genStats(List<? extends JCTree> trees, Env<GenContext> env) {
for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
genStat(l.head, env, CRT_STATEMENT);
}
/** Derived visitor method: check whether CharacterRangeTable
* should be emitted, if so, put a new entry into CRTable
* and call method to generate bytecode.
* If not, just call method to generate bytecode.
* @see #genCond(Tree,boolean)
*
* @param tree The tree to be visited.
* @param crtFlags The CharacterRangeTable flags
* indicating type of the entry.
*/
public CondItem genCond(JCTree tree, int crtFlags) {
if (!genCrt) return genCond(tree, false);
int startpc = code.curPc();
CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0);
code.crt.put(tree, crtFlags, startpc, code.curPc());
return item;
}
/** Derived visitor method: generate code for a boolean
* expression in a control-flow context.
* @param _tree The expression to be visited.
* @param markBranches The flag to indicate that the condition is
* a flow controller so produced conditions
* should contain a proper tree to generate
* CharacterRangeTable branches for them.
*/
public CondItem genCond(JCTree _tree, boolean markBranches) {
JCTree inner_tree = TreeInfo.skipParens(_tree);
if (inner_tree.getTag() == JCTree.CONDEXPR) {
JCConditional tree = (JCConditional)inner_tree;
CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER);
if (cond.isTrue()) {
code.resolve(cond.trueJumps);
CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET);
if (markBranches) result.tree = tree.truepart;
return result;
}
if (cond.isFalse()) {
code.resolve(cond.falseJumps);
CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET);
if (markBranches) result.tree = tree.falsepart;
return result;
}
Chain secondJumps = cond.jumpFalse();
code.resolve(cond.trueJumps);
CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET);
if (markBranches) first.tree = tree.truepart;
Chain falseJumps = first.jumpFalse();
code.resolve(first.trueJumps);
Chain trueJumps = code.branch(goto_);
code.resolve(secondJumps);
CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET);
CondItem result = items.makeCondItem(second.opcode,
code.mergeChains(trueJumps, second.trueJumps),
code.mergeChains(falseJumps, second.falseJumps));
if (markBranches) result.tree = tree.falsepart;
return result;
} else {
CondItem result = genExpr(_tree, syms.booleanType).mkCond();
if (markBranches) result.tree = _tree;
return result;
}
}
/** Visitor method: generate code for an expression, catching and reporting
* any completion failures.
* @param tree The expression to be visited.
* @param pt The expression's expected type (proto-type).
*/
public Item genExpr(JCTree tree, Type pt) {
Type prevPt = this.pt;
try {
if (tree.type.constValue() != null) {
// Short circuit any expressions which are constants
checkStringConstant(tree.pos(), tree.type.constValue());
result = items.makeImmediateItem(tree.type, tree.type.constValue());
} else {
this.pt = pt;
tree.accept(this);
}
return result.coerce(pt);
} catch (CompletionFailure ex) {
chk.completionError(tree.pos(), ex);
code.state.stacksize = 1;
return items.makeStackItem(pt);
} finally {
this.pt = prevPt;
}
}
/** Derived visitor method: generate code for a list of method arguments.
* @param trees The argument expressions to be visited.
* @param pts The expression's expected types (i.e. the formal parameter
* types of the invoked method).
*/
public void genArgs(List<JCExpression> trees, List<Type> pts) {
for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
genExpr(l.head, pts.head).load();
pts = pts.tail;
}
// require lists be of same length
assert pts.isEmpty();
}
/* ************************************************************************
* Visitor methods for statements and definitions
*************************************************************************/
/** Thrown when the byte code size exceeds limit.
*/
public static class CodeSizeOverflow extends RuntimeException {
private static final long serialVersionUID = 0;
public CodeSizeOverflow() {}
}
public void visitMethodDef(JCMethodDecl tree) {
// Create a new local environment that points pack at method
// definition.
Env<GenContext> localEnv = env.dup(tree);
localEnv.enclMethod = tree;
// The expected type of every return statement in this method
// is the method's return type.
this.pt = tree.sym.erasure(types).getReturnType();
checkDimension(tree.pos(), tree.sym.erasure(types));
genMethod(tree, localEnv, false);
}
//where
/** Generate code for a method.
* @param tree The tree representing the method definition.
* @param env The environment current for the method body.
* @param fatcode A flag that indicates whether all jumps are
* within 32K. We first invoke this method under
* the assumption that fatcode == false, i.e. all
* jumps are within 32K. If this fails, fatcode
* is set to true and we try again.
*/
void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
MethodSymbol meth = tree.sym;
// System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) +
(((tree.mods.flags & STATIC) == 0 || meth.isConstructor()) ? 1 : 0) >
ClassFile.MAX_PARAMETERS) {
log.error(tree.pos(), "limit.parameters");
nerrs++;
}
else if (tree.body != null) {
// Create a new code structure and initialize it.
int startpcCrt = initCode(tree, env, fatcode);
try {
genStat(tree.body, env);
} catch (CodeSizeOverflow e) {
// Failed due to code limit, try again with jsr/ret
startpcCrt = initCode(tree, env, fatcode);
genStat(tree.body, env);
}
if (code.state.stacksize != 0) {
log.error(tree.body.pos(), "stack.sim.error", tree);
throw new AssertionError();
}
// If last statement could complete normally, insert a
// return at the end.
if (code.isAlive()) {
code.statBegin(TreeInfo.endPos(tree.body));
if (env.enclMethod == null ||
env.enclMethod.sym.type.getReturnType().tag == VOID) {
code.emitop0(return_);
} else {
// sometime dead code seems alive (4415991);
// generate a small loop instead
int startpc = code.entryPoint();
CondItem c = items.makeCondItem(goto_);
code.resolve(c.jumpTrue(), startpc);
}
}
if (genCrt)
code.crt.put(tree.body,
CRT_BLOCK,
startpcCrt,
code.curPc());
// End the scope of all local variables in variable info.
code.endScopes(0);
// If we exceeded limits, panic
if (code.checkLimits(tree.pos(), log)) {
nerrs++;
return;
}
// If we generated short code but got a long jump, do it again
// with fatCode = true.
if (!fatcode && code.fatcode) genMethod(tree, env, true);
// Clean up
if(stackMap == StackMapFormat.JSR202) {
code.lastFrame = null;
code.frameBeforeLast = null;
}
}
}
private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
MethodSymbol meth = tree.sym;
// Create a new code structure.
meth.code = code = new Code(meth,
fatcode,
lineDebugInfo ? toplevel.lineMap : null,
varDebugInfo,
stackMap,
debugCode,
genCrt ? new CRTable(tree, env.toplevel.endPositions)
: null,
syms,
types,
pool);
items = new Items(pool, code, syms, types);
if (code.debugCode)
System.err.println(meth + " for body " + tree);
// If method is not static, create a new local variable address
// for `this'.
if ((tree.mods.flags & STATIC) == 0) {
Type selfType = meth.owner.type;
if (meth.isConstructor() && selfType != syms.objectType)
selfType = UninitializedType.uninitializedThis(selfType);
code.setDefined(
code.newLocal(
new VarSymbol(FINAL, names._this, selfType, meth.owner)));
}
// Mark all parameters as defined from the beginning of
// the method.
for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
checkDimension(l.head.pos(), l.head.sym.type);
code.setDefined(code.newLocal(l.head.sym));
}
// Get ready to generate code for method body.
int startpcCrt = genCrt ? code.curPc() : 0;
code.entryPoint();