fixed a compiler warning
[charm.git] / src / langs / jade / java.tree2.g
1 header {
2 //header
3 //Pass2:
4 // strip-mine MSA for loops
5 package jade;
6 }
7
8 {
9 //class preamble
10 import jade.JJ.J;
11 import jade.JJ.ASTJ;
12 import antlr.collections.ASTEnumeration;
13 }
14
15 /** Java 1.3 AST Recognizer Grammar
16  *
17  * Author: (see java.g preamble)
18  * Author: J. DeSouza
19  *
20  */
21 class JavaTreeParser2 extends TreeParser;
22
23 options {
24         importVocab = JavaTreeParser1;
25     buildAST = true;
26     ASTLabelType = "ASTJ";
27 }
28
29 compilationUnit
30         :       (p:packageDefinition)?
31                 (importDefinition)*
32                 (typeDefinition[p_AST])*
33         { if (p != null)
34             J.tmp.pop();
35         }
36         ;
37
38 packageDefinition
39         :       #( PACKAGE_DEF i:identifier { J.tmp.push(J.pE(i)); })
40         ;
41
42 importDefinition
43         :       #( IMPORT identifierStar )
44         ;
45
46 typeDefinition[AST parent]
47         :       #(c:CLASS_DEF modifiers IDENT { J.tmp.push(#IDENT.getText()); } extendsClause implementsClause
48             o:objBlock {
49                 if ( ((ASTJ)o).hasMain() ) {
50                     ((ASTJ)c_AST).status = true; // is a mainchare
51                     ((ASTJ)parent).status = true; // is a mainmodule
52                 }
53             }
54         ) { J.tmp.pop(); }
55         |       #(INTERFACE_DEF modifiers IDENT extendsClause interfaceBlock )
56         ;
57
58 typeSpec
59         :       #(TYPE typeSpecArray)
60         ;
61
62 typeSpecArray
63         :       #( ARRAY_DECLARATOR typeSpecArray )
64     |   #( TEMPLATE typeSpecArray )
65         |       type
66         ;
67
68 type:   identifier
69         |       builtInType
70         ;
71
72 builtInType
73     :   "void"
74     |   "boolean"
75     |   "byte"
76     |   "char"
77     |   "short"
78     |   "int"
79     |   "float"
80     |   "long"
81     |   "double"
82     ;
83
84 modifiers
85         :       #( MODIFIERS (modifier)* )
86         ;
87
88 modifier
89     :   "private"
90     |   "public"
91     |   "protected"
92     |   "static"
93     |   "transient"
94     |   "final"
95     |   "abstract"
96     |   "native"
97     |   "threadsafe"
98     |   "synchronized"
99 //     |   "const"
100     |   "volatile"
101         |       "strictfp"
102         |       "threaded"
103         |       "blocking"
104         |       "readonly"
105     ;
106
107 extendsClause
108         :       #(EXTENDS_CLAUSE (identifier)* )
109         ;
110
111 implementsClause
112         :       #(IMPLEMENTS_CLAUSE (identifier)* )
113         ;
114
115 interfaceBlock
116         :       #(      OBJBLOCK
117                         (       methodDecl
118                         |       variableDef[true]
119                         )*
120                 )
121         ;
122
123 objBlock
124         :       #(      OBJBLOCK
125                         (       ctorDef
126                         |       methodDef
127                         |       variableDef[true]
128                         |       typeDefinition[null]
129                         |       #(STATIC_INIT slist)
130                         |       #(INSTANCE_INIT slist)
131                         )*
132                 )
133         ;
134
135 ctorDef
136         :       #(CTOR_DEF modifiers
137             { J.startBlock(); }
138             methodHead
139             {J.tmp.push("");}
140             ctorSList
141             {
142                 J.endBlock();
143                 J.tmp.pop();
144             })
145         ;
146
147 methodDecl
148         :       #(METHOD_DEF modifiers typeSpec { J.startBlock(); } methodHead { J.endBlock(); })
149         ;
150
151 methodDef
152         :       #(METHOD_DEF modifiers typeSpec
153             { J.startBlock(); }
154             mh:methodHead
155             {
156                 J.tmp.push(new String(mh.getText()));
157             }
158             (slist)?
159             {
160                 J.tmp.pop();
161                 J.endBlock();
162             })
163         ;
164
165 variableDef[boolean classVarq]
166         :       #(v:VARIABLE_DEF m:modifiers typeSpec 
167             vd:variableDeclarator
168             varInitializer
169             {
170                 String varName = J.printVariableDeclarator(vd);
171                 if (!classVarq){
172                     J.localStackPush(varName, v);
173                 }
174             })
175         ;
176
177 parameterDef
178         :       #(p:PARAMETER_DEF modifiers typeSpec i:IDENT {
179                     J.localStackPush(i.getText(), p);
180             })
181         ;
182
183 objectinitializer
184         :       #(INSTANCE_INIT slist)
185         ;
186
187 variableDeclarator
188         :       IDENT
189         |       LBRACK variableDeclarator
190         ;
191
192 varInitializer
193         :       #(ASSIGN initializer)
194         |
195         ;
196
197 initializer
198         :       expression
199         |       arrayInitializer
200         ;
201
202 arrayInitializer
203         :       #(ARRAY_INIT (initializer)*)
204         ;
205
206 methodHead
207         :       IDENT #( PARAMETERS (parameterDef)* ) (throwsClause)?
208         ;
209
210 throwsClause
211         :       #( "throws" (identifier)* )
212         ;
213
214 templater
215     :  #( TEMPLATE (identifier|constant)+ )
216     ;
217
218 identifier
219         :       #( IDENT (templater)? )
220         |       #( DOT identifier #( IDENT (templater)? ) )
221         ;
222
223 identifierStar
224         :       IDENT
225         |       #( DOT identifier (STAR|IDENT) )
226         ;
227
228 ctorSList
229         :       #( SLIST (ctorCall)? (stat)* )
230         ;
231
232 slist
233         :       #( SLIST (stat)* )
234         ;
235
236 stat:   typeDefinition[null]
237         |       variableDef[false]
238         |       expression
239         |       #(LABELED_STAT IDENT stat)
240         |       #("if" expression stat (stat)? )
241         |       !#(     fo:"for"
242                         #(FOR_INIT (variableDef[false] | elist)?)
243                         #(FOR_CONDITION (expression)?)
244                         #(FOR_ITERATOR (elist)?)
245                         st:stat
246             {
247                 AST msa=null;
248                 // @@ skip for-analysis until it is ready for checkin
249                 if ( false && (msa=J.isMSAAccessAnywhere(fo))!=null) {
250                     // assume we have "for(i = n0; i <= n1; i++) x += A[i];"
251                     // need to know: i, n0, n1, A, typeof A
252                     // generate: p, pagesize, a
253                     // for (p = n0/pagesize; p <= n1/pagesize; p++) {
254                     //   double *a = (double*)GetPageBaseAddress(A, p);
255                     //   for (i= ((p==n0/pagesize)?n0%p:0); i <= ((p==n1/pagesize)?n1%pagesize:pagesize) )
256                     //     x += a[i];
257                     // }
258                     System.out.print("Found MSA loop: ");
259                     System.out.println(fo.toStringTree(0));
260
261                     J.Env e = new J.Env();
262                     e.put("arr", msa.getText());
263                     J.analyzeFor(fo, e);
264                     if (e.get("i2") != null) { // two-level loop
265
266                         // Set up some string variables to make code gen easier.
267                         String i = e.getStr("i1");
268                         String i0 = e.getStr("n01");  String iFinal = e.getStr("n11"); String iDelta = "1"; // @@
269                         String iOP = e.getStr("OP1");
270                         if (!iOP.equalsIgnoreCase("<="))
271                             J.fatalError(fo, "strip-mining only supports <= in for-condition outer loop. "+iOP);
272                         String j = e.getStr("i2");
273                         String j0 = e.getStr("n02");  String jFinal = e.getStr("n12"); String jDelta = "1"; // @@
274                         String jOP = e.getStr("OP2");
275                         if (!jOP.equalsIgnoreCase("<="))
276                             J.fatalError(fo, "strip-mining only supports <= in for-condition inner loop. "+jOP);
277                         String arr = e.getStr("arr");
278                         String arrType = "double"; // @@ hardcoded
279
280                         // Code generation
281                         StringBuffer s = new StringBuffer("");
282
283                         s.append("{\n");
284                         s.append("int accessMode=-1; int accessPattern=-1;\n");
285                         s.append("int MAJOR_SIZE=("+arr+".getArrayLayout() == MSA_ROW_MAJOR)?"+arr+".getCols():"+arr+".getRows();\n");
286                         s.append("int numEntriesPerPage="+arr+".getNumEntriesPerPage();\n");
287                         s.append("int i0="+i0+"; int iFinal="+iFinal+"; int iDelta="+iDelta+";\n");
288                         s.append("int j0="+j0+"; int jFinal="+jFinal+"; int jDelta="+jDelta+";\n");
289                         s.append("\n");
290                         s.append("int _i = i0; int _j = j0;\n");
291                         s.append("do {\n");
292                         s.append("int index = ("+arr+".getArrayLayout() == MSA_ROW_MAJOR)?"+arr+".getIndex(_i,_j):"+arr+".getIndex(_j,_i);\n"); // @@ should be accessPattern
293                         s.append("int indexSt = (index/numEntriesPerPage)*numEntriesPerPage;\n");
294                         s.append(arrType+" pi = addressof("+arr+".getPageBottom(index,Write_Fault));\n"); // @@ pointer, addressof, accessMode
295                         s.append("int indexEnd = indexSt + numEntriesPerPage -1;\n");
296                         s.append("int iSt = indexSt/MAJOR_SIZE;\n");
297                         s.append("int iN = indexEnd/MAJOR_SIZE;\n");
298                         s.append("int jSt= indexSt % MAJOR_SIZE;\n");
299                         s.append("int jN= indexEnd % MAJOR_SIZE;\n");
300                         s.append("\n");
301                         s.append("for (; _i"+iOP+"_JADE_MIN(iFinal, iN); _i+="+iDelta+") {\n");
302                         s.append("int jEnd;\n");
303                         s.append("if (_i==iN) jEnd = _JADE_MIN(jFinal, jN); else jEnd = jFinal;\n");
304                         s.append("if (_j>jFinal) _j = j0;\n");
305                         s.append("\n");
306                         s.append("for(; _j"+jOP+"jEnd; _j+=jDelta) {\n");
307                         s.append(arrType+" newname = addressof(pi[((_i-iSt)*MAJOR_SIZE+_j-jSt)]);\n"); // @@ pointer, addressof
308                         s.append(i+"=_i;"+j+"=_j;\n");
309                         s.append("{ body |= body; }\n"); // body of user loop
310                         s.append("}\n");
311                         s.append("if (_i==iN && _j>jN && _j<=jFinal)\n");
312                         s.append("break;\n");
313                         s.append("}\n");
314                         s.append("\n");
315                         s.append("if (_j>jFinal) _j = j0;\n");
316                         s.append("} while ( (_i<iFinal) || ( (_i==iFinal) && (_j<=jFinal) ));\n");
317                         s.append("}\n");
318
319 //                         s.append("{ int i1; int n01 = "+e.getStr("n01")+"; int n11 = "+e.getStr("n11")+";\n");
320 //                         s.append("int startPg1 = n01/pageSize; int endPg1 = n11/pageSize;\n");
321 //                         s.append("int i2; int n02 = "+e.getStr("n02")+"; int n12 = "+e.getStr("n12")+";\n");
322 //                         s.append("int startPg2 = n02/pageSize; int endPg2 = n12/pageSize;\n");
323 //                         s.append("for(p1=startPg1; p1<=endPg1; p1++)\n");
324 //                         s.append("for(p2=startPg2; p2<=endPg2; p2++) {\n");
325 //                         s.append("double newname[] = A.get(p1*pageSize, p2*pageSize);\n");
326 //                         s.append("for (i1=(p1==startPg1?(n01)%pageSize:0); i1" + e.get("OP1")
327 //                             + "(p1==endPg1?n11%pageSize:pageSize); i1++)\n");
328 //                         s.append("for (i2=(p2==startPg2?(n02)%pageSize:0); i2" + e.get("OP2")
329 //                             + "(p2==endPg2?n12%pageSize:pageSize); i2++)\n");
330 //                         s.append("{}}}\n");
331
332                         System.out.println(s);
333                         if (true) {
334                         // Prepare the new strip-mined code
335                         ASTJ newCode = J.parseString(s.toString());
336                         newCode.setVerboseStringConversion(true, getTokenNames());
337                         System.out.println(newCode.toStringTree(0));
338                         newCode.setVerboseStringConversion(false, null);
339
340                         // Find the body of the original code
341                         // For a two-level loop, we skip the inner loop
342                         ASTJ origBody = st;
343                         AST tmp3 = st.getFirstChild();
344                         while(tmp3 != null) {
345                             origBody = (ASTJ) tmp3;
346                             tmp3 = tmp3.getNextSibling();
347                         }
348
349                         // Find the location of the body in the new code
350                         ASTJ findBody = J.parseString("{ body |= body; }");
351                         ASTEnumeration bb = newCode.findAll(findBody);
352                         ASTJ theEmptyBody = (ASTJ)bb.nextNode();
353
354                         // Change the original body to use the new array name
355                         msa.setText("newname");
356                         // Replace the empty new body with the original one
357                         theEmptyBody.setFirstChild(astFactory.dupTree(origBody));
358
359 //                         AST lastChild = null;
360 //                         AST lastPointer = null;
361 //                         AST tmp3 = ttt.getFirstChild();
362 //                         while(tmp3!=null) {
363 //                             lastPointer = lastChild;
364 //                             lastChild = tmp3;
365 //                             tmp3 = tmp3.getNextSibling();
366 //                             if (tmp3 == null)
367 //                                 tmp3 = lastChild.getFirstChild();
368 //                         }
369 //                         System.out.println("last child = " + lastChild.toStringTree());
370
371 //                         // @@ We assume here that there is a sibling relationship between lastPointer and lastChild,
372 //                         // which is true in this case since we generate the code.
373 //                         lastPointer.setNextSibling(astFactory.dupTree(body));
374                         stat_AST = newCode;
375                         }
376                     } else {
377                         System.out.println("reached " + fo.toStringTree());
378                         stat_AST = fo;
379                     }
380
381
382 //                     String s = "{ int i = 0; for (i=0; i<10; i++) ; }";
383 //                     AST ttt = J.parseString(s);
384
385 //                     AST _e1 = #(#[LITERAL_for,"for"],
386 //                             #(#[FOR_INIT,"FOR_INIT"], #[EXPR,"EXPR"]),
387 //                             #[FOR_CONDITION,"FOR_CONDITION"],
388 //                             #[FOR_ITERATOR,"FOR_ITERATOR"],
389 //                             #[EXPR,"EXPR"]);
390 //                     System.out.println(fo.toStringTree());
391 //                     System.out.println();
392 //                     System.out.println(_e1.toStringTree());
393 //                     System.out.println(_e1.toStringList());
394 //                     System.out.println();
395                 } else {
396                     // duplicate the tree, but not its nextChild
397                     stat_AST = (ASTJ) astFactory.dupTree(fo);
398                 }
399
400             }
401                 )
402         |       #("while" expression stat)
403         |       #("do" stat expression)
404         |       #("break" (IDENT)? )
405         |       #("continue" (IDENT)? )
406         |       #("return" (expression)? )
407         |       #("switch" expression (caseGroup)*)
408         |       #("throw" expression)
409         |       #("synchronized" expression stat)
410         |       tryBlock
411         |       { J.startBlock(); } slist { J.endBlock(); } // nested SLIST
412         |       EMPTY_STAT
413         ;
414
415 caseGroup
416         :       #(CASE_GROUP (#("case" expression) | "default")+ slist)
417         ;
418
419 tryBlock
420         :       #( "try" slist (handler)* (#("finally" slist))? )
421         ;
422
423 handler
424         :       #( "catch" { J.startBlock(); } parameterDef slist { J.endBlock(); } )
425         ;
426
427 elist
428         :       #( ELIST (expression)* )
429         ;
430
431 colonExpression
432     :   #(COLON expression expression (expression)?)
433     |   expression
434     ;
435
436 expression
437         :       #(EXPR expr)
438         ;
439
440 expr:   #(QUESTION expr expr expr)      // trinary operator
441         |       #(ASSIGN expr expr)                     // binary operators...
442         |       #(PLUS_ASSIGN expr expr)
443         |       #(MINUS_ASSIGN expr expr)
444         |       #(STAR_ASSIGN expr expr)
445         |       #(DIV_ASSIGN expr expr)
446         |       #(MOD_ASSIGN expr expr)
447         |       #(SR_ASSIGN expr expr)
448         |       #(BSR_ASSIGN expr expr)
449         |       #(SL_ASSIGN expr expr)
450         |       #(BAND_ASSIGN expr expr)
451         |       #(BXOR_ASSIGN expr expr)
452         |       #(BOR_ASSIGN expr expr)
453         |       #(LOR expr expr)
454         |       #(LAND expr expr)
455         |       #(BOR expr expr)
456         |       #(BXOR expr expr)
457         |       #(BAND expr expr)
458         |       #(NOT_EQUAL expr expr)
459         |       #(EQUAL expr expr)
460         |       #(LT expr expr)
461         |       #(GT expr expr)
462         |       #(LE expr expr)
463         |       #(GE expr expr)
464         |       #(SL expr expr)
465         |       #(SR expr expr)
466         |       #(BSR expr expr)
467         |       #(PLUS expr expr)
468         |       #(MINUS expr expr)
469         |       #(DIV expr expr)
470         |       #(MOD expr expr)
471         |       #(STAR expr expr)
472         |       #(INC expr)
473         |       #(DEC expr)
474         |       #(POST_INC expr)
475         |       #(POST_DEC expr)
476         |       #(BNOT expr)
477         |       #(LNOT expr)
478         |       #("instanceof" expr expr)
479         |       #(UNARY_MINUS expr)
480         |       #(UNARY_PLUS expr)
481         |       primaryExpression
482         ;
483
484 primaryExpression
485     :   IDENT
486     |   #(      DOT
487                         (       expr
488                                 (       IDENT
489                                 |       arrayIndex
490                                 |       "this"
491                                 |       "class"
492                                 |       #( "new" IDENT elist )
493                                 |   "super"
494                                 )
495                         |       #(ARRAY_DECLARATOR typeSpecArray)
496                         |       builtInType ("class")?
497                         )
498                 )
499         |       arrayIndex
500         |       #(METHOD_CALL primaryExpression elist)
501         |       #(TYPECAST typeSpec expr)
502         |   newExpression
503         |   constant
504     |   "super"
505     |   "true"
506     |   "false"
507     |   "this"
508     |   "null"
509         |       typeSpec // type name used with instanceof
510         ;
511
512 ctorCall
513         :       #( CTOR_CALL elist )
514         |       #( SUPER_CTOR_CALL
515                         (       elist
516                         |       primaryExpression elist
517                         )
518                  )
519         ;
520
521 arrayIndex
522         :       #(INDEX_OP primaryExpression colonExpression)
523         ;
524
525 constant
526     :   NUM_INT
527     |   CHAR_LITERAL
528     |   STRING_LITERAL
529     |   NUM_FLOAT
530     |   NUM_DOUBLE
531     |   NUM_LONG
532     ;
533
534 newExpression
535         :       #(      "new" type
536                         (       newArrayDeclarator (arrayInitializer)?
537                         |       elist (objBlock)?
538                         )
539                 )
540                         
541         ;
542
543 newArrayDeclarator
544         :       #( ARRAY_DECLARATOR (newArrayDeclarator)? (expression)? )
545         ;