2 import IR.Tree.Modifiers;
3 import IR.Tree.FlagExpressionNode;
4 import IR.Tree.DNFFlag;
5 import IR.Tree.DNFFlagAtom;
6 import IR.Tree.TagExpressionList;
7 import IR.Tree.OffsetNode;
14 import Analysis.TaskStateAnalysis.FlagState;
15 import Analysis.TaskStateAnalysis.FlagComparator;
16 import Analysis.TaskStateAnalysis.OptionalTaskDescriptor;
17 import Analysis.TaskStateAnalysis.Predicate;
18 import Analysis.TaskStateAnalysis.SafetyAnalysis;
19 import Analysis.TaskStateAnalysis.TaskIndex;
20 import Analysis.CallGraph.CallGraph;
21 import Analysis.Loops.GlobalFieldType;
22 import Util.CodePrinter;
24 public class BuildCode {
27 Hashtable paramstable;
32 String localsprefix="___locals___";
33 String localsprefixaddr="&"+localsprefix;
34 String localsprefixderef=localsprefix+".";
35 String fcrevert="___fcrevert___";
36 String paramsprefix="___params___";
37 String nextobjstr="___nextobject___";
38 String localcopystr="___localcopy___";
39 public static boolean GENERATEPRECISEGC=false;
40 public static String PREFIX="";
41 public static String arraytype="ArrayObject";
42 public static int flagcount = 0;
45 protected int maxtaskparams=0;
46 protected int maxcount=0;
47 ClassDescriptor[] cdarray;
48 ClassDescriptor[] ifarray;
49 TypeDescriptor[] arraytable;
52 Hashtable<String, ClassDescriptor> printedfieldstbl;
53 int globaldefscount=0;
54 boolean mgcstaticinit = false;
56 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil) {
57 this(st, temptovar, typeutil, null);
60 public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa) {
63 callgraph=new CallGraph(state);
64 this.temptovar=temptovar;
65 paramstable=new Hashtable();
66 tempstable=new Hashtable();
67 fieldorder=new Hashtable();
68 flagorder=new Hashtable();
69 this.typeutil=typeutil;
71 virtualcalls=new Virtual(state, null);
72 printedfieldstbl = new Hashtable<String, ClassDescriptor>();
75 /** The buildCode method outputs C code for all the methods. The Flat
76 * versions of the methods must already be generated and stored in
77 * the State object. */
80 public void buildCode() {
81 /* Create output streams to write to */
82 PrintWriter outclassdefs=null;
83 PrintWriter outstructs=null;
84 PrintWriter outrepairstructs=null;
85 PrintWriter outmethodheader=null;
86 PrintWriter outmethod=null;
87 PrintWriter outvirtual=null;
88 PrintWriter outtask=null;
89 PrintWriter outtaskdefs=null;
90 PrintWriter outoptionalarrays=null;
91 PrintWriter optionalheaders=null;
92 PrintWriter outglobaldefs=null;
93 PrintWriter outglobaldefsprim=null;
96 buildCodeSetup(); //EXTENSION POINT
97 outstructs=new CodePrinter(new FileOutputStream(PREFIX+"structdefs.h"), true);
98 outmethodheader=new CodePrinter(new FileOutputStream(PREFIX+"methodheaders.h"), true);
99 outclassdefs=new CodePrinter(new FileOutputStream(PREFIX+"classdefs.h"), true);
100 outglobaldefs=new CodePrinter(new FileOutputStream(PREFIX+"globaldefs.h"), true);
101 outglobaldefsprim=new CodePrinter(new FileOutputStream(PREFIX+"globaldefsprim.h"), true);
102 outmethod=new CodePrinter(new FileOutputStream(PREFIX+"methods.c"), true);
103 outvirtual=new CodePrinter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
105 outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true);
106 outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
107 if (state.OPTIONAL) {
108 outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
109 optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
112 if (state.structfile!=null) {
113 outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
115 } catch (Exception e) {
120 /* Fix field safe symbols due to shadowing */
121 FieldShadow.handleFieldShadow(state);
123 /* Build the virtual dispatch tables */
124 buildVirtualTables(outvirtual);
126 /* Tag the methods that are invoked by static blocks */
127 tagMethodInvokedByStaticBlock();
129 /* Output includes */
130 outmethodheader.println("#ifndef METHODHEADERS_H");
131 outmethodheader.println("#define METHODHEADERS_H");
132 outmethodheader.println("#include \"structdefs.h\"");
134 if (state.EVENTMONITOR) {
135 outmethodheader.println("#include \"monitor.h\"");
138 additionalIncludesMethodsHeader(outmethodheader);
140 /* Output Structures */
141 outputStructs(outstructs);
143 // Output the C class declarations
144 // These could mutually reference each other
146 outglobaldefs.println("#ifndef __GLOBALDEF_H_");
147 outglobaldefs.println("#define __GLOBALDEF_H_");
148 outglobaldefs.println("");
149 outglobaldefs.println("struct global_defs_t {");
150 outglobaldefs.println(" int size;");
151 outglobaldefs.println(" void * next;");
152 outglobaldefsprim.println("#ifndef __GLOBALDEFPRIM_H_");
153 outglobaldefsprim.println("#define __GLOBALDEFPRIM_H_");
154 outglobaldefsprim.println("");
155 outglobaldefsprim.println("struct global_defsprim_t {");
157 outclassdefs.println("#ifndef __CLASSDEF_H_");
158 outclassdefs.println("#define __CLASSDEF_H_");
159 outputClassDeclarations(outclassdefs, outglobaldefs, outglobaldefsprim);
161 // Output function prototypes and structures for parameters
162 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
163 while(it.hasNext()) {
164 ClassDescriptor cn=(ClassDescriptor)it.next();
165 generateCallStructs(cn, outclassdefs, outstructs, outmethodheader, outglobaldefs, outglobaldefsprim);
167 outclassdefs.println("#include \"globaldefs.h\"");
168 outclassdefs.println("#include \"globaldefsprim.h\"");
169 outclassdefs.println("#endif");
170 outclassdefs.close();
172 outglobaldefs.println("};");
173 outglobaldefs.println("");
174 outglobaldefs.println("extern struct global_defs_t * global_defs_p;");
175 outglobaldefs.println("#endif");
176 outglobaldefs.flush();
177 outglobaldefs.close();
179 outglobaldefsprim.println("};");
180 outglobaldefsprim.println("");
181 outglobaldefsprim.println("extern struct global_defsprim_t * global_defsprim_p;");
182 outglobaldefsprim.println("#endif");
183 outglobaldefsprim.flush();
184 outglobaldefsprim.close();
187 /* Map flags to integers */
188 /* The runtime keeps track of flags using these integers */
189 it=state.getClassSymbolTable().getDescriptorsIterator();
190 while(it.hasNext()) {
191 ClassDescriptor cn=(ClassDescriptor)it.next();
195 generateTaskStructs(outstructs, outmethodheader);
197 /* Outputs generic task structures if this is a task
199 outputTaskTypes(outtask);
203 // an opportunity for subclasses to do extra
205 preCodeGenInitialization();
208 /* Build the actual methods */
209 outputMethods(outmethod);
212 // opportunity for subclasses to gen extra code
213 additionalCodeGen(outmethodheader,
219 /* Output code for tasks */
220 outputTaskCode(outtaskdefs, outmethod);
222 /* Record maximum number of task parameters */
223 outstructs.println("#define MAXTASKPARAMS "+maxtaskparams);
224 } else if (state.main!=null) {
225 /* Generate main method */
226 outputMainMethod(outmethod);
229 /* Generate information for task with optional parameters */
230 if (state.TASK&&state.OPTIONAL) {
231 generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors());
232 outoptionalarrays.close();
235 /* Output structure definitions for repair tool */
236 if (state.structfile!=null) {
237 buildRepairStructs(outrepairstructs);
238 outrepairstructs.close();
242 outmethodheader.println("#endif");
243 outmethodheader.close();
245 outstructs.println("#endif");
250 postCodeGenCleanUp();
253 /* This method goes though the call graph and check which methods are really
254 * invoked and should be generated
256 protected void checkMethods2Gen() {
257 MethodDescriptor md=(state.main==null)?null:typeutil.getMain();
260 // check the methods to be generated
261 state.setGenAllMethods(false);
263 // generate all methods
266 this.state.addMethod2gen(md);
268 Iterator it_classes = this.state.getClassSymbolTable().getDescriptorsIterator();
269 while(it_classes.hasNext()) {
270 ClassDescriptor cd = (ClassDescriptor)it_classes.next();
271 Iterator it_methods = cd.getMethodTable().getDescriptorsIterator();
272 while(it_methods.hasNext()) {
273 md = (MethodDescriptor)it_methods.next();
274 if(md.isStaticBlock() || md.getModifiers().isNative() || this.callgraph.getCallerSet(md).size() > 0
275 || (cd.getSymbol().equals("Thread") && md.getSymbol().equals("staticStart"))) {
276 this.state.addMethod2gen(md);
283 /* This method goes though the call graph and tag those methods that are
284 * invoked inside static blocks
286 protected void tagMethodInvokedByStaticBlock() {
287 Iterator it_sclasses = this.state.getSClassSymbolTable().getDescriptorsIterator();
288 MethodDescriptor current_md=null;
289 HashSet tovisit=new HashSet();
290 HashSet visited=new HashSet();
292 while(it_sclasses.hasNext()) {
293 ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
294 MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
300 while(!tovisit.isEmpty()) {
301 current_md=(MethodDescriptor)tovisit.iterator().next();
302 tovisit.remove(current_md);
303 visited.add(current_md);
304 Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
305 while(it_callee.hasNext()) {
306 Descriptor d = (Descriptor)it_callee.next();
307 if(d instanceof MethodDescriptor) {
308 if(!visited.contains(d)) {
309 ((MethodDescriptor)d).setIsInvokedByStatic(true);
317 /* This code generates code for each static block and static field
319 protected void outputStaticBlocks(PrintWriter outmethod) {
320 // execute all the static blocks and all the static field initializations
321 // execute all the static blocks and all the static field initializations
322 SymbolTable sctbl = this.state.getSClassSymbolTable();
323 Iterator it_sclasses = sctbl.getDescriptorsIterator();
324 if(it_sclasses.hasNext()) {
325 while(it_sclasses.hasNext()) {
326 ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next();
327 MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks");
329 outmethod.println(" {");
330 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
331 outmethod.print(" struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
332 outmethod.println("0, NULL};");
333 outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
335 outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
337 outmethod.println(" }");
343 /* This code generates code to create a Class object for each class for
346 protected void outputClassObjects(PrintWriter outmethod) {
347 // for each class, initialize its Class object
348 SymbolTable ctbl = this.state.getClassSymbolTable();
349 for(Iterator it_classes = ctbl.getDescriptorsIterator();it_classes.hasNext();) {
350 ClassDescriptor t_cd = (ClassDescriptor)it_classes.next();
351 outmethod.println(" {");
352 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
353 outmethod.println(" struct garbagelist dummy={0,NULL};");
354 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new(&dummy, " + typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
356 outmethod.println(" global_defs_p->"+t_cd.getSafeSymbol()+"classobj = allocate_new("+typeutil.getClass(TypeUtil.ObjectClass).getId() + ");");
357 outmethod.println(" }");
361 /* This code just generates the main C method for java programs.
362 * The main C method packs up the arguments into a string array
363 * and passes it to the java main method. */
365 protected void outputMainMethod(PrintWriter outmethod) {
366 outmethod.println("int main(int argc, const char *argv[]) {");
367 outmethod.println(" int i;");
368 outmethod.println(" global_defs_p=calloc(1, sizeof(struct global_defs_t));");
369 outmethod.println(" global_defsprim_p=calloc(1, sizeof(struct global_defsprim_t));");
370 if (GENERATEPRECISEGC) {
371 outmethod.println(" global_defs_p->size="+globaldefscount+";");
372 outmethod.println(" for(i=0;i<"+globaldefscount+";i++) {");
373 outmethod.println(" ((struct garbagelist *)global_defs_p)->array[i]=NULL;");
374 outmethod.println(" }");
376 outputStaticBlocks(outmethod);
377 outputClassObjects(outmethod);
380 additionalCodeAtTopOfMain(outmethod);
383 outmethod.println("initializethreads();");
386 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
387 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
389 outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
391 outmethod.println(" for(i=1;i<argc;i++) {");
392 outmethod.println(" int length=strlen(argv[i]);");
394 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
395 outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
397 outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
399 outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;");
400 outmethod.println(" }");
402 MethodDescriptor md=typeutil.getMain();
403 ClassDescriptor cd=typeutil.getMainClass();
405 outmethod.println(" {");
406 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
407 outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
408 outmethod.println("1, NULL,"+"stringarray};");
409 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
411 outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);");
413 outmethod.println(" }");
416 outmethod.println("pthread_mutex_lock(&gclistlock);");
417 outmethod.println("threadcount--;");
418 outmethod.println("pthread_cond_signal(&gccond);");
419 outmethod.println("pthread_mutex_unlock(&gclistlock);");
422 if (state.EVENTMONITOR) {
423 outmethod.println("dumpdata();");
427 outmethod.println("pthread_exit(NULL);");
430 additionalCodeAtBottomOfMain(outmethod);
432 outmethod.println("}");
435 /* This method outputs code for each task. */
437 protected void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) {
438 /* Compile task based program */
439 outtaskdefs.println("#include \"task.h\"");
440 outtaskdefs.println("#include \"methodheaders.h\"");
441 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
442 while(taskit.hasNext()) {
443 TaskDescriptor td=(TaskDescriptor)taskit.next();
444 FlatMethod fm=state.getMethodFlat(td);
445 generateFlatMethod(fm, outmethod);
446 generateTaskDescriptor(outtaskdefs, fm, td);
449 //Output task descriptors
450 taskit=state.getTaskSymbolTable().getDescriptorsIterator();
451 outtaskdefs.println("struct taskdescriptor * taskarray[]= {");
453 while(taskit.hasNext()) {
454 TaskDescriptor td=(TaskDescriptor)taskit.next();
458 outtaskdefs.println(",");
459 outtaskdefs.print("&task_"+td.getSafeSymbol());
461 outtaskdefs.println("};");
463 outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";");
467 /* This method outputs most of the methods.c file. This includes
468 * some standard includes and then an array with the sizes of
469 * objets and array that stores supertype and then the code for
470 * the Java methods.. */
471 protected void outputMethods(PrintWriter outmethod) {
472 outmethod.println("#include \"methodheaders.h\"");
473 outmethod.println("#include \"virtualtable.h\"");
474 outmethod.println("#include \"runtime.h\"");
476 // always include: compiler directives will leave out
477 // instrumentation when option is not set
478 outmethod.println("#include \"coreprof/coreprof.h\"");
480 if (state.FASTCHECK) {
481 outmethod.println("#include \"localobjects.h\"");
483 if(state.MULTICORE) {
485 outmethod.println("#include \"task.h\"");
487 outmethod.println("#include \"multicoreruntime.h\"");
488 outmethod.println("#include \"runtime_arch.h\"");
490 if (state.THREAD||state.DSM||state.SINGLETM) {
491 outmethod.println("#include <thread.h>");
494 outmethod.println("#include \"thread.h\"");
496 if (state.main!=null) {
497 outmethod.println("#include <string.h>");
499 if (state.CONSCHECK) {
500 outmethod.println("#include \"checkers.h\"");
504 additionalIncludesMethodsImplementation(outmethod);
506 outmethod.println("struct global_defs_t * global_defs_p;");
507 outmethod.println("struct global_defsprim_t * global_defsprim_p;");
508 //Store the sizes of classes & array elements
509 generateSizeArray(outmethod);
511 //Store table of supertypes
512 generateSuperTypeTable(outmethod);
514 //Store the layout of classes
515 generateLayoutStructs(outmethod);
518 additionalCodeAtTopMethodsImplementation(outmethod);
520 generateMethods(outmethod);
523 protected void generateMethods(PrintWriter outmethod) {
524 /* Generate code for methods */
525 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
526 while(classit.hasNext()) {
527 ClassDescriptor cn=(ClassDescriptor)classit.next();
528 Iterator methodit=cn.getMethods();
529 while(methodit.hasNext()) {
530 /* Classify parameters */
531 MethodDescriptor md=(MethodDescriptor)methodit.next();
532 if(!this.state.genAllMethods) {
533 boolean foundmatch = false;
534 Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
535 for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
536 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
537 if (md.matches(matchmd)) {
546 FlatMethod fm=state.getMethodFlat(md);
547 if (!md.getModifiers().isNative()) {
548 generateFlatMethod(fm, outmethod);
554 protected void outputStructs(PrintWriter outstructs) {
555 outstructs.println("#ifndef STRUCTDEFS_H");
556 outstructs.println("#define STRUCTDEFS_H");
557 outstructs.println("#include \"classdefs.h\"");
558 outstructs.println("#ifndef INTPTR");
559 outstructs.println("#ifdef BIT64");
560 outstructs.println("#define INTPTR long");
561 outstructs.println("#else");
562 outstructs.println("#define INTPTR int");
563 outstructs.println("#endif");
564 outstructs.println("#endif");
567 additionalIncludesStructsHeader(outstructs);
570 /* Output #defines that the runtime uses to determine type
571 * numbers for various objects it needs */
572 outstructs.println("#define MAXCOUNT "+maxcount);
574 outstructs.println("#define STRINGARRAYTYPE "+
575 (state.getArrayNumber(
576 (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses()));
578 outstructs.println("#define OBJECTARRAYTYPE "+
579 (state.getArrayNumber(
580 (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses()));
583 outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId());
584 outstructs.println("#define CHARARRAYTYPE "+
585 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses()));
587 outstructs.println("#define BYTEARRAYTYPE "+
588 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses()));
590 outstructs.println("#define BYTEARRAYARRAYTYPE "+
591 (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses()));
593 outstructs.println("#define NUMCLASSES "+state.numClasses());
594 int totalClassSize = state.numClasses() + state.numArrays() + state.numInterfaces();
595 outstructs.println("#define TOTALNUMCLASSANDARRAY "+ totalClassSize);
597 outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId());
598 outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId());
599 outstructs.println("#define TAGARRAYTYPE "+
600 (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses()));
604 protected void outputClassDeclarations(PrintWriter outclassdefs, PrintWriter outglobaldefs, PrintWriter outglobaldefsprim) {
605 if (state.THREAD||state.DSM||state.SINGLETM)
606 outclassdefs.println("#include <pthread.h>");
607 outclassdefs.println("#ifndef INTPTR");
608 outclassdefs.println("#ifdef BIT64");
609 outclassdefs.println("#define INTPTR long");
610 outclassdefs.println("#else");
611 outclassdefs.println("#define INTPTR int");
612 outclassdefs.println("#endif");
613 outclassdefs.println("#endif");
615 outclassdefs.println("#include \"optionalstruct.h\"");
616 outclassdefs.println("struct "+arraytype+";");
617 /* Start by declaring all structs */
618 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
619 while(it.hasNext()) {
620 ClassDescriptor cn=(ClassDescriptor)it.next();
621 outclassdefs.println("struct "+cn.getSafeSymbol()+";");
623 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
624 // this class has static fields/blocks, need to add a global flag to
625 // indicate if its static fields have been initialized and/or if its
626 // static blocks have been executed
627 outglobaldefsprim.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
630 // for each class, create a global object
631 outglobaldefs.println(" struct ___Object___ *"+cn.getSafeSymbol()+"classobj;");
634 outclassdefs.println("");
635 //Print out definition for array type
636 outclassdefs.println("struct "+arraytype+" {");
637 outclassdefs.println(" int type;");
640 additionalClassObjectFields(outclassdefs);
643 if (state.EVENTMONITOR) {
644 outclassdefs.println(" int objuid;");
647 outclassdefs.println(" pthread_t tid;");
648 outclassdefs.println(" void * lockentry;");
649 outclassdefs.println(" int lockcount;");
652 outclassdefs.println(" int mutex;");
653 outclassdefs.println(" volatile int notifycount;");
654 outclassdefs.println(" volatile int objlock;");
655 if(state.MULTICOREGC) {
656 outclassdefs.println(" int marked;");
660 outclassdefs.println(" int flag;");
661 if(!state.MULTICORE) {
662 outclassdefs.println(" void * flagptr;");
664 outclassdefs.println(" int version;");
665 outclassdefs.println(" int * lock;"); // lock entry for this obj
666 outclassdefs.println(" int mutex;");
667 outclassdefs.println(" int lockcount;");
668 if(state.MULTICOREGC) {
669 outclassdefs.println(" int marked;");
673 outclassdefs.println(" int numfses;");
674 outclassdefs.println(" int * fses;");
678 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
679 printedfieldstbl.clear();
680 printExtraArrayFields(outclassdefs);
681 if (state.ARRAYPAD) {
682 outclassdefs.println(" int paddingforarray;");
685 outclassdefs.println(" int ___length___;");
686 outclassdefs.println("};\n");
689 // TODO add version for normal Java later
690 outclassdefs.println("");
691 //Print out definition for Class type
692 outclassdefs.println("struct Class {");
693 outclassdefs.println(" int type;");
696 additionalClassObjectFields(outclassdefs);
699 if (state.EVENTMONITOR) {
700 outclassdefs.println(" int objuid;");
703 outclassdefs.println(" pthread_t tid;");
704 outclassdefs.println(" void * lockentry;");
705 outclassdefs.println(" int lockcount;");
708 outclassdefs.println(" int mutex;");
709 outclassdefs.println(" volatile int notifycount;");
710 outclassdefs.println(" volatile int objlock;");
711 if(state.MULTICOREGC) {
712 outclassdefs.println(" int marked;");
716 outclassdefs.println(" int flag;");
717 if(!state.MULTICORE) {
718 outclassdefs.println(" void * flagptr;");
720 outclassdefs.println(" int version;");
721 outclassdefs.println(" int * lock;"); // lock entry for this obj
722 outclassdefs.println(" int mutex;");
723 outclassdefs.println(" int lockcount;");
724 if(state.MULTICOREGC) {
725 outclassdefs.println(" int marked;");
729 outclassdefs.println(" int numfses;");
730 outclassdefs.println(" int * fses;");
733 printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs, outglobaldefs, outglobaldefsprim);
734 printedfieldstbl.clear();
735 outclassdefs.println("};\n");
738 outclassdefs.println("");
739 outclassdefs.println("extern int classsize[];");
740 outclassdefs.println("extern int hasflags[];");
741 outclassdefs.println("extern unsigned INTPTR * pointerarray[];");
742 outclassdefs.println("extern int* supertypes[];");
743 outclassdefs.println("");
746 /** Prints out definitions for generic task structures */
748 protected void outputTaskTypes(PrintWriter outtask) {
749 outtask.println("#ifndef _TASK_H");
750 outtask.println("#define _TASK_H");
751 outtask.println("struct parameterdescriptor {");
752 outtask.println("int type;");
753 outtask.println("int numberterms;");
754 outtask.println("int *intarray;");
755 outtask.println("void * queue;");
756 outtask.println("int numbertags;");
757 outtask.println("int *tagarray;");
758 outtask.println("};");
760 outtask.println("struct taskdescriptor {");
761 outtask.println("void * taskptr;");
762 outtask.println("int numParameters;");
763 outtask.println(" int numTotal;");
764 outtask.println("struct parameterdescriptor **descriptorarray;");
765 outtask.println("char * name;");
766 outtask.println("};");
767 outtask.println("extern struct taskdescriptor * taskarray[];");
768 outtask.println("extern numtasks;");
769 outtask.println("#endif");
773 protected void buildRepairStructs(PrintWriter outrepairstructs) {
774 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
775 while(classit.hasNext()) {
776 ClassDescriptor cn=(ClassDescriptor)classit.next();
777 outrepairstructs.println("structure "+cn.getSymbol()+" {");
778 outrepairstructs.println(" int __type__;");
780 outrepairstructs.println(" int __flag__;");
781 if(!state.MULTICORE) {
782 outrepairstructs.println(" int __flagptr__;");
785 printRepairStruct(cn, outrepairstructs);
786 outrepairstructs.println("}\n");
789 for(int i=0; i<state.numArrays(); i++) {
790 TypeDescriptor tdarray=arraytable[i];
791 TypeDescriptor tdelement=tdarray.dereference();
792 outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
793 outrepairstructs.println(" int __type__;");
794 printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
795 outrepairstructs.println(" int length;");
796 outrepairstructs.println("}\n");
800 protected void printRepairStruct(ClassDescriptor cn, PrintWriter output) {
801 ClassDescriptor sp=cn.getSuperDesc();
803 printRepairStruct(sp, output);
805 Vector fields=(Vector)fieldorder.get(cn);
807 for(int i=0; i<fields.size(); i++) {
808 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
809 if (fd.getType().isArray()) {
810 output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
811 } else if (fd.getType().isClass())
812 output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
813 else if (fd.getType().isFloat())
814 output.println(" int "+fd.getSymbol()+"; /* really float */");
816 output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
820 /** This method outputs TaskDescriptor information */
821 protected void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
822 for (int i=0; i<task.numParameters(); i++) {
823 VarDescriptor param_var=task.getParameter(i);
824 TypeDescriptor param_type=task.getParamType(i);
825 FlagExpressionNode param_flag=task.getFlag(param_var);
826 TagExpressionList param_tag=task.getTag(param_var);
829 if (param_flag==null) {
830 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
831 output.println("0x0, 0x0 };");
834 DNFFlag dflag=param_flag.getDNF();
835 dnfterms=dflag.size();
837 Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
838 output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
839 for(int j=0; j<dflag.size(); j++) {
842 Vector term=dflag.get(j);
845 for(int k=0; k<term.size(); k++) {
846 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
847 FlagDescriptor fd=dfa.getFlag();
848 boolean negated=dfa.getNegated();
849 int flagid=1<<((Integer)flags.get(fd)).intValue();
854 output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
856 output.println("};");
859 output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
861 for(int j=0; j<param_tag.numTags(); j++) {
864 /* for each tag we need */
865 /* which slot it is */
866 /* what type it is */
867 TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
868 TempDescriptor tmp=param_tag.getTemp(j);
869 int slot=fm.getTagInt(tmp);
870 output.println(slot+", "+state.getTagId(tvd.getTag()));
872 output.println("};");
874 output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
875 output.println("/* type */"+param_type.getClassDesc().getId()+",");
876 output.println("/* number of DNF terms */"+dnfterms+",");
877 output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
878 output.println("0,");
880 output.println("/* number of tags */"+param_tag.numTags()+",");
882 output.println("/* number of tags */ 0,");
883 output.println("parametertag_"+i+"_"+task.getSafeSymbol());
884 output.println("};");
888 output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
889 for (int i=0; i<task.numParameters(); i++) {
892 output.print("¶meter_"+i+"_"+task.getSafeSymbol());
894 output.println("};");
896 output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={");
897 output.println("&"+task.getSafeSymbol()+",");
898 output.println("/* number of parameters */" +task.numParameters() + ",");
899 int numtotal=task.numParameters()+fm.numTags();
900 output.println("/* number total parameters */" +numtotal + ",");
901 output.println("parameterdescriptors_"+task.getSafeSymbol()+",");
902 output.println("\""+task.getSymbol()+"\"");
903 output.println("};");
907 /** The buildVirtualTables method outputs the virtual dispatch
908 * tables for methods. */
910 protected void buildVirtualTables(PrintWriter outvirtual) {
911 Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
912 while(classit.hasNext()) {
913 ClassDescriptor cd=(ClassDescriptor)classit.next();
914 if (virtualcalls.getMethodCount(cd)>maxcount)
915 maxcount=virtualcalls.getMethodCount(cd);
917 MethodDescriptor[][] virtualtable=null;
918 virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
920 /* Fill in virtual table */
921 classit=state.getClassSymbolTable().getDescriptorsIterator();
922 while(classit.hasNext()) {
923 ClassDescriptor cd=(ClassDescriptor)classit.next();
924 if(cd.isInterface()) {
927 fillinRow(cd, virtualtable, cd.getId());
930 ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass);
931 Iterator arrayit=state.getArrayIterator();
932 while(arrayit.hasNext()) {
933 TypeDescriptor td=(TypeDescriptor)arrayit.next();
934 int id=state.getArrayNumber(td);
935 fillinRow(objectcd, virtualtable, id+state.numClasses());
938 outvirtual.print("void * virtualtable[]={");
939 boolean needcomma=false;
940 for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
941 for(int j=0; j<maxcount; j++) {
943 outvirtual.print(", ");
944 if (virtualtable[i][j]!=null) {
945 MethodDescriptor md=virtualtable[i][j];
946 outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
948 outvirtual.print("0");
952 outvirtual.println("");
954 outvirtual.println("};");
958 protected void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
959 /* Get inherited methods */
960 Iterator it_sifs = cd.getSuperInterfaces();
961 while(it_sifs.hasNext()) {
962 ClassDescriptor superif = (ClassDescriptor)it_sifs.next();
963 fillinRow(superif, virtualtable, rownum);
965 if (cd.getSuperDesc()!=null)
966 fillinRow(cd.getSuperDesc(), virtualtable, rownum);
967 /* Override them with our methods */
968 for(Iterator it=cd.getMethods(); it.hasNext(); ) {
969 MethodDescriptor md=(MethodDescriptor)it.next();
970 if (md.isStatic()||md.getReturnType()==null)
972 boolean foundmatch = false;
973 if(this.state.genAllMethods) {
976 Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
977 for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
978 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
979 if (md.matches(matchmd)) {
988 int methodnum = virtualcalls.getMethodNumber(md);
989 virtualtable[rownum][methodnum]=md;
993 /** Generate array that contains the sizes of class objects. The
994 * object allocation functions in the runtime use this
997 protected void generateSizeArray(PrintWriter outclassdefs) {
998 outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n");
999 generateSizeArrayExtensions(outclassdefs);
1001 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1002 cdarray=new ClassDescriptor[state.numClasses()];
1003 ifarray = new ClassDescriptor[state.numInterfaces()];
1005 int interfaceid = 0;
1006 while(it.hasNext()) {
1007 ClassDescriptor cd=(ClassDescriptor)it.next();
1008 if(cd.isInterface()) {
1009 ifarray[cd.getId()] = cd;
1011 cdarray[cd.getId()] = cd;
1015 arraytable=new TypeDescriptor[state.numArrays()];
1017 Iterator arrayit=state.getArrayIterator();
1018 while(arrayit.hasNext()) {
1019 TypeDescriptor td=(TypeDescriptor)arrayit.next();
1020 int id=state.getArrayNumber(td);
1024 /* Print out types */
1025 outclassdefs.println("/* ");
1026 for(int i=0; i<state.numClasses(); i++) {
1027 ClassDescriptor cd=cdarray[i];
1029 outclassdefs.println("NULL " + i);
1031 outclassdefs.println(cd +" "+i);
1035 for(int i=0; i<state.numArrays(); i++) {
1036 TypeDescriptor arraytd=arraytable[i];
1037 outclassdefs.println(arraytd.toPrettyString() +" "+(i+state.numClasses()));
1040 for(int i=0; i<state.numInterfaces(); i++) {
1041 ClassDescriptor ifcd = ifarray[i];
1042 outclassdefs.println(ifcd +" "+(i+state.numClasses()+state.numArrays()));
1045 outclassdefs.println("*/");
1048 outclassdefs.print("int classsize[]={");
1050 boolean needcomma=false;
1051 for(int i=0; i<state.numClasses(); i++) {
1053 outclassdefs.print(", ");
1055 outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
1057 outclassdefs.print("0");
1063 for(int i=0; i<state.numArrays(); i++) {
1065 outclassdefs.print(", ");
1066 TypeDescriptor tdelement=arraytable[i].dereference();
1067 if (tdelement.isArray()||tdelement.isClass()||tdelement.isNull())
1068 outclassdefs.print("sizeof(void *)");
1070 outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
1074 for(int i=0; i<state.numInterfaces(); i++) {
1076 outclassdefs.print(", ");
1077 outclassdefs.print("sizeof(struct "+ifarray[i].getSafeSymbol()+")");
1081 outclassdefs.println("};");
1083 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1085 outclassdefs.print("int typearray[]={");
1086 for(int i=0; i<state.numClasses(); i++) {
1087 ClassDescriptor cd=cdarray[i];
1088 ClassDescriptor supercd=i>0 ? cd.getSuperDesc() : null;
1089 if(supercd != null && supercd.isInterface()) {
1090 throw new Error("Super class can not be interfaces");
1093 outclassdefs.print(", ");
1095 outclassdefs.print("-1");
1097 outclassdefs.print(supercd.getId());
1101 for(int i=0; i<state.numArrays(); i++) {
1102 TypeDescriptor arraytd=arraytable[i];
1103 ClassDescriptor arraycd=arraytd.getClassDesc();
1104 if (arraycd==null) {
1106 outclassdefs.print(", ");
1107 outclassdefs.print(objectclass.getId());
1111 ClassDescriptor cd=arraycd.getSuperDesc();
1114 TypeDescriptor supertd=new TypeDescriptor(cd);
1115 supertd.setArrayCount(arraytd.getArrayCount());
1116 type=state.getArrayNumber(supertd);
1118 type+=state.numClasses();
1121 cd=cd.getSuperDesc();
1124 outclassdefs.print(", ");
1125 outclassdefs.print(type);
1129 for(int i=0; i<state.numInterfaces(); i++) {
1130 ClassDescriptor cd=ifarray[i];
1131 ClassDescriptor supercd=cd.getSuperDesc();
1132 if(supercd != null && supercd.isInterface()) {
1133 throw new Error("Super class can not be interfaces");
1136 outclassdefs.print(", ");
1138 outclassdefs.print("-1");
1140 outclassdefs.print(supercd.getId());
1144 outclassdefs.println("};");
1149 outclassdefs.print("int typearray2[]={");
1150 for(int i=0; i<state.numArrays(); i++) {
1151 TypeDescriptor arraytd=arraytable[i];
1152 ClassDescriptor arraycd=arraytd.getClassDesc();
1153 if (arraycd==null) {
1155 outclassdefs.print(", ");
1156 outclassdefs.print("-1");
1160 ClassDescriptor cd=arraycd.getSuperDesc();
1161 int level=arraytd.getArrayCount()-1;
1163 for(; level>0; level--) {
1164 TypeDescriptor supertd=new TypeDescriptor(objectclass);
1165 supertd.setArrayCount(level);
1166 type=state.getArrayNumber(supertd);
1168 type+=state.numClasses();
1173 outclassdefs.print(", ");
1174 outclassdefs.print(type);
1178 outclassdefs.println("};");
1181 /** Constructs params and temp objects for each method or task.
1182 * These objects tell the compiler which temps need to be
1185 protected void generateTempStructs(FlatMethod fm) {
1186 MethodDescriptor md=fm.getMethod();
1187 TaskDescriptor task=fm.getTask();
1188 ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++);
1190 paramstable.put(md, objectparams);
1192 paramstable.put(task, objectparams);
1194 for(int i=0; i<fm.numParameters(); i++) {
1195 TempDescriptor temp=fm.getParameter(i);
1196 TypeDescriptor type=temp.getType();
1197 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1198 objectparams.addPtr(temp);
1200 objectparams.addPrim(temp);
1203 for(int i=0; i<fm.numTags(); i++) {
1204 TempDescriptor temp=fm.getTag(i);
1205 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
1206 objectparams.addPtr(temp);
1208 objectparams.addPrim(temp);
1211 TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
1213 tempstable.put(md, objecttemps);
1215 tempstable.put(task, objecttemps);
1217 for(Iterator nodeit=fm.getNodeSet().iterator(); nodeit.hasNext(); ) {
1218 FlatNode fn=(FlatNode)nodeit.next();
1219 TempDescriptor[] writes=fn.writesTemps();
1220 for(int i=0; i<writes.length; i++) {
1221 TempDescriptor temp=writes[i];
1222 TypeDescriptor type=temp.getType();
1223 if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
1224 objecttemps.addPtr(temp);
1226 objecttemps.addPrim(temp);
1231 /** This method outputs the following information about classes
1233 * (1) For classes, what are the locations of pointers.
1234 * (2) For arrays, does the array contain pointers or primitives.
1235 * (3) For classes, does the class contain flags.
1238 protected void generateLayoutStructs(PrintWriter output) {
1239 Iterator it=state.getClassSymbolTable().getDescriptorsIterator();
1240 while(it.hasNext()) {
1241 ClassDescriptor cn=(ClassDescriptor)it.next();
1242 output.println("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
1243 Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
1245 while(allit.hasNext()) {
1246 FieldDescriptor fd=(FieldDescriptor)allit.next();
1250 TypeDescriptor type=fd.getType();
1254 output.print(count);
1255 allit=cn.getFieldTable().getAllDescriptorsIterator();
1256 while(allit.hasNext()) {
1257 FieldDescriptor fd=(FieldDescriptor)allit.next();
1261 TypeDescriptor type=fd.getType();
1263 output.println(",");
1264 output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
1265 fd.getSafeSymbol()+"))");
1268 output.println("};");
1270 output.println("unsigned INTPTR * pointerarray[]={");
1271 boolean needcomma=false;
1272 for(int i=0; i<state.numClasses(); i++) {
1273 ClassDescriptor cn=cdarray[i];
1275 output.println(",");
1278 output.print(cn.getSafeSymbol()+"_pointers");
1280 output.print("NULL");
1284 for(int i=0; i<state.numArrays(); i++) {
1286 output.println(", ");
1287 TypeDescriptor tdelement=arraytable[i].dereference();
1288 if (tdelement.isArray()||tdelement.isClass())
1289 output.print("((unsigned INTPTR *)1)");
1295 output.println("};");
1297 output.println("int hasflags[]={");
1298 for(int i=0; i<state.numClasses(); i++) {
1299 ClassDescriptor cn=cdarray[i];
1301 output.println(", ");
1303 if ((cn != null) && (cn.hasFlags()))
1308 output.println("};");
1311 private int checkarraysupertype(ClassDescriptor arraycd, TypeDescriptor arraytd) {
1314 TypeDescriptor supertd=new TypeDescriptor(arraycd);
1315 supertd.setArrayCount(arraytd.getArrayCount());
1316 type=state.getArrayNumber(supertd);
1321 ClassDescriptor cd = arraycd.getSuperDesc();
1323 type = checkarraysupertype(cd, arraytd);
1329 Iterator it_sifs = arraycd.getSuperInterfaces();
1330 while(it_sifs.hasNext()) {
1331 ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1332 type = checkarraysupertype(ifcd, arraytd);
1342 /** Print out table to give us supertypes */
1343 protected void generateSuperTypeTable(PrintWriter output) {
1344 ClassDescriptor objectclass=typeutil.getClass(TypeUtil.ObjectClass);
1345 for(int i=0; i<state.numClasses(); i++) {
1346 ClassDescriptor cn=cdarray[i];
1350 output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1351 boolean ncomma = false;
1353 if((cn != null) && (cn.getSuperDesc() != null)) {
1356 Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1357 while(it_sifs != null && it_sifs.hasNext()) {
1363 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1367 ClassDescriptor cdsuper=cn.getSuperDesc();
1368 output.print(cdsuper.getId());
1370 it_sifs = cn != null? cn.getSuperInterfaces() : null;
1371 while(it_sifs != null && it_sifs.hasNext()) {
1375 output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1378 output.println("};");
1381 for(int i=0; i<state.numArrays(); i++) {
1382 TypeDescriptor arraytd=arraytable[i];
1383 ClassDescriptor arraycd=arraytd.getClassDesc();
1384 output.print("int supertypes___arraytype___" + (i+state.numClasses()) + "[] = {");
1385 boolean ncomma = false;
1387 if (arraycd==null) {
1391 output.print(objectclass.getId());
1392 output.println("};");
1395 if((arraycd != null) && (arraycd.getSuperDesc() != null)) {
1398 Iterator it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1399 while(it_sifs != null && it_sifs.hasNext()) {
1405 if ((arraycd != null) && (arraycd.getSuperDesc()!=null)) {
1406 ClassDescriptor cd=arraycd.getSuperDesc();
1409 type = checkarraysupertype(cd, arraytd);
1411 type += state.numClasses();
1418 it_sifs = arraycd != null? arraycd.getSuperInterfaces() : null;
1419 while(it_sifs != null && it_sifs.hasNext()) {
1420 ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
1421 int type = checkarraysupertype(ifcd , arraytd);
1423 type += state.numClasses();
1429 output.println("};");
1432 for(int i=0; i<state.numInterfaces(); i++) {
1433 ClassDescriptor cn=ifarray[i];
1437 output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
1438 boolean ncomma = false;
1440 if((cn != null) && (cn.getSuperDesc() != null)) {
1443 Iterator it_sifs = cn != null? cn.getSuperInterfaces() : null;
1444 while(it_sifs != null && it_sifs.hasNext()) {
1450 if ((cn != null) && (cn.getSuperDesc()!=null)) {
1454 ClassDescriptor cdsuper=cn.getSuperDesc();
1455 output.print(cdsuper.getId());
1457 it_sifs = cn != null? cn.getSuperInterfaces() : null;
1458 while(it_sifs != null && it_sifs.hasNext()) {
1462 output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
1465 output.println("};");
1468 output.println("int* supertypes[]={");
1469 boolean needcomma=false;
1470 for(int i=0; i<state.numClasses(); i++) {
1471 ClassDescriptor cn=cdarray[i];
1473 output.println(",");
1476 output.print("supertypes" + cn.getSafeSymbol());
1482 for(int i=0; i<state.numArrays(); i++) {
1484 output.println(",");
1486 output.print("supertypes___arraytype___" + (i+state.numClasses()));
1489 for(int i=0; i<state.numInterfaces(); i++) {
1490 ClassDescriptor cn=ifarray[i];
1492 output.println(",");
1494 output.print("supertypes" + cn.getSafeSymbol());
1496 output.println("};");
1499 /** Force consistent field ordering between inherited classes. */
1501 protected void printClassStruct(ClassDescriptor cn, PrintWriter classdefout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1503 ClassDescriptor sp=cn.getSuperDesc();
1505 printClassStruct(sp, classdefout, /*globaldefout*/ null, null);
1507 SymbolTable sitbl = cn.getSuperInterfaceTable();
1508 Iterator it_sifs = sitbl.getDescriptorsIterator();
1509 while(it_sifs.hasNext()) {
1510 ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1511 printClassStruct(si, classdefout, /*globaldefout*/ null, null);
1514 if (!fieldorder.containsKey(cn)) {
1515 Vector fields=new Vector();
1516 fieldorder.put(cn,fields);
1518 Vector fieldvec=cn.getFieldVec();
1519 for(int i=0; i<fieldvec.size(); i++) {
1520 FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
1521 if((sp != null) && sp.getFieldTable().contains(fd.getSymbol())) {
1524 it_sifs = sitbl.getDescriptorsIterator();
1525 boolean hasprinted = false;
1526 while(it_sifs.hasNext()) {
1527 ClassDescriptor si = (ClassDescriptor)it_sifs.next();
1528 if(si.getFieldTable().contains(fd.getSymbol())) {
1534 // this field has been defined in the super class
1541 //Vector fields=(Vector)fieldorder.get(cn);
1543 Vector fields = cn.getFieldVec();
1545 for(int i=0; i<fields.size(); i++) {
1546 FieldDescriptor fd=(FieldDescriptor)fields.get(i);
1547 String fstring = fd.getSafeSymbol();
1548 if(printedfieldstbl.containsKey(fstring)) {
1549 printedfieldstbl.put(fstring, cn);
1552 printedfieldstbl.put(fstring, cn);
1554 if (fd.getType().isClass()
1555 && fd.getType().getClassDesc().isEnum()) {
1556 classdefout.println(" int " + fd.getSafeSymbol() + ";");
1557 } else if (fd.getType().isClass()||fd.getType().isArray()) {
1558 if (fd.isStatic()) {
1559 // TODO add version for normal Java later
1561 if(globaldefout != null) {
1562 if(fd.isVolatile()) {
1563 globaldefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1565 globaldefout.println(" struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1569 } else if (fd.isVolatile()) {
1571 classdefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
1573 classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
1575 } else if (fd.isStatic()) {
1576 // TODO add version for normal Java later
1578 if(globaldefout != null) {
1579 if(fd.isVolatile()) {
1580 globaldefprimout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1582 globaldefprimout.println(" "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1585 } else if (fd.isVolatile()) {
1587 classdefout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
1589 classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
1594 /* Map flags to integers consistently between inherited
1597 protected void mapFlags(ClassDescriptor cn) {
1598 ClassDescriptor sp=cn.getSuperDesc();
1602 if (!flagorder.containsKey(cn)) {
1603 Hashtable flags=new Hashtable();
1604 flagorder.put(cn,flags);
1606 Hashtable superflags=(Hashtable)flagorder.get(sp);
1607 Iterator superflagit=superflags.keySet().iterator();
1608 while(superflagit.hasNext()) {
1609 FlagDescriptor fd=(FlagDescriptor)superflagit.next();
1610 Integer number=(Integer)superflags.get(fd);
1611 flags.put(fd, number);
1612 if ((number.intValue()+1)>max)
1613 max=number.intValue()+1;
1617 Iterator flagit=cn.getFlags();
1618 while(flagit.hasNext()) {
1619 FlagDescriptor fd=(FlagDescriptor)flagit.next();
1620 if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
1621 flags.put(fd, new Integer(max++));
1627 /** This function outputs (1) structures that parameters are
1628 * passed in (when PRECISE GC is enabled) and (2) function
1629 * prototypes for the methods */
1631 protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout, PrintWriter globaldefout, PrintWriter globaldefprimout) {
1632 /* Output class structure */
1633 classdefout.println("struct "+cn.getSafeSymbol()+" {");
1634 classdefout.println(" int type;");
1637 additionalClassObjectFields(classdefout);
1640 if (state.EVENTMONITOR) {
1641 classdefout.println(" int objuid;");
1644 classdefout.println(" pthread_t tid;");
1645 classdefout.println(" void * lockentry;");
1646 classdefout.println(" int lockcount;");
1649 classdefout.println(" int mutex;");
1650 classdefout.println(" volatile int notifycount;");
1651 classdefout.println(" volatile int objlock;");
1652 if(state.MULTICOREGC) {
1653 classdefout.println(" int marked;");
1657 classdefout.println(" int flag;");
1658 if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
1659 classdefout.println(" void * flagptr;");
1660 } else if (state.MULTICORE) {
1661 classdefout.println(" int version;");
1662 classdefout.println(" int * lock;"); // lock entry for this obj
1663 classdefout.println(" int mutex;");
1664 classdefout.println(" int lockcount;");
1665 if(state.MULTICOREGC) {
1666 classdefout.println(" int marked;");
1669 if (state.OPTIONAL) {
1670 classdefout.println(" int numfses;");
1671 classdefout.println(" int * fses;");
1674 printClassStruct(cn, classdefout, globaldefout, globaldefprimout);
1675 printedfieldstbl.clear(); // = new Hashtable<String, ClassDescriptor>();
1676 classdefout.println("};\n");
1677 generateCallStructsMethods(cn, output, headersout);
1681 protected void generateCallStructsMethods(ClassDescriptor cn, PrintWriter output, PrintWriter headersout) {
1682 for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) {
1683 MethodDescriptor md=(MethodDescriptor)methodit.next();
1684 boolean foundmatch = false;
1685 if(this.state.genAllMethods) {
1688 Set vec_md = this.state.getMethod2gen().getSet(md.getSymbol());
1689 for(Iterator matchit=vec_md.iterator(); matchit.hasNext();) {
1690 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
1691 if (md.matches(matchmd)) {
1698 generateMethod(cn, md, headersout, output);
1703 protected void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, PrintWriter output) {
1704 /* Output parameter structure */
1705 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1706 if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1707 // generate the staticinit version
1708 String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1710 ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1711 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
1712 output.println(" int size;");
1713 output.println(" void * next;");
1714 for(int i=0; i<objectparams.numPointers(); i++) {
1715 TempDescriptor temp=objectparams.getPointer(i);
1716 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1717 output.println(" int " + temp.getSafeSymbol() + ";");
1719 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1722 output.println("};\n");
1725 ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1726 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
1727 output.println(" int size;");
1728 output.println(" void * next;");
1729 for(int i=0; i<objectparams.numPointers(); i++) {
1730 TempDescriptor temp=objectparams.getPointer(i);
1731 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1732 output.println(" int " + temp.getSafeSymbol() + ";");
1734 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1737 output.println("};\n");
1741 protected void generateMethod(ClassDescriptor cn, MethodDescriptor md, PrintWriter headersout, PrintWriter output) {
1742 FlatMethod fm=state.getMethodFlat(md);
1743 generateTempStructs(fm);
1745 ParamsObject objectparams=(ParamsObject) paramstable.get(md);
1746 TempObject objecttemps=(TempObject) tempstable.get(md);
1748 boolean printcomma = false;
1750 generateMethodParam(cn, md, output);
1752 if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1753 // generate the staticinit version
1754 String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1756 /* Output temp structure */
1757 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1758 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals {");
1759 output.println(" int size;");
1760 output.println(" void * next;");
1761 for(int i=0; i<objecttemps.numPointers(); i++) {
1762 TempDescriptor temp=objecttemps.getPointer(i);
1763 if (!temp.getType().isArray() && temp.getType().isNull())
1764 output.println(" void * "+temp.getSafeSymbol()+";");
1766 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1768 output.println("};\n");
1771 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+" 1");
1772 /* First the return type */
1773 if (md.getReturnType()!=null) {
1774 if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1775 headersout.println(" int ");
1776 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1777 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1779 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1781 //catch the constructor case
1782 headersout.print("void ");
1784 /* Next the method name */
1785 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
1787 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1788 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
1792 /* Output parameter list*/
1793 for(int i=0; i<objectparams.numPrimitives(); i++) {
1794 TempDescriptor temp=objectparams.getPrimitive(i);
1796 headersout.print(", ");
1798 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1799 headersout.print("int " + temp.getSafeSymbol());
1800 } else if (temp.getType().isClass()||temp.getType().isArray())
1801 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1803 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1805 headersout.println(");\n");
1808 /* Output temp structure */
1809 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1810 output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
1811 output.println(" int size;");
1812 output.println(" void * next;");
1813 for(int i=0; i<objecttemps.numPointers(); i++) {
1814 TempDescriptor temp=objecttemps.getPointer(i);
1815 if (!temp.getType().isArray() && temp.getType().isNull())
1816 output.println(" void * "+temp.getSafeSymbol()+";");
1818 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1820 output.println("};\n");
1823 /********* Output method declaration ***********/
1824 headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+" 1");
1825 /* First the return type */
1826 if (md.getReturnType()!=null) {
1827 if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
1828 headersout.println(" int ");
1829 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
1830 headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
1832 headersout.print(md.getReturnType().getSafeSymbol()+" ");
1834 //catch the constructor case
1835 headersout.print("void ");
1837 /* Next the method name */
1838 headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
1840 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1841 headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
1845 /* Output parameter list*/
1846 for(int i=0; i<objectparams.numPrimitives(); i++) {
1847 TempDescriptor temp=objectparams.getPrimitive(i);
1849 headersout.print(", ");
1851 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
1852 headersout.print("int " + temp.getSafeSymbol());
1853 } else if (temp.getType().isClass()||temp.getType().isArray())
1854 headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
1856 headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
1858 headersout.println(");\n");
1862 /** This function outputs (1) structures that parameters are
1863 * passed in (when PRECISE GC is enabled) and (2) function
1864 * prototypes for the tasks */
1866 protected void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
1867 /* Cycle through tasks */
1868 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
1870 while(taskit.hasNext()) {
1871 /* Classify parameters */
1872 TaskDescriptor task=(TaskDescriptor)taskit.next();
1873 FlatMethod fm=state.getMethodFlat(task);
1874 generateTempStructs(fm);
1876 ParamsObject objectparams=(ParamsObject) paramstable.get(task);
1877 TempObject objecttemps=(TempObject) tempstable.get(task);
1879 /* Output parameter structure */
1880 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1881 output.println("struct "+task.getSafeSymbol()+"_params {");
1882 output.println(" int size;");
1883 output.println(" void * next;");
1884 for(int i=0; i<objectparams.numPointers(); i++) {
1885 TempDescriptor temp=objectparams.getPointer(i);
1886 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1889 output.println("};\n");
1890 if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
1891 maxtaskparams=objectparams.numPointers()+fm.numTags();
1895 /* Output temp structure */
1896 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1897 output.println("struct "+task.getSafeSymbol()+"_locals {");
1898 output.println(" int size;");
1899 output.println(" void * next;");
1900 for(int i=0; i<objecttemps.numPointers(); i++) {
1901 TempDescriptor temp=objecttemps.getPointer(i);
1902 if (!temp.getType().isArray() && temp.getType().isNull())
1903 output.println(" void * "+temp.getSafeSymbol()+";");
1904 else if(temp.getType().isTag())
1905 output.println(" struct "+
1906 (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1908 output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
1910 output.println("};\n");
1913 /* Output task declaration */
1914 headersout.print("void " + task.getSafeSymbol()+"(");
1916 boolean printcomma=false;
1917 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1918 headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
1920 headersout.print("void * parameterarray[]");
1921 headersout.println(");\n");
1925 protected void generateFlatMethod(FlatMethod fm, PrintWriter output) {
1926 if (State.PRINTFLAT)
1927 System.out.println(fm.printMethod());
1928 MethodDescriptor md=fm.getMethod();
1929 TaskDescriptor task=fm.getTask();
1930 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
1931 ParamsObject objectparams=(ParamsObject)paramstable.get(md!=null ? md : task);
1933 if((md != null) && md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
1934 // generate a special static init version
1935 mgcstaticinit = true;
1936 String mdstring = md.getSafeMethodDescriptor() + "staticinit";
1938 generateHeader(fm, md!=null ? md : task,output);
1939 TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1941 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1942 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals "+localsprefix+"={");
1943 output.print(objecttemp.numPointers()+",");
1944 output.print(paramsprefix);
1945 for(int j=0; j<objecttemp.numPointers(); j++)
1946 output.print(", NULL");
1947 output.println("};");
1950 for(int i=0; i<objecttemp.numPrimitives(); i++) {
1951 TempDescriptor td=objecttemp.getPrimitive(i);
1952 TypeDescriptor type=td.getType();
1953 if (type.isNull() && !type.isArray())
1954 output.println(" void * "+td.getSafeSymbol()+";");
1955 else if (type.isClass() && type.getClassDesc().isEnum()) {
1956 output.println(" int " + td.getSafeSymbol() + ";");
1957 } else if (type.isClass()||type.isArray())
1958 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
1960 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
1963 additionalCodeAtTopFlatMethodBody(output, fm);
1965 /* Check to see if we need to do a GC if this is a
1966 * multi-threaded program...*/
1968 if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
1969 || this.state.MULTICOREGC) {
1970 //Don't bother if we aren't in recursive methods...The loops case will catch it
1971 if (callgraph.getAllMethods(md).contains(md)) {
1972 if (this.state.MULTICOREGC) {
1973 output.println("if(gcflag) gc("+localsprefixaddr+");");
1975 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
1980 generateCode(fm.getNext(0), fm, null, output);
1982 output.println("}\n\n");
1984 mgcstaticinit = false;
1987 generateHeader(fm, md!=null ? md : task,output);
1988 TempObject objecttemp=(TempObject) tempstable.get(md!=null ? md : task);
1990 if((md != null) && (md.isStaticBlock())) {
1991 mgcstaticinit = true;
1994 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
1996 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
1998 output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
1999 output.print(objecttemp.numPointers()+",");
2000 output.print(paramsprefix);
2001 for(int j=0; j<objecttemp.numPointers(); j++)
2002 output.print(", NULL");
2003 output.println("};");
2006 for(int i=0; i<objecttemp.numPrimitives(); i++) {
2007 TempDescriptor td=objecttemp.getPrimitive(i);
2008 TypeDescriptor type=td.getType();
2009 if (type.isNull() && !type.isArray())
2010 output.println(" void * "+td.getSafeSymbol()+";");
2011 else if (type.isClass() && type.getClassDesc().isEnum()) {
2012 output.println(" int " + td.getSafeSymbol() + ";");
2013 } else if (type.isClass()||type.isArray())
2014 output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
2016 output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
2019 additionalCodeAtTopFlatMethodBody(output, fm);
2021 /* Check to see if we need to do a GC if this is a
2022 * multi-threaded program...*/
2024 if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2025 || this.state.MULTICOREGC) {
2026 //Don't bother if we aren't in recursive methods...The loops case will catch it
2027 if (callgraph.getAllMethods(md).contains(md)) {
2028 if (this.state.MULTICOREGC) {
2029 output.println("if(gcflag) gc("+localsprefixaddr+");");
2031 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2036 if(fm.getMethod().isStaticBlock()) {
2037 // a static block, check if it has been executed
2038 output.println(" if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag != 0) {");
2039 output.println(" return;");
2040 output.println(" }");
2044 generateCode(fm.getNext(0), fm, null, output);
2046 output.println("}\n\n");
2048 mgcstaticinit = false;
2051 protected void generateCode(FlatNode first,
2053 Set<FlatNode> stopset,
2054 PrintWriter output) {
2056 /* Assign labels to FlatNode's if necessary.*/
2058 Hashtable<FlatNode, Integer> nodetolabel;
2060 nodetolabel=assignLabels(first, stopset);
2062 Set<FlatNode> storeset=null;
2063 HashSet<FlatNode> genset=null;
2064 HashSet<FlatNode> refset=null;
2065 Set<FlatNode> unionset=null;
2067 /* Do the actual code generation */
2068 FlatNode current_node=null;
2069 HashSet tovisit=new HashSet();
2070 HashSet visited=new HashSet();
2072 while(current_node!=null||!tovisit.isEmpty()) {
2073 if (current_node==null) {
2074 current_node=(FlatNode)tovisit.iterator().next();
2075 tovisit.remove(current_node);
2076 } else if (tovisit.contains(current_node)) {
2077 tovisit.remove(current_node);
2079 visited.add(current_node);
2080 if (nodetolabel.containsKey(current_node)) {
2081 output.println("L"+nodetolabel.get(current_node)+":");
2083 if (state.INSTRUCTIONFAILURE) {
2085 output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
2087 output.println("if ((--instructioncount)==0) injectinstructionfailure();");
2089 if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
2091 generateFlatNode(fm, current_node, output);
2093 if (state.OOOJAVA && stopset!=null) {
2094 assert first.getPrev(0) instanceof FlatSESEEnterNode;
2095 assert current_node instanceof FlatSESEExitNode;
2096 FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
2097 FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
2098 assert fsen.getFlatExit().equals(fsxn);
2099 assert fsxn.getFlatEnter().equals(fsen);
2101 if (current_node.kind()!=FKind.FlatReturnNode) {
2102 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2103 // a static block, check if it has been executed
2104 output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2107 output.println(" return;");
2110 } else if(current_node.numNext()==1) {
2112 if (state.OOOJAVA &&
2113 current_node.kind()==FKind.FlatSESEEnterNode) {
2114 FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
2115 generateFlatNode(fm, current_node, output);
2116 nextnode=fsen.getFlatExit().getNext(0);
2119 generateFlatNode(fm, current_node, output);
2120 nextnode=current_node.getNext(0);
2122 if (visited.contains(nextnode)) {
2123 output.println("goto L"+nodetolabel.get(nextnode)+";");
2126 current_node=nextnode;
2127 } else if (current_node.numNext()==2) {
2130 generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
2131 if (!visited.contains(current_node.getNext(1)))
2132 tovisit.add(current_node.getNext(1));
2133 if (visited.contains(current_node.getNext(0))) {
2134 output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
2137 current_node=current_node.getNext(0);
2138 } else throw new Error();
2142 protected Hashtable<FlatNode, Integer> assignLabels(FlatNode first, Set<FlatNode> lastset) {
2143 HashSet tovisit=new HashSet();
2144 HashSet visited=new HashSet();
2146 Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
2149 /*Assign labels first. A node needs a label if the previous
2150 * node has two exits or this node is a join point. */
2152 while(!tovisit.isEmpty()) {
2153 FlatNode fn=(FlatNode)tovisit.iterator().next();
2158 if(lastset!=null&&lastset.contains(fn)) {
2159 // if last is not null and matches, don't go
2160 // any further for assigning labels
2164 for(int i=0; i<fn.numNext(); i++) {
2165 FlatNode nn=fn.getNext(i);
2168 //1) Edge >1 of node
2169 nodetolabel.put(nn,new Integer(labelindex++));
2171 if (!visited.contains(nn)&&!tovisit.contains(nn)) {
2175 nodetolabel.put(nn,new Integer(labelindex++));
2182 /** Generate text string that corresponds to the TempDescriptor td. */
2183 protected String generateTemp(FlatMethod fm, TempDescriptor td) {
2184 MethodDescriptor md=fm.getMethod();
2185 TaskDescriptor task=fm.getTask();
2186 TempObject objecttemps=(TempObject) tempstable.get(md!=null ? md : task);
2188 if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) {
2189 return td.getSafeSymbol();
2192 if (objecttemps.isLocalPtr(td)) {
2193 return localsprefixderef+td.getSafeSymbol();
2196 if (objecttemps.isParamPtr(td)) {
2197 return paramsprefix+"->"+td.getSafeSymbol();
2205 protected void generateFlatNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
2206 if(state.LINENUM) printSourceLineNumber(fm,fn,output);
2207 additionalCodePreNode(fm, fn, output);
2210 case FKind.FlatAtomicEnterNode:
2211 generateFlatAtomicEnterNode(fm, (FlatAtomicEnterNode) fn, output);
2214 case FKind.FlatAtomicExitNode:
2215 generateFlatAtomicExitNode(fm, (FlatAtomicExitNode) fn, output);
2218 case FKind.FlatInstanceOfNode:
2219 generateFlatInstanceOfNode(fm, (FlatInstanceOfNode)fn, output);
2222 case FKind.FlatSESEEnterNode:
2223 generateFlatSESEEnterNode(fm, (FlatSESEEnterNode)fn, output);
2226 case FKind.FlatSESEExitNode:
2227 generateFlatSESEExitNode(fm, (FlatSESEExitNode)fn, output);
2230 case FKind.FlatWriteDynamicVarNode:
2231 generateFlatWriteDynamicVarNode(fm, (FlatWriteDynamicVarNode)fn, output);
2234 case FKind.FlatGlobalConvNode:
2235 generateFlatGlobalConvNode(fm, (FlatGlobalConvNode) fn, output);
2238 case FKind.FlatTagDeclaration:
2239 generateFlatTagDeclaration(fm, (FlatTagDeclaration) fn,output);
2242 case FKind.FlatCall:
2243 generateFlatCall(fm, (FlatCall) fn,output);
2246 case FKind.FlatFieldNode:
2247 generateFlatFieldNode(fm, (FlatFieldNode) fn,output);
2250 case FKind.FlatElementNode:
2251 generateFlatElementNode(fm, (FlatElementNode) fn,output);
2254 case FKind.FlatSetElementNode:
2255 generateFlatSetElementNode(fm, (FlatSetElementNode) fn,output);
2258 case FKind.FlatSetFieldNode:
2259 generateFlatSetFieldNode(fm, (FlatSetFieldNode) fn,output);
2263 generateFlatNew(fm, (FlatNew) fn,output);
2266 case FKind.FlatOpNode:
2267 generateFlatOpNode(fm, (FlatOpNode) fn,output);
2270 case FKind.FlatCastNode:
2271 generateFlatCastNode(fm, (FlatCastNode) fn,output);
2274 case FKind.FlatLiteralNode:
2275 generateFlatLiteralNode(fm, (FlatLiteralNode) fn,output);
2278 case FKind.FlatReturnNode:
2279 generateFlatReturnNode(fm, (FlatReturnNode) fn,output);
2283 output.println("/* nop */");
2286 case FKind.FlatGenReachNode:
2287 // this node is just for generating a reach graph
2288 // in disjointness analysis at a particular program point
2291 case FKind.FlatExit:
2292 output.println("/* exit */");
2295 case FKind.FlatBackEdge:
2296 generateFlatBackEdge(fm, (FlatBackEdge)fn, output);
2299 case FKind.FlatCheckNode:
2300 generateFlatCheckNode(fm, (FlatCheckNode) fn, output);
2303 case FKind.FlatFlagActionNode:
2304 generateFlatFlagActionNode(fm, (FlatFlagActionNode) fn, output);
2307 case FKind.FlatPrefetchNode:
2308 generateFlatPrefetchNode(fm, (FlatPrefetchNode) fn, output);
2311 case FKind.FlatOffsetNode:
2312 generateFlatOffsetNode(fm, (FlatOffsetNode)fn, output);
2319 additionalCodePostNode(fm, fn, output);
2322 public void generateFlatBackEdge(FlatMethod fm, FlatBackEdge fn, PrintWriter output) {
2323 if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
2324 || (this.state.MULTICOREGC)) {
2325 if(this.state.MULTICOREGC) {
2326 output.println("if (gcflag) gc("+localsprefixaddr+");");
2328 output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
2331 output.println("/* nop */");
2334 public void generateFlatOffsetNode(FlatMethod fm, FlatOffsetNode fofn, PrintWriter output) {
2335 output.println("/* FlatOffsetNode */");
2336 FieldDescriptor fd=fofn.getField();
2337 if(!fd.isStatic()) {
2338 output.println(generateTemp(fm, fofn.getDst())+ " = (short)(int) (&((struct "+fofn.getClassType().getSafeSymbol() +" *)0)->"+
2339 fd.getSafeSymbol()+");");
2341 output.println("/* offset */");
2344 public void generateFlatPrefetchNode(FlatMethod fm, FlatPrefetchNode fpn, PrintWriter output) {
2347 public void generateFlatGlobalConvNode(FlatMethod fm, FlatGlobalConvNode fgcn, PrintWriter output) {
2350 public void generateFlatInstanceOfNode(FlatMethod fm, FlatInstanceOfNode fion, PrintWriter output) {
2353 if (fion.getType().isArray()) {
2354 type=state.getArrayNumber(fion.getType())+state.numClasses();
2355 } else if (fion.getType().getClassDesc().isInterface()) {
2356 type=fion.getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2358 type=fion.getType().getClassDesc().getId();
2360 if (fion.getSrc().getType().isArray()) {
2361 otype=state.getArrayNumber(fion.getSrc().getType())+state.numClasses();
2362 } else if (fion.getSrc().getType().getClassDesc().isInterface()) {
2363 otype=fion.getSrc().getType().getClassDesc().getId()+state.numClasses()+state.numArrays();
2365 otype=fion.getSrc().getType().getClassDesc().getId();
2368 if (fion.getType().getSymbol().equals(TypeUtil.ObjectClass))
2369 output.println(generateTemp(fm, fion.getDst())+"=(" + generateTemp(fm,fion.getSrc()) + "!= NULL);");
2371 output.println(generateTemp(fm, fion.getDst())+"=instanceof("+generateTemp(fm,fion.getSrc())+","+type+");");
2375 public void generateFlatAtomicEnterNode(FlatMethod fm, FlatAtomicEnterNode faen, PrintWriter output) {
2378 public void generateFlatAtomicExitNode(FlatMethod fm, FlatAtomicExitNode faen, PrintWriter output) {
2381 public void generateFlatSESEEnterNode(FlatMethod fm,
2382 FlatSESEEnterNode fsen,
2383 PrintWriter output) {
2384 // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2385 // just skip over them and code generates exactly the same
2388 public void generateFlatSESEExitNode(FlatMethod fm,
2389 FlatSESEExitNode fsexn,
2390 PrintWriter output) {
2391 // if OOOJAVA flag is off, okay that SESE nodes are in IR graph,
2392 // just skip over them and code generates exactly the same
2395 public void generateFlatWriteDynamicVarNode(FlatMethod fm,
2396 FlatWriteDynamicVarNode fwdvn,
2397 PrintWriter output) {
2401 protected void generateFlatCheckNode(FlatMethod fm, FlatCheckNode fcn, PrintWriter output) {
2402 if (state.CONSCHECK) {
2403 String specname=fcn.getSpec();
2404 String varname="repairstate___";
2405 output.println("{");
2406 output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();");
2408 TempDescriptor[] temps=fcn.getTemps();
2409 String[] vars=fcn.getVars();
2410 for(int i=0; i<temps.length; i++) {
2411 output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";");
2414 output.println("if (doanalysis"+specname+"("+varname+")) {");
2415 output.println("free"+specname+"_state("+varname+");");
2416 output.println("} else {");
2417 output.println("/* Bad invariant */");
2418 output.println("free"+specname+"_state("+varname+");");
2419 output.println("abort_task();");
2420 output.println("}");
2421 output.println("}");
2425 protected void generateFlatCall(FlatMethod fm, FlatCall fc, PrintWriter output) {
2426 MethodDescriptor md=fc.getMethod();
2427 ParamsObject objectparams=(ParamsObject)paramstable.get(md);
2428 ClassDescriptor cn=md.getClassDesc();
2429 String mdstring = md.getSafeMethodDescriptor();
2430 if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2431 mdstring += "staticinit";
2434 // if the called method is a static block or a static method or a constructor
2435 // need to check if it can be invoked inside some static block
2436 if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
2437 ((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) {
2438 if(!md.isInvokedByStatic()) {
2439 System.err.println("Error: a method that is invoked inside a static block is not tagged!");
2441 // is a static block or is invoked in some static block
2442 ClassDescriptor cd = fm.getMethod().getClassDesc();
2444 // the same class, do nothing
2445 } else if(mgcstaticinit) {
2446 // generate static init check code if it has not done static init in main()
2447 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2448 // need to check if the class' static fields have been initialized and/or
2449 // its static blocks have been executed
2450 output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2451 if(cn.getNumStaticBlocks() != 0) {
2452 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2453 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2454 output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2455 output.println("0, NULL};");
2456 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2458 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2461 output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2463 output.println("}");
2467 if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
2468 output.println("{");
2469 // call MonitorEnter/MonitorExit on a class obj
2470 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2471 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2472 output.println("1," + localsprefixaddr + ", global_defs_p->"+ fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj};");
2473 output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2475 output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
2476 + md.getSafeMethodDescriptor() + "((struct ___Object___*)(global_defs_p->"
2477 + fc.getThis().getType().getClassDesc().getSafeSymbol() +"classobj));");
2479 output.println("}");
2483 output.println("{");
2484 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2485 output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params __parameterlist__={");
2486 output.print(objectparams.numPointers());
2487 output.print(", "+localsprefixaddr);
2488 if (md.getThis()!=null) {
2490 output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
2492 if (fc.getThis()!=null&&md.getThis()==null) {
2493 System.out.println("WARNING!!!!!!!!!!!!");
2494 System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
2498 for(int i=0; i<fc.numArgs(); i++) {
2499 Descriptor var=md.getParameter(i);
2500 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2501 if (objectparams.isParamPtr(paramtemp)) {
2502 TempDescriptor targ=fc.getArg(i);
2504 TypeDescriptor td=md.getParamType(i);
2506 output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ));
2508 output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ));
2511 output.println("};");
2516 if (fc.getReturnTemp()!=null)
2517 output.print(generateTemp(fm,fc.getReturnTemp())+"=");
2519 /* Do we need to do virtual dispatch? */
2520 if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
2522 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring);
2526 if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2527 output.print("int ");
2528 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2529 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2531 output.print(md.getReturnType().getSafeSymbol()+" ");
2532 output.print("(*)(");
2534 boolean printcomma=false;
2535 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2536 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * ");
2540 for(int i=0; i<objectparams.numPrimitives(); i++) {
2541 TempDescriptor temp=objectparams.getPrimitive(i);
2545 if (temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2546 output.print("int ");
2547 } else if (temp.getType().isClass()||temp.getType().isArray())
2548 output.print("struct " + temp.getType().getSafeSymbol()+" * ");
2550 output.print(temp.getType().getSafeSymbol());
2554 output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
2558 boolean needcomma=false;
2559 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2560 output.print("&__parameterlist__");
2564 if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2565 if (fc.getThis()!=null) {
2566 TypeDescriptor ptd=null;
2567 if(md.getThis() != null) {
2568 ptd = md.getThis().getType();
2570 ptd = fc.getThis().getType();
2574 if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
2576 } else if (ptd.isClass()&&!ptd.isArray())
2577 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2578 output.print(generateTemp(fm,fc.getThis()));
2583 for(int i=0; i<fc.numArgs(); i++) {
2584 Descriptor var=md.getParameter(i);
2585 TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
2586 if (objectparams.isParamPrim(paramtemp)) {
2587 TempDescriptor targ=fc.getArg(i);
2591 TypeDescriptor ptd=md.getParamType(i);
2592 if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
2594 } else if (ptd.isClass()&&!ptd.isArray())
2595 output.print("(struct "+ptd.getSafeSymbol()+" *) ");
2596 output.print(generateTemp(fm, targ));
2600 output.println(");");
2601 output.println(" }");
2604 protected boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
2605 if(thiscd.isInterface()) {
2606 // for interfaces, always need virtual dispatch
2609 Set subclasses=typeutil.getSubClasses(thiscd);
2610 if (subclasses==null)
2612 for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) {
2613 ClassDescriptor cd=(ClassDescriptor)classit.next();
2614 Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
2615 for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
2616 MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
2617 if (md.matches(matchmd))
2625 protected void generateFlatFieldNode(FlatMethod fm, FlatFieldNode ffn, PrintWriter output) {
2627 if(ffn.getField().isStatic()) {
2629 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2630 // is a static block or is invoked in some static block
2631 ClassDescriptor cd = fm.getMethod().getClassDesc();
2632 ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
2634 // the same class, do nothing
2635 } else if(mgcstaticinit) {
2636 // generate the static init check code if has not done the static init in main()
2637 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2638 // need to check if the class' static fields have been initialized and/or
2639 // its static blocks have been executed
2640 output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2641 if(cn.getNumStaticBlocks() != 0) {
2642 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2643 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2644 output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2645 output.println("0, NULL};");
2646 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2648 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2651 output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2653 output.println("}");
2657 // redirect to the global_defs_p structure
2658 if((ffn.getField().isStatic()) || (ffn.getSrc().getType().isClassNameRef())) {
2659 // reference to the static field with Class name
2660 if (ffn.getField().getType().isPtr())
2661 output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
2663 output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
2665 output.println(generateTemp(fm, ffn.getDst())+"=*"+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2667 } else if (ffn.getField().isEnum()) {
2668 // an Enum value, directly replace the field access as int
2669 output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";");
2671 output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
2676 protected void generateFlatSetFieldNode(FlatMethod fm, FlatSetFieldNode fsfn, PrintWriter output) {
2677 if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray())
2678 throw new Error("Can't set array length");
2679 if (state.FASTCHECK) {
2680 String dst=generateTemp(fm, fsfn.getDst());
2681 output.println("if(!"+dst+"->"+localcopystr+") {");
2682 /* Link object into list */
2683 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2684 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2686 output.println("COPY_OBJ("+dst+");");
2687 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2688 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2689 output.println("}");
2692 if(fsfn.getField().isStatic()) {
2694 if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
2695 // is a static block or is invoked in some static block
2696 ClassDescriptor cd = fm.getMethod().getClassDesc();
2697 ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
2699 // the same class, do nothing
2700 } else if(mgcstaticinit){
2701 // generate static init check code if has not done the static init in main()
2702 if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
2703 // need to check if the class' static fields have been initialized and/or
2704 // its static blocks have been executed
2705 output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
2706 if(cn.getNumStaticBlocks() != 0) {
2707 MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
2708 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2709 output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
2710 output.println("0, NULL};");
2711 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
2713 output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
2716 output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
2718 output.println("}");
2722 // redirect to the global_defs_p structure
2723 if((fsfn.getDst().getType().isClassNameRef()) || (fsfn.getField().isStatic())) {
2724 // reference to the static field with Class name
2725 if (fsfn.getField().getType().isPtr())
2726 output.println("global_defs_p->" +
2727 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2729 output.println("global_defsprim_p->" +
2730 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2732 output.println("*"+generateTemp(fm, fsfn.getDst())+"->"+
2733 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2736 output.println(generateTemp(fm, fsfn.getDst())+"->"+
2737 fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
2742 protected void generateFlatElementNode(FlatMethod fm, FlatElementNode fen, PrintWriter output) {
2743 TypeDescriptor elementtype=fen.getSrc().getType().dereference();
2746 if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2748 } else if (elementtype.isArray()||elementtype.isClass())
2751 type=elementtype.getSafeSymbol()+" ";
2753 if (this.state.ARRAYBOUNDARYCHECK && fen.needsBoundsCheck()) {
2754 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fen.getIndex())+") >= "+generateTemp(fm,fen.getSrc()) + "->___length___))");
2755 output.println("failedboundschk();");
2757 output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
2760 protected void generateFlatSetElementNode(FlatMethod fm, FlatSetElementNode fsen, PrintWriter output) {
2761 //TODO: need dynamic check to make sure this assignment is actually legal
2762 //Because Object[] could actually be something more specific...ie. Integer[]
2764 TypeDescriptor elementtype=fsen.getDst().getType().dereference();
2767 if (elementtype.isClass() && elementtype.getClassDesc().isEnum()) {
2769 } else if (elementtype.isArray()||elementtype.isClass() || (elementtype.isNull()))
2772 type=elementtype.getSafeSymbol()+" ";
2774 if (this.state.ARRAYBOUNDARYCHECK && fsen.needsBoundsCheck()) {
2775 output.println("if (unlikely(((unsigned int)"+generateTemp(fm, fsen.getIndex())+") >= "+generateTemp(fm,fsen.getDst()) + "->___length___))");
2776 output.println("failedboundschk();");
2778 if (state.FASTCHECK) {
2779 String dst=generateTemp(fm, fsen.getDst());
2780 output.println("if(!"+dst+"->"+localcopystr+") {");
2781 /* Link object into list */
2782 if (GENERATEPRECISEGC || this.state.MULTICOREGC)
2783 output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
2785 output.println("COPY_OBJ("+dst+");");
2786 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2787 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2788 output.println("}");
2790 output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
2794 protected void generateFlatNew(FlatMethod fm, FlatNew fn, PrintWriter output) {
2795 if (fn.getType().isArray()) {
2796 int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
2797 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2798 output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2800 output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
2803 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2804 output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
2806 output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
2809 if (state.FASTCHECK) {
2810 String dst=generateTemp(fm,fn.getDst());
2811 output.println(dst+"->___localcopy___=(struct ___Object___*)1;");
2812 output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
2813 output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
2817 protected void generateFlatTagDeclaration(FlatMethod fm, FlatTagDeclaration fn, PrintWriter output) {
2818 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2819 output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+localsprefixaddr+", "+state.getTagId(fn.getType())+");");
2821 output.println(generateTemp(fm,fn.getDst())+"=allocate_tag("+state.getTagId(fn.getType())+");");
2825 protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
2826 if (fon.getRight()!=null) {
2827 if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
2828 if (fon.getLeft().getType().isLong())
2829 output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2831 output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
2834 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
2835 } else if (fon.getOp().getOp()==Operation.ASSIGN)
2836 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2837 else if (fon.getOp().getOp()==Operation.UNARYPLUS)
2838 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
2839 else if (fon.getOp().getOp()==Operation.UNARYMINUS)
2840 output.println(generateTemp(fm, fon.getDest())+" = -"+generateTemp(fm, fon.getLeft())+";");
2841 else if (fon.getOp().getOp()==Operation.LOGIC_NOT)
2842 output.println(generateTemp(fm, fon.getDest())+" = !"+generateTemp(fm, fon.getLeft())+";");
2843 else if (fon.getOp().getOp()==Operation.COMP)
2844 output.println(generateTemp(fm, fon.getDest())+" = ~"+generateTemp(fm, fon.getLeft())+";");
2845 else if (fon.getOp().getOp()==Operation.ISAVAILABLE) {
2846 output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+"->fses==NULL;");
2848 output.println(generateTemp(fm, fon.getDest())+fon.getOp().toString()+generateTemp(fm, fon.getLeft())+";");
2851 protected void generateFlatCastNode(FlatMethod fm, FlatCastNode fcn, PrintWriter output) {
2852 /* TODO: Do type check here */
2853 if (fcn.getType().isArray()) {
2854 output.println(generateTemp(fm,fcn.getDst())+"=(struct ArrayObject *)"+generateTemp(fm,fcn.getSrc())+";");
2855 } else if (fcn.getType().isClass() && fcn.getType().getClassDesc().isEnum()) {
2856 output.println(generateTemp(fm,fcn.getDst())+"=(int)"+generateTemp(fm,fcn.getSrc())+";");
2857 } else if (fcn.getType().isClass())
2858 output.println(generateTemp(fm,fcn.getDst())+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc())+";");
2860 output.println(generateTemp(fm,fcn.getDst())+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc())+";");
2863 protected void generateFlatLiteralNode(FlatMethod fm, FlatLiteralNode fln, PrintWriter output) {
2864 if (fln.getValue()==null)
2865 output.println(generateTemp(fm, fln.getDst())+"=0;");
2866 else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
2867 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2868 output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2870 output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
2872 } else if (fln.getType().isBoolean()) {
2873 if (((Boolean)fln.getValue()).booleanValue())
2874 output.println(generateTemp(fm, fln.getDst())+"=1;");
2876 output.println(generateTemp(fm, fln.getDst())+"=0;");
2877 } else if (fln.getType().isChar()) {
2878 String st=FlatLiteralNode.escapeString(fln.getValue().toString());
2879 output.println(generateTemp(fm, fln.getDst())+"='"+st+"';");
2880 } else if (fln.getType().isLong()) {
2881 output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+"LL;");
2883 output.println(generateTemp(fm, fln.getDst())+"="+fln.getValue()+";");
2886 protected void generateFlatReturnNode(FlatMethod fm, FlatReturnNode frn, PrintWriter output) {
2887 if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
2888 // a static block, check if it has been executed
2889 output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
2893 if (frn.getReturnTemp()!=null) {
2894 if (frn.getReturnTemp().getType().isPtr())
2895 output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
2897 output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
2899 output.println("return;");
2903 protected void generateFlatCondBranch(FlatMethod fm, FlatCondBranch fcb, String label, PrintWriter output) {
2904 output.println("if (!"+generateTemp(fm, fcb.getTest())+") goto "+label+";");
2907 /** This method generates header information for the method or
2908 * task referenced by the Descriptor des. */
2909 protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output) {
2910 generateHeader(fm, des, output, false);
2913 protected void generateHeader(FlatMethod fm, Descriptor des, PrintWriter output, boolean addSESErecord) {
2915 ParamsObject objectparams=(ParamsObject)paramstable.get(des);
2916 MethodDescriptor md=null;
2917 TaskDescriptor task=null;
2918 if (des instanceof MethodDescriptor)
2919 md=(MethodDescriptor) des;
2921 task=(TaskDescriptor) des;
2922 String mdstring = md != null ? md.getSafeMethodDescriptor() : null;
2924 ClassDescriptor cn=md!=null ? md.getClassDesc() : null;
2926 if (md!=null&&md.getReturnType()!=null) {
2927 if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
2928 output.print("int ");
2929 } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
2930 output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
2932 output.print(md.getReturnType().getSafeSymbol()+" ");
2934 //catch the constructor case
2935 output.print("void ");
2937 if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
2938 mdstring += "staticinit";
2940 output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
2942 output.print(task.getSafeSymbol()+"(");
2944 boolean printcomma=false;
2945 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
2947 output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
2949 output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
2955 for(int i=0; i<objectparams.numPrimitives(); i++) {
2956 TempDescriptor temp=objectparams.getPrimitive(i);
2960 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2961 output.print("int " + temp.getSafeSymbol());
2962 } else if (temp.getType().isClass()||temp.getType().isArray())
2963 output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
2965 output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
2967 output.println(") {");
2968 } else if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
2969 /* Imprecise Task */
2970 output.println("void * parameterarray[]) {");
2971 /* Unpack variables */
2972 for(int i=0; i<objectparams.numPrimitives(); i++) {
2973 TempDescriptor temp=objectparams.getPrimitive(i);
2974 if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
2975 output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
2977 output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
2980 for(int i=0; i<fm.numTags(); i++) {
2981 TempDescriptor temp=fm.getTag(i);
2982 int offset=i+objectparams.numPrimitives();
2983 output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
2986 if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
2987 maxtaskparams=objectparams.numPrimitives()+fm.numTags();
2988 } else output.println(") {");
2991 public void generateFlatFlagActionNode(FlatMethod fm, FlatFlagActionNode ffan, PrintWriter output) {
2992 output.println("/* FlatFlagActionNode */");
2995 /* Process tag changes */
2996 Relation tagsettable=new Relation();
2997 Relation tagcleartable=new Relation();
2999 Iterator tagsit=ffan.getTempTagPairs();
3000 while (tagsit.hasNext()) {
3001 TempTagPair ttp=(TempTagPair) tagsit.next();
3002 TempDescriptor objtmp=ttp.getTemp();
3003 TagDescriptor tag=ttp.getTag();
3004 TempDescriptor tagtmp=ttp.getTagTemp();
3005 boolean tagstatus=ffan.getTagChange(ttp);
3007 tagsettable.put(objtmp, tagtmp);
3009 tagcleartable.put(objtmp, tagtmp);
3014 Hashtable flagandtable=new Hashtable();
3015 Hashtable flagortable=new Hashtable();
3017 /* Process flag changes */
3018 Iterator flagsit=ffan.getTempFlagPairs();
3019 while(flagsit.hasNext()) {
3020 TempFlagPair tfp=(TempFlagPair)flagsit.next();
3021 TempDescriptor temp=tfp.getTemp();
3022 Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
3023 FlagDescriptor flag=tfp.getFlag();
3025 //Newly allocate objects that don't set any flags case
3026 if (flagortable.containsKey(temp)) {
3030 flagortable.put(temp,new Integer(mask));
3032 int flagid=1<<((Integer)flagtable.get(flag)).intValue();
3033 boolean flagstatus=ffan.getFlagChange(tfp);
3036 if (flagortable.containsKey(temp)) {
3037 mask=((Integer)flagortable.get(temp)).intValue();
3040 flagortable.put(temp,new Integer(mask));
3042 int mask=0xFFFFFFFF;
3043 if (flagandtable.containsKey(temp)) {
3044 mask=((Integer)flagandtable.get(temp)).intValue();
3046 mask&=(0xFFFFFFFF^flagid);
3047 flagandtable.put(temp,new Integer(mask));
3053 HashSet flagtagset=new HashSet();
3054 flagtagset.addAll(flagortable.keySet());
3055 flagtagset.addAll(flagandtable.keySet());
3056 flagtagset.addAll(tagsettable.keySet());
3057 flagtagset.addAll(tagcleartable.keySet());
3059 Iterator ftit=flagtagset.iterator();
3060 while(ftit.hasNext()) {
3061 TempDescriptor temp=(TempDescriptor)ftit.next();
3064 Set tagtmps=tagcleartable.get(temp);
3065 if (tagtmps!=null) {
3066 Iterator tagit=tagtmps.iterator();
3067 while(tagit.hasNext()) {
3068 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3069 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3070 output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3072 output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3076 tagtmps=tagsettable.get(temp);
3077 if (tagtmps!=null) {
3078 Iterator tagit=tagtmps.iterator();
3079 while(tagit.hasNext()) {
3080 TempDescriptor tagtmp=(TempDescriptor)tagit.next();
3081 if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
3082 output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3084 output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
3089 int andmask=0xFFFFFFF;
3091 if (flagortable.containsKey(temp))
3092 ormask=((Integer)flagortable.get(temp)).intValue();
3093 if (flagandtable.containsKey(temp))
3094 andmask=((Integer)flagandtable.get(temp)).intValue();
3095 generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask);
3096 generateObjectDistribute(ffan, fm, temp, output);
3100 protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp,
3101 PrintWriter output, int ormask, int andmask) {
3102 if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
3103 output.println("flagorandinit("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3105 output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");");
3109 protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, TempDescriptor temp, PrintWriter output) {
3110 output.println("enqueueObject("+generateTemp(fm, temp)+");");
3113 void generateOptionalHeader(PrintWriter headers) {
3116 headers.println("#include \"task.h\"\n\n");
3117 headers.println("#ifndef _OPTIONAL_STRUCT_");
3118 headers.println("#define _OPTIONAL_STRUCT_");
3120 //STRUCT PREDICATEMEMBER
3121 headers.println("struct predicatemember{");
3122 headers.println("int type;");
3123 headers.println("int numdnfterms;");
3124 headers.println("int * flags;");
3125 headers.println("int numtags;");
3126 headers.println("int * tags;\n};\n\n");
3128 //STRUCT OPTIONALTASKDESCRIPTOR
3129 headers.println("struct optionaltaskdescriptor{");
3130 headers.println("struct taskdescriptor * task;");
3131 headers.println("int index;");
3132 headers.println("int numenterflags;");
3133 headers.println("int * enterflags;");
3134 headers.println("int numpredicatemembers;");
3135 headers.println("struct predicatemember ** predicatememberarray;");
3136 headers.println("};\n\n");
3138 //STRUCT TASKFAILURE
3139 headers.println("struct taskfailure {");
3140 headers.println("struct taskdescriptor * task;");
3141 headers.println("int index;");
3142 headers.println("int numoptionaltaskdescriptors;");
3143 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3145 //STRUCT FSANALYSISWRAPPER
3146 headers.println("struct fsanalysiswrapper{");
3147 headers.println("int flags;");
3148 headers.println("int numtags;");
3149 headers.println("int * tags;");
3150 headers.println("int numtaskfailures;");
3151 headers.println("struct taskfailure ** taskfailurearray;");
3152 headers.println("int numoptionaltaskdescriptors;");
3153 headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n");
3155 //STRUCT CLASSANALYSISWRAPPER
3156 headers.println("struct classanalysiswrapper{");
3157 headers.println("int type;");
3158 headers.println("int numotd;");
3159 headers.println("struct optionaltaskdescriptor ** otdarray;");
3160 headers.println("int numfsanalysiswrappers;");
3161 headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};");
3163 headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];");
3165 Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
3166 while(taskit.hasNext()) {
3167 TaskDescriptor td=(TaskDescriptor)taskit.next();
3168 headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";");
3173 //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE
3174 int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) {
3175 int predicateindex = 0;
3176 //iterate through the classes concerned by the predicate
3177 Set c_vard = predicate.vardescriptors;
3178 Hashtable<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
3181 for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext(); ) {
3182 VarDescriptor vard = (VarDescriptor)vard_it.next();
3183 TypeDescriptor typed = vard.getType();
3185 //generate for flags
3186 HashSet fen_hashset = predicate.flags.get(vard.getSymbol());
3187 output.println("int predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3189 if (fen_hashset!=null) {
3190 for (Iterator fen_it = fen_hashset.iterator(); fen_it.hasNext(); ) {
3191 FlagExpressionNode fen = (FlagExpressionNode)fen_it.next();
3193 DNFFlag dflag=fen.getDNF();
3194 numberterms+=dflag.size();
3196 Hashtable flags=(Hashtable)flagorder.get(typed.getClassDesc());
3198 for(int j=0; j<dflag.size(); j++) {
3200 output.println(",");
3201 Vector term=dflag.get(j);
3204 for(int k=0; k<term.size(); k++) {
3205 DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
3206 FlagDescriptor fd=dfa.getFlag();
3207 boolean negated=dfa.getNegated();
3208 int flagid=1<<((Integer)flags.get(fd)).intValue();
3213 output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
3218 output.println("};\n");
3221 TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
3222 output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3225 for(int j=0; j<tagel.numTags(); j++) {
3227 output.println(",");
3228 TempDescriptor tmp=tagel.getTemp(j);
3229 if (!slotnumber.containsKey(tmp)) {
3230 Integer slotint=new Integer(current_slot++);
3231 slotnumber.put(tmp,slotint);
3233 int slot=slotnumber.get(tmp).intValue();
3234 output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
3236 numtags = tagel.numTags();
3238 output.println("};");
3240 //store the result into a predicatemember struct
3241 output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3242 output.println("/*type*/"+typed.getClassDesc().getId()+",");
3243 output.println("/* number of dnf terms */"+numberterms+",");
3244 output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3245 output.println("/* number of tag */"+numtags+",");
3246 output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3247 output.println("};\n");
3252 //generate an array that stores the entire predicate
3253 output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3254 for( int j = 0; j<predicateindex; j++) {
3255 if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3256 else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3258 output.println("};\n");
3259 return predicateindex;
3263 void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution, Hashtable optionaltaskdescriptors) {
3264 generateOptionalHeader(headers);
3266 output.println("#include \"optionalstruct.h\"\n\n");
3267 output.println("#include \"stdlib.h\"\n");
3269 HashSet processedcd = new HashSet();
3271 Enumeration e = safeexecution.keys();
3272 while (e.hasMoreElements()) {
3275 ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
3276 Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times
3278 //Generate the struct of optionals
3279 Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3280 numotd = c_otd.size();
3281 if(maxotd<numotd) maxotd = numotd;
3282 if( !c_otd.isEmpty() ) {
3283 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3284 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3286 //generate the int arrays for the predicate
3287 Predicate predicate = otd.predicate;
3288 int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
3289 TreeSet<Integer> fsset=new TreeSet<Integer>();
3290 //iterate through possible FSes corresponding to
3291 //the state when entering
3293 for(Iterator fses = otd.enterflagstates.iterator(); fses.hasNext(); ) {
3294 FlagState fs = (FlagState)fses.next();
3296 for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3297 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3298 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3301 fsset.add(new Integer(flagid));
3302 //tag information not needed because tag
3303 //changes are not tolerated.
3306 output.println("int enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
3307 boolean needcomma=false;
3308 for(Iterator<Integer> it=fsset.iterator(); it.hasNext(); ) {
3311 output.println(it.next());
3314 output.println("};\n");
3317 //generate optionaltaskdescriptor that actually
3318 //includes exit fses, predicate and the task
3320 output.println("struct optionaltaskdescriptor optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
3321 output.println("&task_"+otd.td.getSafeSymbol()+",");
3322 output.println("/*index*/"+otd.getIndex()+",");
3323 output.println("/*number of enter flags*/"+fsset.size()+",");
3324 output.println("enterflag_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3325 output.println("/*number of members */"+predicateindex+",");
3326 output.println("predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3327 output.println("};\n");
3331 // if there are no optionals, there is no need to build the rest of the struct
3333 output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
3334 c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
3335 if( !c_otd.isEmpty() ) {
3336 boolean needcomma=false;
3337 for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
3338 OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
3340 output.println(",");
3342 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3345 output.println("};\n");
3347 //get all the possible flagstates reachable by an object
3348 Hashtable hashtbtemp = safeexecution.get(cdtemp);
3350 TreeSet fsts=new TreeSet(new FlagComparator(flaginfo));
3351 fsts.addAll(hashtbtemp.keySet());
3352 for(Iterator fsit=fsts.iterator(); fsit.hasNext(); ) {
3353 FlagState fs = (FlagState)fsit.next();
3356 //get the set of OptionalTaskDescriptors corresponding
3357 HashSet<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)hashtbtemp.get(fs);
3358 //iterate through the OptionalTaskDescriptors and
3359 //store the pointers to the optionals struct (see on
3360 //top) into an array
3362 output.println("struct optionaltaskdescriptor * optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[] = {");
3363 for(Iterator<OptionalTaskDescriptor> mos = ordertd(availabletasks).iterator(); mos.hasNext(); ) {
3364 OptionalTaskDescriptor mm = mos.next();
3366 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol());
3368 output.println("&optionaltaskdescriptor_"+mm.getuid()+"_"+cdtemp.getSafeSymbol()+",");
3371 output.println("};\n");
3373 //process flag information (what the flag after failure is) so we know what optionaltaskdescriptors to choose.
3376 for(Iterator flags = fs.getFlags(); flags.hasNext(); ) {
3377 FlagDescriptor flagd = (FlagDescriptor)flags.next();
3378 int id=1<<((Integer)flaginfo.get(flagd)).intValue();
3382 //process tag information
3385 boolean first = true;
3386 Enumeration tag_enum = fs.getTags();
3387 output.println("int tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3388 while(tag_enum.hasMoreElements()) {
3390 TagDescriptor tagd = (TagDescriptor)tag_enum.nextElement();
3394 output.println(", ");
3395 output.println("/*tagid*/"+state.getTagId(tagd));
3397 output.println("};");
3399 Set<TaskIndex> tiset=sa.getTaskIndex(fs);
3400 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3401 TaskIndex ti=itti.next();
3405 Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
3407 output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
3408 boolean needcomma=false;
3409 for(Iterator<OptionalTaskDescriptor> otdit=ordertd(otdset).iterator(); otdit.hasNext(); ) {
3410 OptionalTaskDescriptor otd=otdit.next();
3414 output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
3416 output.println("};");
3418 output.print("struct taskfailure taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+" = {");
3419 output.print("&task_"+ti.getTask().getSafeSymbol()+", ");
3420 output.print(ti.getIndex()+", ");
3421 output.print(otdset.size()+", ");
3422 output.print("optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array");
3423 output.println("};");
3426 tiset=sa.getTaskIndex(fs);
3427 boolean needcomma=false;
3429 output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
3430 for(Iterator<TaskIndex> itti=tiset.iterator(); itti.hasNext(); ) {
3431 TaskIndex ti=itti.next();
3432 if (ti.isRuntime()) {
3439 output.print("&taskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex());
3441 output.println("};\n");
3443 //Store the result in fsanalysiswrapper
3445 output.println("struct fsanalysiswrapper fsanalysiswrapper_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+"={");
3446 output.println("/*flag*/"+flagid+",");
3447 output.println("/* number of tags*/"+tagcounter+",");
3448 output.println("tags_FS"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3449 output.println("/* numtask failures */"+(tiset.size()-runtimeti)+",");
3450 output.println("taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+",");
3451 output.println("/* number of optionaltaskdescriptors */"+availabletasks.size()+",");
3452 output.println("optionaltaskdescriptorarray_FS"+fscounter+"_"+cdtemp.getSafeSymbol());
3453 output.println("};\n");
3457 //Build the array of fsanalysiswrappers
3458 output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {");
3459 boolean needcomma=false;
3460 for(int i = 0; i<fscounter; i++) {
3461 if (needcomma) output.print(",");
3462 output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
3465 output.println("};");
3467 //Build the classanalysiswrapper referring to the previous array
3468 output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
3469 output.println("/*type*/"+cdtemp.getId()+",");
3470 output.println("/*numotd*/"+numotd+",");
3471 output.println("otdarray"+cdtemp.getSafeSymbol()+",");
3472 output.println("/* number of fsanalysiswrappers */"+fscounter+",");
3473 output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
3474 processedcd.add(cdtemp);
3477 //build an array containing every classes for which code has been build
3478 output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
3479 for(int i=0; i<state.numClasses(); i++) {
3480 ClassDescriptor cn=cdarray[i];
3483 if ((cn != null) && (processedcd.contains(cn)))
3484 output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
3486 output.print("NULL");
3488 output.println("};");
3490 output.println("#define MAXOTD "+maxotd);
3491 headers.println("#endif");
3494 public List<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
3495 Relation r=new Relation();
3496 for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator(); otdit.hasNext(); ) {
3497 OptionalTaskDescriptor otd=otdit.next();
3498 TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
3502 LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
3503 for(Iterator it=r.keySet().iterator(); it.hasNext(); ) {
3504 Set s=r.get(it.next());
3505 for(Iterator it2=s.iterator(); it2.hasNext(); ) {
3506 OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
3514 // override these methods in a subclass of BuildCode
3515 // to generate code for additional systems
3516 protected void printExtraArrayFields(PrintWriter outclassdefs) {
3518 protected void outputTransCode(PrintWriter output) {
3520 protected void buildCodeSetup() {
3522 protected void generateSizeArrayExtensions(PrintWriter outclassdefs) {
3524 protected void additionalIncludesMethodsHeader(PrintWriter outmethodheader) {
3526 protected void preCodeGenInitialization() {
3528 protected void postCodeGenCleanUp() {
3530 protected void additionalCodeGen(PrintWriter outmethodheader,
3531 PrintWriter outstructs,
3532 PrintWriter outmethod) {
3534 protected void additionalCodeAtTopOfMain(PrintWriter outmethod) {
3536 protected void additionalCodeAtBottomOfMain(PrintWriter outmethod) {
3538 protected void additionalIncludesMethodsImplementation(PrintWriter outmethod) {
3540 protected void additionalIncludesStructsHeader(PrintWriter outstructs) {
3542 protected void additionalClassObjectFields(PrintWriter outclassdefs) {
3544 protected void additionalCodeAtTopMethodsImplementation(PrintWriter outmethod) {
3546 protected void additionalCodeAtTopFlatMethodBody(PrintWriter output, FlatMethod fm) {
3548 protected void additionalCodePreNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3550 protected void additionalCodePostNode(FlatMethod fm, FlatNode fn, PrintWriter output) {
3553 private void printSourceLineNumber(FlatMethod fm, FlatNode fn, PrintWriter output) {
3554 // we do not print out line number if no one explicitly set the number
3555 if(fn.getNumLine()!=-1){
3557 int lineNum=fn.getNumLine();
3559 // do not generate the line number if it is same as the previous one
3560 boolean needtoprint;
3561 if(fn.prev.size()==0){
3567 for(int i=0;i<fn.prev.size();i++){
3568 int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
3569 if(prevLineNum!=lineNum){
3575 output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());